Address.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2022 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 System;
  17. using System.Collections.Generic;
  18. using System.Net;
  19. using System.Net.Sockets;
  20. using System.Text.Json;
  21. using System.Threading.Tasks;
  22. using TechnitiumLibrary;
  23. using TechnitiumLibrary.Net.Dns;
  24. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  25. namespace Failover
  26. {
  27. enum FailoverType
  28. {
  29. Unknown = 0,
  30. Primary = 1,
  31. Secondary = 2
  32. }
  33. public class Address : IDnsApplication, IDnsAppRecordRequestHandler
  34. {
  35. #region variables
  36. HealthService _healthService;
  37. #endregion
  38. #region IDisposable
  39. bool _disposed;
  40. public void Dispose()
  41. {
  42. if (_disposed)
  43. return;
  44. if (_healthService is not null)
  45. _healthService.Dispose();
  46. _disposed = true;
  47. }
  48. #endregion
  49. #region private
  50. private void GetAnswers(JsonElement jsonAddresses, DnsQuestionRecord question, uint appRecordTtl, string healthCheck, Uri healthCheckUrl, List<DnsResourceRecord> answers)
  51. {
  52. switch (question.Type)
  53. {
  54. case DnsResourceRecordType.A:
  55. foreach (JsonElement jsonAddress in jsonAddresses.EnumerateArray())
  56. {
  57. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  58. if (address.AddressFamily == AddressFamily.InterNetwork)
  59. {
  60. HealthCheckResponse response = _healthService.QueryStatus(address, healthCheck, healthCheckUrl, true);
  61. switch (response.Status)
  62. {
  63. case HealthStatus.Unknown:
  64. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.A, question.Class, 30, new DnsARecordData(address)));
  65. break;
  66. case HealthStatus.Healthy:
  67. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.A, question.Class, appRecordTtl, new DnsARecordData(address)));
  68. break;
  69. }
  70. }
  71. }
  72. break;
  73. case DnsResourceRecordType.AAAA:
  74. foreach (JsonElement jsonAddress in jsonAddresses.EnumerateArray())
  75. {
  76. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  77. if (address.AddressFamily == AddressFamily.InterNetworkV6)
  78. {
  79. HealthCheckResponse response = _healthService.QueryStatus(address, healthCheck, healthCheckUrl, true);
  80. switch (response.Status)
  81. {
  82. case HealthStatus.Unknown:
  83. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.AAAA, question.Class, 30, new DnsAAAARecordData(address)));
  84. break;
  85. case HealthStatus.Healthy:
  86. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.AAAA, question.Class, appRecordTtl, new DnsAAAARecordData(address)));
  87. break;
  88. }
  89. }
  90. }
  91. break;
  92. }
  93. }
  94. private void GetStatusAnswers(JsonElement jsonAddresses, FailoverType type, DnsQuestionRecord question, uint appRecordTtl, string healthCheck, Uri healthCheckUrl, List<DnsResourceRecord> answers)
  95. {
  96. foreach (JsonElement jsonAddress in jsonAddresses.EnumerateArray())
  97. {
  98. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  99. HealthCheckResponse response = _healthService.QueryStatus(address, healthCheck, healthCheckUrl, false);
  100. string text = "app=failover; addressType=" + type.ToString() + "; address=" + address.ToString() + "; healthCheck=" + healthCheck + (healthCheckUrl is null ? "" : "; healthCheckUrl=" + healthCheckUrl.AbsoluteUri) + "; healthStatus=" + response.Status.ToString() + ";";
  101. if (response.Status == HealthStatus.Failed)
  102. text += " failureReason=" + response.FailureReason + ";";
  103. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.TXT, question.Class, appRecordTtl, new DnsTXTRecordData(text)));
  104. }
  105. }
  106. #endregion
  107. #region public
  108. public Task InitializeAsync(IDnsServer dnsServer, string config)
  109. {
  110. if (_healthService is null)
  111. _healthService = HealthService.Create(dnsServer);
  112. _healthService.Initialize(config);
  113. return Task.CompletedTask;
  114. }
  115. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, string zoneName, string appRecordName, uint appRecordTtl, string appRecordData)
  116. {
  117. DnsQuestionRecord question = request.Question[0];
  118. switch (question.Type)
  119. {
  120. case DnsResourceRecordType.A:
  121. case DnsResourceRecordType.AAAA:
  122. {
  123. using JsonDocument jsonDocument = JsonDocument.Parse(appRecordData);
  124. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  125. string healthCheck = jsonAppRecordData.GetPropertyValue("healthCheck", null);
  126. Uri healthCheckUrl = null;
  127. if (_healthService.HealthChecks.TryGetValue(healthCheck, out HealthCheck hc) && ((hc.Type == HealthCheckType.Https) || (hc.Type == HealthCheckType.Http)) && (hc.Url is null))
  128. {
  129. //read health check url only for http/https type checks and only when app config does not have an url configured
  130. if (jsonAppRecordData.TryGetProperty("healthCheckUrl", out JsonElement jsonHealthCheckUrl) && (jsonHealthCheckUrl.ValueKind != JsonValueKind.Null))
  131. {
  132. healthCheckUrl = new Uri(jsonHealthCheckUrl.GetString());
  133. }
  134. else
  135. {
  136. if (hc.Type == HealthCheckType.Https)
  137. healthCheckUrl = new Uri("https://" + question.Name);
  138. else
  139. healthCheckUrl = new Uri("http://" + question.Name);
  140. }
  141. }
  142. List<DnsResourceRecord> answers = new List<DnsResourceRecord>();
  143. if (jsonAppRecordData.TryGetProperty("primary", out JsonElement jsonPrimary))
  144. GetAnswers(jsonPrimary, question, appRecordTtl, healthCheck, healthCheckUrl, answers);
  145. if (answers.Count == 0)
  146. {
  147. if (jsonAppRecordData.TryGetProperty("secondary", out JsonElement jsonSecondary))
  148. GetAnswers(jsonSecondary, question, appRecordTtl, healthCheck, healthCheckUrl, answers);
  149. if (answers.Count == 0)
  150. {
  151. if (jsonAppRecordData.TryGetProperty("serverDown", out JsonElement jsonServerDown))
  152. {
  153. if (question.Type == DnsResourceRecordType.A)
  154. {
  155. foreach (JsonElement jsonAddress in jsonServerDown.EnumerateArray())
  156. {
  157. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  158. if (address.AddressFamily == AddressFamily.InterNetwork)
  159. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.A, question.Class, 30, new DnsARecordData(address)));
  160. }
  161. }
  162. else
  163. {
  164. foreach (JsonElement jsonAddress in jsonServerDown.EnumerateArray())
  165. {
  166. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  167. if (address.AddressFamily == AddressFamily.InterNetworkV6)
  168. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.AAAA, question.Class, 30, new DnsAAAARecordData(address)));
  169. }
  170. }
  171. }
  172. if (answers.Count == 0)
  173. return Task.FromResult<DnsDatagram>(null);
  174. }
  175. }
  176. if (answers.Count > 1)
  177. answers.Shuffle();
  178. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answers));
  179. }
  180. case DnsResourceRecordType.TXT:
  181. {
  182. using JsonDocument jsonDocument = JsonDocument.Parse(appRecordData);
  183. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  184. bool allowTxtStatus = jsonAppRecordData.GetPropertyValue("allowTxtStatus", false);
  185. if (!allowTxtStatus)
  186. return Task.FromResult<DnsDatagram>(null);
  187. string healthCheck = jsonAppRecordData.GetPropertyValue("healthCheck", null);
  188. Uri healthCheckUrl = null;
  189. if (_healthService.HealthChecks.TryGetValue(healthCheck, out HealthCheck hc) && ((hc.Type == HealthCheckType.Https) || (hc.Type == HealthCheckType.Http)) && (hc.Url is null))
  190. {
  191. //read health check url only for http/https type checks and only when app config does not have an url configured
  192. if (jsonAppRecordData.TryGetProperty("healthCheckUrl", out JsonElement jsonHealthCheckUrl) && (jsonHealthCheckUrl.ValueKind != JsonValueKind.Null))
  193. {
  194. healthCheckUrl = new Uri(jsonHealthCheckUrl.GetString());
  195. }
  196. else
  197. {
  198. if (hc.Type == HealthCheckType.Https)
  199. healthCheckUrl = new Uri("https://" + question.Name);
  200. else
  201. healthCheckUrl = new Uri("http://" + question.Name);
  202. }
  203. }
  204. List<DnsResourceRecord> answers = new List<DnsResourceRecord>();
  205. if (jsonAppRecordData.TryGetProperty("primary", out JsonElement jsonPrimary))
  206. GetStatusAnswers(jsonPrimary, FailoverType.Primary, question, 30, healthCheck, healthCheckUrl, answers);
  207. if (jsonAppRecordData.TryGetProperty("secondary", out JsonElement jsonSecondary))
  208. GetStatusAnswers(jsonSecondary, FailoverType.Secondary, question, 30, healthCheck, healthCheckUrl, answers);
  209. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answers));
  210. }
  211. default:
  212. return Task.FromResult<DnsDatagram>(null);
  213. }
  214. }
  215. #endregion
  216. #region properties
  217. public string Description
  218. { get { return "Returns A or AAAA records from primary set of addresses with a continous health check as configured in the app config. When none of the primary addresses are healthy, the app returns healthy addresses from the secondary set of addresses. When none of the primary and secondary addresses are healthy, the app returns all addresses from the server down set of addresses. The server down feature is expected to be used for showing a service status page and not to serve the actual content.\n\nIf an URL is provided for the health check in the app's config then it will override the 'healthCheckUrl' parameter. When an URL is not provided in 'healthCheckUrl' parameter for 'http' or 'https' type health check, the domain name of the APP record will be used to auto generate an URL.\n\nSet 'allowTxtStatus' parameter to 'true' in your APP record data to allow checking health status by querying for TXT record."; } }
  219. public string ApplicationRecordDataTemplate
  220. {
  221. get
  222. {
  223. return @"{
  224. ""primary"": [
  225. ""1.1.1.1"",
  226. ""::1""
  227. ],
  228. ""secondary"": [
  229. ""2.2.2.2"",
  230. ""::2""
  231. ],
  232. ""serverDown"": [
  233. ""3.3.3.3""
  234. ],
  235. ""healthCheck"": ""https"",
  236. ""healthCheckUrl"": ""https://www.example.com/"",
  237. ""allowTxtStatus"": false
  238. }";
  239. }
  240. }
  241. #endregion
  242. }
  243. }