WebHook.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Net;
  19. using System.Net.Http;
  20. using System.Net.Http.Headers;
  21. using System.Text.Json;
  22. using System.Threading.Tasks;
  23. using TechnitiumLibrary;
  24. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  25. using TechnitiumLibrary.Net.Http.Client;
  26. using TechnitiumLibrary.Net.Proxy;
  27. namespace Failover
  28. {
  29. class WebHook : IDisposable
  30. {
  31. #region variables
  32. readonly HealthService _service;
  33. readonly string _name;
  34. bool _enabled;
  35. Uri[] _urls;
  36. SocketsHttpHandler _httpHandler;
  37. HttpClientNetworkHandler _httpCustomResolverHandler;
  38. HttpClient _httpClient;
  39. #endregion
  40. #region constructor
  41. public WebHook(HealthService service, JsonElement jsonWebHook)
  42. {
  43. _service = service;
  44. _name = jsonWebHook.GetPropertyValue("name", "default");
  45. Reload(jsonWebHook);
  46. }
  47. #endregion
  48. #region IDisposable
  49. bool _disposed;
  50. protected virtual void Dispose(bool disposing)
  51. {
  52. if (_disposed)
  53. return;
  54. if (disposing)
  55. {
  56. if (_httpClient != null)
  57. {
  58. _httpClient.Dispose();
  59. _httpClient = null;
  60. }
  61. if (_httpHandler != null)
  62. {
  63. _httpHandler.Dispose();
  64. _httpHandler = null;
  65. }
  66. }
  67. _disposed = true;
  68. }
  69. public void Dispose()
  70. {
  71. Dispose(true);
  72. GC.SuppressFinalize(this);
  73. }
  74. #endregion
  75. #region private
  76. private void ConditionalHttpReload()
  77. {
  78. bool handlerChanged = false;
  79. NetProxy proxy = _service.DnsServer.Proxy;
  80. if (_httpHandler is null)
  81. {
  82. SocketsHttpHandler httpHandler = new SocketsHttpHandler();
  83. httpHandler.Proxy = proxy;
  84. httpHandler.UseProxy = proxy is not null;
  85. httpHandler.AllowAutoRedirect = true;
  86. httpHandler.MaxAutomaticRedirections = 10;
  87. _httpHandler = httpHandler;
  88. handlerChanged = true;
  89. }
  90. else
  91. {
  92. if (_httpHandler.Proxy != proxy)
  93. {
  94. SocketsHttpHandler httpHandler = new SocketsHttpHandler();
  95. httpHandler.Proxy = proxy;
  96. httpHandler.UseProxy = proxy is not null;
  97. httpHandler.AllowAutoRedirect = true;
  98. httpHandler.MaxAutomaticRedirections = 10;
  99. SocketsHttpHandler oldHttpHandler = _httpHandler;
  100. _httpHandler = httpHandler;
  101. handlerChanged = true;
  102. oldHttpHandler.Dispose();
  103. }
  104. }
  105. if ((_httpCustomResolverHandler is null) || handlerChanged)
  106. _httpCustomResolverHandler = new HttpClientNetworkHandler(_httpHandler, _service.DnsServer.PreferIPv6 ? HttpClientNetworkType.PreferIPv6 : HttpClientNetworkType.Default, _service.DnsServer);
  107. if (_httpClient is null)
  108. {
  109. HttpClient httpClient = new HttpClient(_httpCustomResolverHandler);
  110. _httpClient = httpClient;
  111. }
  112. else
  113. {
  114. if (handlerChanged)
  115. {
  116. HttpClient httpClient = new HttpClient(_httpCustomResolverHandler);
  117. HttpClient oldHttpClient = _httpClient;
  118. _httpClient = httpClient;
  119. oldHttpClient.Dispose();
  120. }
  121. }
  122. }
  123. private async Task CallAsync(HttpContent content)
  124. {
  125. ConditionalHttpReload();
  126. async Task CallWebHook(Uri url)
  127. {
  128. try
  129. {
  130. HttpResponseMessage response = await _httpClient.PostAsync(url, content);
  131. response.EnsureSuccessStatusCode();
  132. }
  133. catch (Exception ex)
  134. {
  135. _service.DnsServer.WriteLog("Webhook call failed for URL: " + url.AbsoluteUri + "\r\n" + ex.ToString());
  136. }
  137. }
  138. List<Task> tasks = new List<Task>();
  139. foreach (Uri url in _urls)
  140. tasks.Add(CallWebHook(url));
  141. await Task.WhenAll(tasks);
  142. }
  143. #endregion
  144. #region public
  145. public void Reload(JsonElement jsonWebHook)
  146. {
  147. _enabled = jsonWebHook.GetPropertyValue("enabled", false);
  148. if (jsonWebHook.TryReadArray("urls", delegate (string uri) { return new Uri(uri); }, out Uri[] urls))
  149. _urls = urls;
  150. else
  151. _urls = null;
  152. ConditionalHttpReload();
  153. }
  154. public Task CallAsync(IPAddress address, string healthCheck, HealthCheckResponse healthCheckResponse)
  155. {
  156. if (!_enabled)
  157. return Task.CompletedTask;
  158. HttpContent content;
  159. {
  160. using (MemoryStream mS = new MemoryStream())
  161. {
  162. Utf8JsonWriter jsonWriter = new Utf8JsonWriter(mS);
  163. jsonWriter.WriteStartObject();
  164. jsonWriter.WriteString("address", address.ToString());
  165. jsonWriter.WriteString("healthCheck", healthCheck);
  166. jsonWriter.WriteString("status", healthCheckResponse.Status.ToString());
  167. if (healthCheckResponse.Status == HealthStatus.Failed)
  168. jsonWriter.WriteString("failureReason", healthCheckResponse.FailureReason);
  169. jsonWriter.WriteString("dateTime", healthCheckResponse.DateTime);
  170. jsonWriter.WriteEndObject();
  171. jsonWriter.Flush();
  172. content = new ByteArrayContent(mS.ToArray());
  173. content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  174. }
  175. }
  176. return CallAsync(content);
  177. }
  178. public Task CallAsync(IPAddress address, string healthCheck, Exception ex)
  179. {
  180. if (!_enabled)
  181. return Task.CompletedTask;
  182. HttpContent content;
  183. {
  184. using (MemoryStream mS = new MemoryStream())
  185. {
  186. Utf8JsonWriter jsonWriter = new Utf8JsonWriter(mS);
  187. jsonWriter.WriteStartObject();
  188. jsonWriter.WriteString("address", address.ToString());
  189. jsonWriter.WriteString("healthCheck", healthCheck);
  190. jsonWriter.WriteString("status", "Error");
  191. jsonWriter.WriteString("failureReason", ex.ToString());
  192. jsonWriter.WriteString("dateTime", DateTime.UtcNow);
  193. jsonWriter.WriteEndObject();
  194. jsonWriter.Flush();
  195. content = new ByteArrayContent(mS.ToArray());
  196. content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  197. }
  198. }
  199. return CallAsync(content);
  200. }
  201. public Task CallAsync(string domain, DnsResourceRecordType type, string healthCheck, HealthCheckResponse healthCheckResponse)
  202. {
  203. if (!_enabled)
  204. return Task.CompletedTask;
  205. HttpContent content;
  206. {
  207. using (MemoryStream mS = new MemoryStream())
  208. {
  209. Utf8JsonWriter jsonWriter = new Utf8JsonWriter(mS);
  210. jsonWriter.WriteStartObject();
  211. jsonWriter.WriteString("domain", domain);
  212. jsonWriter.WriteString("recordType", type.ToString());
  213. jsonWriter.WriteString("healthCheck", healthCheck);
  214. jsonWriter.WriteString("status", healthCheckResponse.Status.ToString());
  215. if (healthCheckResponse.Status == HealthStatus.Failed)
  216. jsonWriter.WriteString("failureReason", healthCheckResponse.FailureReason);
  217. jsonWriter.WriteString("dateTime", healthCheckResponse.DateTime);
  218. jsonWriter.WriteEndObject();
  219. jsonWriter.Flush();
  220. content = new ByteArrayContent(mS.ToArray());
  221. content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  222. }
  223. }
  224. return CallAsync(content);
  225. }
  226. public Task CallAsync(string domain, DnsResourceRecordType type, string healthCheck, Exception ex)
  227. {
  228. if (!_enabled)
  229. return Task.CompletedTask;
  230. HttpContent content;
  231. {
  232. using (MemoryStream mS = new MemoryStream())
  233. {
  234. Utf8JsonWriter jsonWriter = new Utf8JsonWriter(mS);
  235. jsonWriter.WriteStartObject();
  236. jsonWriter.WriteString("domain", domain);
  237. jsonWriter.WriteString("recordType", type.ToString());
  238. jsonWriter.WriteString("healthCheck", healthCheck);
  239. jsonWriter.WriteString("status", "Error");
  240. jsonWriter.WriteString("failureReason", ex.ToString());
  241. jsonWriter.WriteString("dateTime", DateTime.UtcNow);
  242. jsonWriter.WriteEndObject();
  243. jsonWriter.Flush();
  244. content = new ByteArrayContent(mS.ToArray());
  245. content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  246. }
  247. }
  248. return CallAsync(content);
  249. }
  250. #endregion
  251. #region properties
  252. public string Name
  253. { get { return _name; } }
  254. public bool Enabled
  255. { get { return _enabled; } }
  256. public Uri[] Urls
  257. { get { return _urls; } }
  258. #endregion
  259. }
  260. }