CNAME.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2021 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 DnsApplicationCommon;
  16. using MaxMind.GeoIP2;
  17. using MaxMind.GeoIP2.Model;
  18. using MaxMind.GeoIP2.Responses;
  19. using Newtonsoft.Json;
  20. using System;
  21. using System.Collections.Generic;
  22. using System.IO;
  23. using System.Net;
  24. using System.Threading.Tasks;
  25. using TechnitiumLibrary.Net.Dns;
  26. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  27. namespace GeoDistance
  28. {
  29. public sealed class CNAME : IDnsApplicationRequestHandler
  30. {
  31. #region variables
  32. DatabaseReader _mmCityReader;
  33. #endregion
  34. #region IDisposable
  35. bool _disposed;
  36. private void Dispose(bool disposing)
  37. {
  38. if (_disposed)
  39. return;
  40. if (disposing)
  41. {
  42. if (_mmCityReader != null)
  43. _mmCityReader.Dispose();
  44. }
  45. _disposed = true;
  46. }
  47. public void Dispose()
  48. {
  49. Dispose(true);
  50. }
  51. #endregion
  52. #region private
  53. private static double GetDistance(double lat1, double long1, double lat2, double long2)
  54. {
  55. double d1 = lat1 * (Math.PI / 180.0);
  56. double num1 = long1 * (Math.PI / 180.0);
  57. double d2 = lat2 * (Math.PI / 180.0);
  58. double num2 = long2 * (Math.PI / 180.0) - num1;
  59. 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);
  60. return 6376500.0 * (2.0 * Math.Atan2(Math.Sqrt(d3), Math.Sqrt(1.0 - d3)));
  61. }
  62. #endregion
  63. #region public
  64. public Task InitializeAsync(IDnsServer dnsServer, string config)
  65. {
  66. if (_mmCityReader == null)
  67. {
  68. string mmFile = Path.Combine(dnsServer.ApplicationFolder, "GeoIP2-City.mmdb");
  69. if (!File.Exists(mmFile))
  70. mmFile = Path.Combine(dnsServer.ApplicationFolder, "GeoLite2-City.mmdb");
  71. if (!File.Exists(mmFile))
  72. throw new FileNotFoundException("MaxMind City file is missing!");
  73. _mmCityReader = new DatabaseReader(mmFile);
  74. }
  75. return Task.CompletedTask;
  76. }
  77. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, string zoneName, uint appRecordTtl, string appRecordData, bool isRecursionAllowed, IDnsServer dnsServer)
  78. {
  79. Location location = null;
  80. if (_mmCityReader.TryCity(remoteEP.Address, out CityResponse response))
  81. location = response.Location;
  82. dynamic jsonAppRecordData = JsonConvert.DeserializeObject(appRecordData);
  83. dynamic jsonClosestServer = null;
  84. if ((location == null) || !location.HasCoordinates)
  85. {
  86. jsonClosestServer = jsonAppRecordData[0];
  87. }
  88. else
  89. {
  90. double lastDistance = double.MaxValue;
  91. foreach (dynamic jsonServer in jsonAppRecordData)
  92. {
  93. double lat = Convert.ToDouble(jsonServer.lat.Value);
  94. double @long = Convert.ToDouble(jsonServer.@long.Value);
  95. double distance = GetDistance(lat, @long, location.Latitude.Value, location.Longitude.Value);
  96. if (distance < lastDistance)
  97. {
  98. lastDistance = distance;
  99. jsonClosestServer = jsonServer;
  100. }
  101. }
  102. }
  103. if (jsonClosestServer == null)
  104. return Task.FromResult<DnsDatagram>(null);
  105. dynamic jsonCname = jsonClosestServer.cname;
  106. if (jsonCname == null)
  107. return Task.FromResult<DnsDatagram>(null);
  108. string cname = jsonCname.Value;
  109. if (string.IsNullOrEmpty(cname))
  110. return Task.FromResult<DnsDatagram>(null);
  111. IReadOnlyList<DnsResourceRecord> answers;
  112. if (request.Question[0].Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase)) //check for zone apex
  113. answers = new DnsResourceRecord[] { new DnsResourceRecord(request.Question[0].Name, DnsResourceRecordType.ANAME, DnsClass.IN, appRecordTtl, new DnsANAMERecord(cname)) }; //use ANAME
  114. else
  115. answers = new DnsResourceRecord[] { new DnsResourceRecord(request.Question[0].Name, DnsResourceRecordType.CNAME, DnsClass.IN, appRecordTtl, new DnsCNAMERecord(cname)) };
  116. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answers));
  117. }
  118. #endregion
  119. #region properties
  120. public string Description
  121. { 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."; } }
  122. public string ApplicationRecordDataTemplate
  123. {
  124. get
  125. {
  126. return @"[
  127. {
  128. ""name"": ""server1-mumbai"",
  129. ""lat"": ""19.07283"",
  130. ""long"": ""72.88261"",
  131. ""cname"": ""mumbai.example.com""
  132. },
  133. {
  134. ""name"": ""server2-london"",
  135. ""lat"": ""51.50853"",
  136. ""long"": ""-0.12574"",
  137. ""cname"": ""london.example.com""
  138. }
  139. ]";
  140. }
  141. }
  142. #endregion
  143. }
  144. }