CNAME.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2024 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.Security.Cryptography;
  20. using System.Text.Json;
  21. using System.Threading.Tasks;
  22. using TechnitiumLibrary.Net.Dns;
  23. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  24. namespace WeightedRoundRobin
  25. {
  26. public sealed class CNAME : IDnsApplication, IDnsAppRecordRequestHandler
  27. {
  28. #region IDisposable
  29. public void Dispose()
  30. {
  31. //do nothing
  32. }
  33. #endregion
  34. #region public
  35. public Task InitializeAsync(IDnsServer dnsServer, string config)
  36. {
  37. return Task.CompletedTask;
  38. }
  39. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, string zoneName, string appRecordName, uint appRecordTtl, string appRecordData)
  40. {
  41. DnsQuestionRecord question = request.Question[0];
  42. if (!question.Name.Equals(appRecordName, StringComparison.OrdinalIgnoreCase) && !appRecordName.StartsWith('*'))
  43. return Task.FromResult<DnsDatagram>(null);
  44. List<WeightedDomain> domainNames;
  45. int totalWeight = 0;
  46. using (JsonDocument jsonDocument = JsonDocument.Parse(appRecordData))
  47. {
  48. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  49. if (!jsonAppRecordData.TryGetProperty("cnames", out JsonElement jsonCnames) || (jsonCnames.ValueKind == JsonValueKind.Null))
  50. return Task.FromResult<DnsDatagram>(null);
  51. domainNames = new List<WeightedDomain>(jsonCnames.GetArrayLength());
  52. foreach (JsonElement jsonCnameEntry in jsonCnames.EnumerateArray())
  53. {
  54. if (jsonCnameEntry.TryGetProperty("enabled", out JsonElement jsonEnabled) && (jsonEnabled.ValueKind != JsonValueKind.Null) && !jsonEnabled.GetBoolean())
  55. continue;
  56. if (!jsonCnameEntry.TryGetProperty("domain", out JsonElement jsonDomain) || (jsonDomain.ValueKind == JsonValueKind.Null))
  57. continue;
  58. if (!jsonCnameEntry.TryGetProperty("weight", out JsonElement jsonWeight) || (jsonWeight.ValueKind == JsonValueKind.Null))
  59. continue;
  60. int weight = jsonWeight.GetInt32();
  61. if (weight < 1)
  62. continue;
  63. domainNames.Add(new WeightedDomain() { Domain = jsonDomain.GetString(), Weight = weight });
  64. totalWeight += weight;
  65. }
  66. }
  67. if (domainNames.Count == 0)
  68. return Task.FromResult<DnsDatagram>(null);
  69. int randomSelection = RandomNumberGenerator.GetInt32(1, 101);
  70. int rangeFrom;
  71. int rangeTo = 0;
  72. DnsResourceRecord answer = null;
  73. for (int i = 0; i < domainNames.Count; i++)
  74. {
  75. rangeFrom = rangeTo + 1;
  76. if (i == domainNames.Count - 1)
  77. rangeTo = 100;
  78. else
  79. rangeTo += domainNames[i].Weight * 100 / totalWeight;
  80. if ((rangeFrom <= randomSelection) && (randomSelection <= rangeTo))
  81. {
  82. if (question.Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase)) //check for zone apex
  83. answer = new DnsResourceRecord(question.Name, DnsResourceRecordType.ANAME, DnsClass.IN, appRecordTtl, new DnsANAMERecordData(domainNames[i].Domain)); //use ANAME
  84. else
  85. answer = new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, DnsClass.IN, appRecordTtl, new DnsCNAMERecordData(domainNames[i].Domain));
  86. break;
  87. }
  88. }
  89. if (answer is null)
  90. throw new InvalidOperationException();
  91. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, new DnsResourceRecord[] { answer }));
  92. }
  93. #endregion
  94. #region properties
  95. public string Description
  96. { get { return "Returns a CNAME record using weighted round-robin load balancing."; } }
  97. public string ApplicationRecordDataTemplate
  98. {
  99. get
  100. {
  101. return @"{
  102. ""cnames"": [
  103. {
  104. ""domain"": ""example.com"",
  105. ""weight"": 5,
  106. ""enabled"": true
  107. },
  108. {
  109. ""domain"": ""example.net"",
  110. ""weight"": 3,
  111. ""enabled"": true
  112. }
  113. ]
  114. }";
  115. }
  116. }
  117. #endregion
  118. struct WeightedDomain
  119. {
  120. public string Domain;
  121. public int Weight;
  122. }
  123. }
  124. }