Address.cs 7.6 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.Responses;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Net;
  20. using System.Net.Sockets;
  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 GeoContinent
  28. {
  29. public sealed class Address : 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 public
  54. public Task InitializeAsync(IDnsServer dnsServer, string config)
  55. {
  56. _dnsServer = dnsServer;
  57. _maxMind = MaxMind.Create(dnsServer);
  58. return Task.CompletedTask;
  59. }
  60. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, string zoneName, string appRecordName, uint appRecordTtl, string appRecordData)
  61. {
  62. DnsQuestionRecord question = request.Question[0];
  63. if (!question.Name.Equals(appRecordName, StringComparison.OrdinalIgnoreCase))
  64. return Task.FromResult<DnsDatagram>(null);
  65. switch (question.Type)
  66. {
  67. case DnsResourceRecordType.A:
  68. case DnsResourceRecordType.AAAA:
  69. using (JsonDocument jsonDocument = JsonDocument.Parse(appRecordData))
  70. {
  71. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  72. JsonElement jsonContinent = default;
  73. bool ecsUsed = false;
  74. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  75. if (requestECS is not null)
  76. {
  77. if (_maxMind.DatabaseReader.TryCountry(requestECS.Address, out CountryResponse csResponse))
  78. {
  79. ecsUsed = true;
  80. if (!jsonAppRecordData.TryGetProperty(csResponse.Continent.Code, out jsonContinent))
  81. jsonAppRecordData.TryGetProperty("default", out jsonContinent);
  82. }
  83. }
  84. if (jsonContinent.ValueKind == JsonValueKind.Undefined)
  85. {
  86. if (_maxMind.DatabaseReader.TryCountry(remoteEP.Address, out CountryResponse response))
  87. {
  88. if (!jsonAppRecordData.TryGetProperty(response.Continent.Code, out jsonContinent))
  89. jsonAppRecordData.TryGetProperty("default", out jsonContinent);
  90. }
  91. else
  92. {
  93. jsonAppRecordData.TryGetProperty("default", out jsonContinent);
  94. }
  95. if (jsonContinent.ValueKind == JsonValueKind.Undefined)
  96. return Task.FromResult<DnsDatagram>(null);
  97. }
  98. List<DnsResourceRecord> answers = new List<DnsResourceRecord>();
  99. switch (question.Type)
  100. {
  101. case DnsResourceRecordType.A:
  102. foreach (JsonElement jsonAddress in jsonContinent.EnumerateArray())
  103. {
  104. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  105. if (address.AddressFamily == AddressFamily.InterNetwork)
  106. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.A, DnsClass.IN, appRecordTtl, new DnsARecordData(address)));
  107. }
  108. break;
  109. case DnsResourceRecordType.AAAA:
  110. foreach (JsonElement jsonAddress in jsonContinent.EnumerateArray())
  111. {
  112. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  113. if (address.AddressFamily == AddressFamily.InterNetworkV6)
  114. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.AAAA, DnsClass.IN, appRecordTtl, new DnsAAAARecordData(address)));
  115. }
  116. break;
  117. }
  118. if (answers.Count == 0)
  119. return Task.FromResult<DnsDatagram>(null);
  120. if (answers.Count > 1)
  121. answers.Shuffle();
  122. EDnsOption[] options;
  123. if (requestECS is null)
  124. {
  125. options = null;
  126. }
  127. else
  128. {
  129. if (ecsUsed)
  130. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, requestECS.SourcePrefixLength, requestECS.Address);
  131. else
  132. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, 0, requestECS.Address);
  133. }
  134. 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));
  135. }
  136. default:
  137. return Task.FromResult<DnsDatagram>(null);
  138. }
  139. }
  140. #endregion
  141. #region properties
  142. public string Description
  143. { get { return "Returns A or AAAA records based on the continent the client queries from using MaxMind GeoIP2 Country database. Use the two character continent code like \"NA\" (North America) or \"OC\" (Oceania)."; } }
  144. public string ApplicationRecordDataTemplate
  145. {
  146. get
  147. {
  148. return @"{
  149. ""EU"": [
  150. ""1.1.1.1"",
  151. ""2.2.2.2""
  152. ],
  153. ""default"": [
  154. ""3.3.3.3""
  155. ]
  156. }";
  157. }
  158. }
  159. #endregion
  160. }
  161. }