CNAME.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2024 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.ApplicationCommon;
  16. using MaxMind.GeoIP2.Model;
  17. using MaxMind.GeoIP2.Responses;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Net;
  21. using System.Text.Json;
  22. using System.Threading.Tasks;
  23. using TechnitiumLibrary;
  24. using TechnitiumLibrary.Net.Dns;
  25. using TechnitiumLibrary.Net.Dns.EDnsOptions;
  26. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  27. namespace GeoDistance
  28. {
  29. public sealed class CNAME : IDnsApplication, IDnsAppRecordRequestHandler
  30. {
  31. #region variables
  32. IDnsServer _dnsServer;
  33. MaxMind _maxMind;
  34. #endregion
  35. #region IDisposable
  36. bool _disposed;
  37. private void Dispose(bool disposing)
  38. {
  39. if (_disposed)
  40. return;
  41. if (disposing)
  42. {
  43. if (_maxMind is not null)
  44. _maxMind.Dispose();
  45. }
  46. _disposed = true;
  47. }
  48. public void Dispose()
  49. {
  50. Dispose(true);
  51. }
  52. #endregion
  53. #region private
  54. private static double GetDistance(double lat1, double long1, double lat2, double long2)
  55. {
  56. double d1 = lat1 * (Math.PI / 180.0);
  57. double num1 = long1 * (Math.PI / 180.0);
  58. double d2 = lat2 * (Math.PI / 180.0);
  59. double num2 = long2 * (Math.PI / 180.0) - num1;
  60. double d3 = Math.Pow(Math.Sin((d2 - d1) / 2.0), 2.0) + Math.Cos(d1) * Math.Cos(d2) * Math.Pow(Math.Sin(num2 / 2.0), 2.0);
  61. return 6376500.0 * (2.0 * Math.Atan2(Math.Sqrt(d3), Math.Sqrt(1.0 - d3)));
  62. }
  63. #endregion
  64. #region public
  65. public Task InitializeAsync(IDnsServer dnsServer, string config)
  66. {
  67. _dnsServer = dnsServer;
  68. _maxMind = MaxMind.Create(dnsServer);
  69. return Task.CompletedTask;
  70. }
  71. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, string zoneName, string appRecordName, uint appRecordTtl, string appRecordData)
  72. {
  73. DnsQuestionRecord question = request.Question[0];
  74. if (!question.Name.Equals(appRecordName, StringComparison.OrdinalIgnoreCase) && !appRecordName.StartsWith('*'))
  75. return Task.FromResult<DnsDatagram>(null);
  76. Location location = null;
  77. byte scopePrefixLength = 0;
  78. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  79. if (requestECS is not null)
  80. {
  81. if ((_maxMind.IspReader is not null) && _maxMind.IspReader.TryIsp(requestECS.Address, out IspResponse csIsp) && (csIsp.Network is not null))
  82. scopePrefixLength = (byte)csIsp.Network.PrefixLength;
  83. else if ((_maxMind.AsnReader is not null) && _maxMind.AsnReader.TryAsn(requestECS.Address, out AsnResponse csAsn) && (csAsn.Network is not null))
  84. scopePrefixLength = (byte)csAsn.Network.PrefixLength;
  85. else
  86. scopePrefixLength = requestECS.SourcePrefixLength;
  87. if (_maxMind.CityReader.TryCity(requestECS.Address, out CityResponse csResponse) && csResponse.Location.HasCoordinates)
  88. location = csResponse.Location;
  89. }
  90. if ((location is null) && _maxMind.CityReader.TryCity(remoteEP.Address, out CityResponse response) && response.Location.HasCoordinates)
  91. location = response.Location;
  92. using JsonDocument jsonDocument = JsonDocument.Parse(appRecordData);
  93. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  94. JsonElement jsonClosestServer = default;
  95. if (location is null)
  96. {
  97. if (jsonAppRecordData.GetArrayLength() > 0)
  98. jsonClosestServer = jsonAppRecordData[0];
  99. }
  100. else
  101. {
  102. double lastDistance = double.MaxValue;
  103. foreach (JsonElement jsonServer in jsonAppRecordData.EnumerateArray())
  104. {
  105. double lat = Convert.ToDouble(jsonServer.GetProperty("lat").GetString());
  106. double @long = Convert.ToDouble(jsonServer.GetProperty("long").GetString());
  107. double distance = GetDistance(lat, @long, location.Latitude.Value, location.Longitude.Value);
  108. if (distance < lastDistance)
  109. {
  110. lastDistance = distance;
  111. jsonClosestServer = jsonServer;
  112. }
  113. }
  114. }
  115. if (jsonClosestServer.ValueKind == JsonValueKind.Undefined)
  116. return Task.FromResult<DnsDatagram>(null);
  117. string cname = jsonClosestServer.GetPropertyValue("cname", null);
  118. if (string.IsNullOrEmpty(cname))
  119. return Task.FromResult<DnsDatagram>(null);
  120. IReadOnlyList<DnsResourceRecord> answers;
  121. if (question.Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase)) //check for zone apex
  122. answers = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.ANAME, DnsClass.IN, appRecordTtl, new DnsANAMERecordData(cname)) }; //use ANAME
  123. else
  124. answers = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, DnsClass.IN, appRecordTtl, new DnsCNAMERecordData(cname)) };
  125. EDnsOption[] options = null;
  126. if (requestECS is not null)
  127. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, scopePrefixLength, requestECS.Address);
  128. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answers, null, null, _dnsServer.UdpPayloadSize, EDnsHeaderFlags.None, options));
  129. }
  130. #endregion
  131. #region properties
  132. public string Description
  133. { get { return "Returns CNAME record of the server located geographically closest to the client using MaxMind GeoIP2 City database. Note that the app will return ANAME record for an APP record at zone apex. Use the geographic coordinates in decimal degrees (DD) form for the city the server is located in."; } }
  134. public string ApplicationRecordDataTemplate
  135. {
  136. get
  137. {
  138. return @"[
  139. {
  140. ""name"": ""server1-mumbai"",
  141. ""lat"": ""19.07283"",
  142. ""long"": ""72.88261"",
  143. ""cname"": ""mumbai.example.com""
  144. },
  145. {
  146. ""name"": ""server2-london"",
  147. ""lat"": ""51.50853"",
  148. ""long"": ""-0.12574"",
  149. ""cname"": ""london.example.com""
  150. }
  151. ]";
  152. }
  153. }
  154. #endregion
  155. }
  156. }