CNAME.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2023 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. Location location = null;
  74. bool ecsUsed = false;
  75. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  76. if (requestECS is not null)
  77. {
  78. if (_maxMind.DatabaseReader.TryCity(requestECS.Address, out CityResponse csResponse) && csResponse.Location.HasCoordinates)
  79. {
  80. ecsUsed = true;
  81. location = csResponse.Location;
  82. }
  83. }
  84. if ((location is null) && _maxMind.DatabaseReader.TryCity(remoteEP.Address, out CityResponse response) && response.Location.HasCoordinates)
  85. location = response.Location;
  86. using JsonDocument jsonDocument = JsonDocument.Parse(appRecordData);
  87. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  88. JsonElement jsonClosestServer = default;
  89. if (location is null)
  90. {
  91. if (jsonAppRecordData.GetArrayLength() > 0)
  92. jsonClosestServer = jsonAppRecordData[0];
  93. }
  94. else
  95. {
  96. double lastDistance = double.MaxValue;
  97. foreach (JsonElement jsonServer in jsonAppRecordData.EnumerateArray())
  98. {
  99. double lat = Convert.ToDouble(jsonServer.GetProperty("lat").GetString());
  100. double @long = Convert.ToDouble(jsonServer.GetProperty("long").GetString());
  101. double distance = GetDistance(lat, @long, location.Latitude.Value, location.Longitude.Value);
  102. if (distance < lastDistance)
  103. {
  104. lastDistance = distance;
  105. jsonClosestServer = jsonServer;
  106. }
  107. }
  108. }
  109. if (jsonClosestServer.ValueKind == JsonValueKind.Undefined)
  110. return Task.FromResult<DnsDatagram>(null);
  111. string cname = jsonClosestServer.GetPropertyValue("cname", null);
  112. if (string.IsNullOrEmpty(cname))
  113. return Task.FromResult<DnsDatagram>(null);
  114. IReadOnlyList<DnsResourceRecord> answers;
  115. if (request.Question[0].Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase)) //check for zone apex
  116. answers = new DnsResourceRecord[] { new DnsResourceRecord(request.Question[0].Name, DnsResourceRecordType.ANAME, DnsClass.IN, appRecordTtl, new DnsANAMERecordData(cname)) }; //use ANAME
  117. else
  118. answers = new DnsResourceRecord[] { new DnsResourceRecord(request.Question[0].Name, DnsResourceRecordType.CNAME, DnsClass.IN, appRecordTtl, new DnsCNAMERecordData(cname)) };
  119. EDnsOption[] options;
  120. if (requestECS is null)
  121. {
  122. options = null;
  123. }
  124. else
  125. {
  126. if (ecsUsed)
  127. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, requestECS.SourcePrefixLength, requestECS.Address);
  128. else
  129. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, 0, requestECS.Address);
  130. }
  131. 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));
  132. }
  133. #endregion
  134. #region properties
  135. public string Description
  136. { 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."; } }
  137. public string ApplicationRecordDataTemplate
  138. {
  139. get
  140. {
  141. return @"[
  142. {
  143. ""name"": ""server1-mumbai"",
  144. ""lat"": ""19.07283"",
  145. ""long"": ""72.88261"",
  146. ""cname"": ""mumbai.example.com""
  147. },
  148. {
  149. ""name"": ""server2-london"",
  150. ""lat"": ""51.50853"",
  151. ""long"": ""-0.12574"",
  152. ""cname"": ""london.example.com""
  153. }
  154. ]";
  155. }
  156. }
  157. #endregion
  158. }
  159. }