CNAME.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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.Text.Json;
  20. using System.Threading.Tasks;
  21. using TechnitiumLibrary;
  22. using TechnitiumLibrary.Net.Dns;
  23. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  24. namespace Failover
  25. {
  26. public class CNAME : IDnsApplication, IDnsAppRecordRequestHandler
  27. {
  28. #region variables
  29. HealthService _healthService;
  30. #endregion
  31. #region IDisposable
  32. bool _disposed;
  33. public void Dispose()
  34. {
  35. if (_disposed)
  36. return;
  37. if (_healthService is not null)
  38. _healthService.Dispose();
  39. _disposed = true;
  40. }
  41. #endregion
  42. #region private
  43. private IReadOnlyList<DnsResourceRecord> GetAnswers(string domain, DnsQuestionRecord question, string zoneName, uint appRecordTtl, string healthCheck, Uri healthCheckUrl)
  44. {
  45. HealthCheckResponse response = _healthService.QueryStatus(domain, question.Type, healthCheck, healthCheckUrl, true);
  46. switch (response.Status)
  47. {
  48. case HealthStatus.Unknown:
  49. if (question.Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase)) //check for zone apex
  50. return new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.ANAME, DnsClass.IN, 30, new DnsANAMERecordData(domain)) }; //use ANAME
  51. else
  52. return new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, DnsClass.IN, 30, new DnsCNAMERecordData(domain)) };
  53. case HealthStatus.Healthy:
  54. if (question.Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase)) //check for zone apex
  55. return new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.ANAME, DnsClass.IN, appRecordTtl, new DnsANAMERecordData(domain)) }; //use ANAME
  56. else
  57. return new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, DnsClass.IN, appRecordTtl, new DnsCNAMERecordData(domain)) };
  58. }
  59. return null;
  60. }
  61. private void GetStatusAnswers(string domain, FailoverType type, DnsQuestionRecord question, uint appRecordTtl, string healthCheck, Uri healthCheckUrl, List<DnsResourceRecord> answers)
  62. {
  63. {
  64. HealthCheckResponse response = _healthService.QueryStatus(domain, DnsResourceRecordType.A, healthCheck, healthCheckUrl, false);
  65. string text = "app=failover; cnameType=" + type.ToString() + "; domain=" + domain + "; qType: A; healthCheck=" + healthCheck + (healthCheckUrl is null ? "" : "; healthCheckUrl=" + healthCheckUrl.AbsoluteUri) + "; healthStatus=" + response.Status.ToString() + ";";
  66. if (response.Status == HealthStatus.Failed)
  67. text += " failureReason=" + response.FailureReason + ";";
  68. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.TXT, question.Class, appRecordTtl, new DnsTXTRecordData(text)));
  69. }
  70. {
  71. HealthCheckResponse response = _healthService.QueryStatus(domain, DnsResourceRecordType.AAAA, healthCheck, healthCheckUrl, false);
  72. string text = "app=failover; cnameType=" + type.ToString() + "; domain=" + domain + "; qType: AAAA; healthCheck=" + healthCheck + (healthCheckUrl is null ? "" : "; healthCheckUrl=" + healthCheckUrl.AbsoluteUri) + "; healthStatus=" + response.Status.ToString() + ";";
  73. if (response.Status == HealthStatus.Failed)
  74. text += " failureReason=" + response.FailureReason + ";";
  75. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.TXT, question.Class, appRecordTtl, new DnsTXTRecordData(text)));
  76. }
  77. }
  78. #endregion
  79. #region public
  80. public Task InitializeAsync(IDnsServer dnsServer, string config)
  81. {
  82. if (_healthService is null)
  83. _healthService = HealthService.Create(dnsServer);
  84. //let Address class initialize config
  85. return Task.CompletedTask;
  86. }
  87. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, string zoneName, string appRecordName, uint appRecordTtl, string appRecordData)
  88. {
  89. DnsQuestionRecord question = request.Question[0];
  90. using JsonDocument jsonDocument = JsonDocument.Parse(appRecordData);
  91. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  92. string healthCheck = jsonAppRecordData.GetPropertyValue("healthCheck", null);
  93. Uri healthCheckUrl = null;
  94. if (_healthService.HealthChecks.TryGetValue(healthCheck, out HealthCheck hc) && ((hc.Type == HealthCheckType.Https) || (hc.Type == HealthCheckType.Http)) && (hc.Url is null))
  95. {
  96. //read health check url only for http/https type checks and only when app config does not have an url configured
  97. if (jsonAppRecordData.TryGetProperty("healthCheckUrl", out JsonElement jsonHealthCheckUrl) && (jsonHealthCheckUrl.ValueKind != JsonValueKind.Null))
  98. {
  99. healthCheckUrl = new Uri(jsonHealthCheckUrl.GetString());
  100. }
  101. else
  102. {
  103. if (hc.Type == HealthCheckType.Https)
  104. healthCheckUrl = new Uri("https://" + question.Name);
  105. else
  106. healthCheckUrl = new Uri("http://" + question.Name);
  107. }
  108. }
  109. IReadOnlyList<DnsResourceRecord> answers = null;
  110. if (question.Type == DnsResourceRecordType.TXT)
  111. {
  112. bool allowTxtStatus = jsonAppRecordData.GetPropertyValue("allowTxtStatus", false);
  113. if (!allowTxtStatus)
  114. return Task.FromResult<DnsDatagram>(null);
  115. List<DnsResourceRecord> txtAnswers = new List<DnsResourceRecord>();
  116. if (jsonAppRecordData.TryGetProperty("primary", out JsonElement jsonPrimary))
  117. GetStatusAnswers(jsonPrimary.GetString(), FailoverType.Primary, question, 30, healthCheck, healthCheckUrl, txtAnswers);
  118. if (jsonAppRecordData.TryGetProperty("secondary", out JsonElement jsonSecondary))
  119. {
  120. foreach (JsonElement jsonDomain in jsonSecondary.EnumerateArray())
  121. GetStatusAnswers(jsonDomain.GetString(), FailoverType.Secondary, question, 30, healthCheck, healthCheckUrl, txtAnswers);
  122. }
  123. answers = txtAnswers;
  124. }
  125. else
  126. {
  127. if (jsonAppRecordData.TryGetProperty("primary", out JsonElement jsonPrimary))
  128. answers = GetAnswers(jsonPrimary.GetString(), question, zoneName, appRecordTtl, healthCheck, healthCheckUrl);
  129. if (answers is null)
  130. {
  131. if (jsonAppRecordData.TryGetProperty("secondary", out JsonElement jsonSecondary))
  132. {
  133. foreach (JsonElement jsonDomain in jsonSecondary.EnumerateArray())
  134. {
  135. answers = GetAnswers(jsonDomain.GetString(), question, zoneName, appRecordTtl, healthCheck, healthCheckUrl);
  136. if (answers is not null)
  137. break;
  138. }
  139. }
  140. if (answers is null)
  141. {
  142. if (!jsonAppRecordData.TryGetProperty("serverDown", out JsonElement jsonServerDown) || (jsonServerDown.ValueKind == JsonValueKind.Null))
  143. return Task.FromResult<DnsDatagram>(null);
  144. string serverDown = jsonServerDown.GetString();
  145. if (question.Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase)) //check for zone apex
  146. answers = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.ANAME, DnsClass.IN, 30, new DnsANAMERecordData(serverDown)) }; //use ANAME
  147. else
  148. answers = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, DnsClass.IN, 30, new DnsCNAMERecordData(serverDown)) };
  149. }
  150. }
  151. }
  152. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answers));
  153. }
  154. #endregion
  155. #region properties
  156. public string Description
  157. { get { return "Returns CNAME record for primary domain name with a continous health check as configured in the app config. When the primary domain name is unhealthy, the app returns one of the secondary domain names in the given order of preference that is healthy. When none of the primary and secondary domain names are healthy, the app returns the server down domain name. The server down feature is expected to be used for showing a service status page and not to serve the actual content. Note that the app will return ANAME record for an APP record at zone apex.\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."; } }
  158. public string ApplicationRecordDataTemplate
  159. {
  160. get
  161. {
  162. return @"{
  163. ""primary"": ""in.example.org"",
  164. ""secondary"": [
  165. ""sg.example.org"",
  166. ""eu.example.org""
  167. ],
  168. ""serverDown"": ""status.example.org"",
  169. ""healthCheck"": ""tcp443"",
  170. ""healthCheckUrl"": null,
  171. ""allowTxtStatus"": false
  172. }";
  173. }
  174. }
  175. #endregion
  176. }
  177. }