WebServiceDashboardApi.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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.Auth;
  16. using DnsServerCore.Dns;
  17. using Microsoft.AspNetCore.Http;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Globalization;
  21. using System.Net;
  22. using System.Text.Json;
  23. using System.Threading.Tasks;
  24. using TechnitiumLibrary.Net.Dns;
  25. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  26. namespace DnsServerCore
  27. {
  28. class WebServiceDashboardApi
  29. {
  30. #region variables
  31. readonly DnsWebService _dnsWebService;
  32. #endregion
  33. #region constructor
  34. public WebServiceDashboardApi(DnsWebService dnsWebService)
  35. {
  36. _dnsWebService = dnsWebService;
  37. }
  38. #endregion
  39. #region private
  40. private static void WriteChartDataSet(Utf8JsonWriter jsonWriter, string label, string backgroundColor, string borderColor, List<KeyValuePair<string, long>> statsPerInterval)
  41. {
  42. jsonWriter.WriteStartObject();
  43. jsonWriter.WriteString("label", label);
  44. jsonWriter.WriteString("backgroundColor", backgroundColor);
  45. jsonWriter.WriteString("borderColor", borderColor);
  46. jsonWriter.WriteNumber("borderWidth", 2);
  47. jsonWriter.WriteBoolean("fill", true);
  48. jsonWriter.WritePropertyName("data");
  49. jsonWriter.WriteStartArray();
  50. foreach (KeyValuePair<string, long> item in statsPerInterval)
  51. jsonWriter.WriteNumberValue(item.Value);
  52. jsonWriter.WriteEndArray();
  53. jsonWriter.WriteEndObject();
  54. }
  55. private async Task<IDictionary<string, string>> ResolvePtrTopClientsAsync(List<KeyValuePair<string, long>> topClients)
  56. {
  57. IDictionary<string, string> dhcpClientIpMap = _dnsWebService.DhcpServer.GetAddressHostNameMap();
  58. async Task<KeyValuePair<string, string>> ResolvePtrAsync(string ip)
  59. {
  60. if (dhcpClientIpMap.TryGetValue(ip, out string dhcpDomain))
  61. return new KeyValuePair<string, string>(ip, dhcpDomain);
  62. IPAddress address = IPAddress.Parse(ip);
  63. if (IPAddress.IsLoopback(address))
  64. return new KeyValuePair<string, string>(ip, "localhost");
  65. DnsDatagram ptrResponse = await _dnsWebService.DnsServer.DirectQueryAsync(new DnsQuestionRecord(address, DnsClass.IN), 500);
  66. if (ptrResponse.Answer.Count > 0)
  67. {
  68. IReadOnlyList<string> ptrDomains = DnsClient.ParseResponsePTR(ptrResponse);
  69. if (ptrDomains.Count > 0)
  70. return new KeyValuePair<string, string>(ip, ptrDomains[0]);
  71. }
  72. return new KeyValuePair<string, string>(ip, null);
  73. }
  74. List<Task<KeyValuePair<string, string>>> resolverTasks = new List<Task<KeyValuePair<string, string>>>();
  75. foreach (KeyValuePair<string, long> item in topClients)
  76. {
  77. resolverTasks.Add(ResolvePtrAsync(item.Key));
  78. }
  79. Dictionary<string, string> result = new Dictionary<string, string>();
  80. foreach (Task<KeyValuePair<string, string>> resolverTask in resolverTasks)
  81. {
  82. try
  83. {
  84. KeyValuePair<string, string> ptrResult = await resolverTask;
  85. result[ptrResult.Key] = ptrResult.Value;
  86. }
  87. catch
  88. { }
  89. }
  90. return result;
  91. }
  92. #endregion
  93. #region public
  94. public async Task GetStats(HttpContext context)
  95. {
  96. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Dashboard, context.GetCurrentSession().User, PermissionFlag.View))
  97. throw new DnsWebServiceException("Access was denied.");
  98. HttpRequest request = context.Request;
  99. string strType = request.GetQueryOrForm("type", "lastHour");
  100. bool utcFormat = request.GetQueryOrForm("utc", bool.Parse, false);
  101. bool isLanguageEnUs = true;
  102. string acceptLanguage = request.Headers.AcceptLanguage;
  103. if (!string.IsNullOrEmpty(acceptLanguage))
  104. isLanguageEnUs = acceptLanguage.StartsWith("en-us", StringComparison.OrdinalIgnoreCase);
  105. Dictionary<string, List<KeyValuePair<string, long>>> data;
  106. string labelFormat;
  107. switch (strType.ToLowerInvariant())
  108. {
  109. case "lasthour":
  110. data = _dnsWebService.DnsServer.StatsManager.GetLastHourMinuteWiseStats(utcFormat);
  111. labelFormat = "HH:mm";
  112. break;
  113. case "lastday":
  114. data = _dnsWebService.DnsServer.StatsManager.GetLastDayHourWiseStats(utcFormat);
  115. if (isLanguageEnUs)
  116. labelFormat = "MM/DD HH:00";
  117. else
  118. labelFormat = "DD/MM HH:00";
  119. break;
  120. case "lastweek":
  121. data = _dnsWebService.DnsServer.StatsManager.GetLastWeekDayWiseStats(utcFormat);
  122. if (isLanguageEnUs)
  123. labelFormat = "MM/DD";
  124. else
  125. labelFormat = "DD/MM";
  126. break;
  127. case "lastmonth":
  128. data = _dnsWebService.DnsServer.StatsManager.GetLastMonthDayWiseStats(utcFormat);
  129. if (isLanguageEnUs)
  130. labelFormat = "MM/DD";
  131. else
  132. labelFormat = "DD/MM";
  133. break;
  134. case "lastyear":
  135. labelFormat = "MM/YYYY";
  136. data = _dnsWebService.DnsServer.StatsManager.GetLastYearMonthWiseStats(utcFormat);
  137. break;
  138. case "custom":
  139. string strStartDate = request.GetQueryOrForm("start");
  140. string strEndDate = request.GetQueryOrForm("end");
  141. if (!DateTime.TryParse(strStartDate, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime startDate))
  142. throw new DnsWebServiceException("Invalid start date format.");
  143. if (!DateTime.TryParse(strEndDate, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime endDate))
  144. throw new DnsWebServiceException("Invalid end date format.");
  145. if (startDate > endDate)
  146. throw new DnsWebServiceException("Start date must be less than or equal to end date.");
  147. if ((Convert.ToInt32((endDate - startDate).TotalDays) + 1) > 7)
  148. {
  149. data = _dnsWebService.DnsServer.StatsManager.GetDayWiseStats(startDate, endDate, utcFormat);
  150. if (isLanguageEnUs)
  151. labelFormat = "MM/DD";
  152. else
  153. labelFormat = "DD/MM";
  154. }
  155. else
  156. {
  157. data = _dnsWebService.DnsServer.StatsManager.GetHourWiseStats(startDate, endDate, utcFormat);
  158. if (isLanguageEnUs)
  159. labelFormat = "MM/DD HH:00";
  160. else
  161. labelFormat = "DD/MM HH:00";
  162. }
  163. break;
  164. default:
  165. throw new DnsWebServiceException("Unknown stats type requested: " + strType);
  166. }
  167. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  168. //stats
  169. {
  170. List<KeyValuePair<string, long>> stats = data["stats"];
  171. jsonWriter.WritePropertyName("stats");
  172. jsonWriter.WriteStartObject();
  173. foreach (KeyValuePair<string, long> item in stats)
  174. jsonWriter.WriteNumber(item.Key, item.Value);
  175. jsonWriter.WriteNumber("zones", _dnsWebService.DnsServer.AuthZoneManager.TotalZones);
  176. jsonWriter.WriteNumber("cachedEntries", _dnsWebService.DnsServer.CacheZoneManager.TotalEntries);
  177. jsonWriter.WriteNumber("allowedZones", _dnsWebService.DnsServer.AllowedZoneManager.TotalZonesAllowed);
  178. jsonWriter.WriteNumber("blockedZones", _dnsWebService.DnsServer.BlockedZoneManager.TotalZonesBlocked);
  179. jsonWriter.WriteNumber("allowListZones", _dnsWebService.DnsServer.BlockListZoneManager.TotalZonesAllowed);
  180. jsonWriter.WriteNumber("blockListZones", _dnsWebService.DnsServer.BlockListZoneManager.TotalZonesBlocked);
  181. jsonWriter.WriteEndObject();
  182. }
  183. //main chart
  184. {
  185. jsonWriter.WritePropertyName("mainChartData");
  186. jsonWriter.WriteStartObject();
  187. //label format
  188. {
  189. jsonWriter.WriteString("labelFormat", labelFormat);
  190. }
  191. //label
  192. {
  193. List<KeyValuePair<string, long>> statsPerInterval = data["totalQueriesPerInterval"];
  194. jsonWriter.WritePropertyName("labels");
  195. jsonWriter.WriteStartArray();
  196. foreach (KeyValuePair<string, long> item in statsPerInterval)
  197. jsonWriter.WriteStringValue(item.Key);
  198. jsonWriter.WriteEndArray();
  199. }
  200. //datasets
  201. {
  202. jsonWriter.WritePropertyName("datasets");
  203. jsonWriter.WriteStartArray();
  204. WriteChartDataSet(jsonWriter, "Total", "rgba(102, 153, 255, 0.1)", "rgb(102, 153, 255)", data["totalQueriesPerInterval"]);
  205. WriteChartDataSet(jsonWriter, "No Error", "rgba(92, 184, 92, 0.1)", "rgb(92, 184, 92)", data["totalNoErrorPerInterval"]);
  206. WriteChartDataSet(jsonWriter, "Server Failure", "rgba(217, 83, 79, 0.1)", "rgb(217, 83, 79)", data["totalServerFailurePerInterval"]);
  207. WriteChartDataSet(jsonWriter, "NX Domain", "rgba(120, 120, 120, 0.1)", "rgb(120, 120, 120)", data["totalNxDomainPerInterval"]);
  208. WriteChartDataSet(jsonWriter, "Refused", "rgba(91, 192, 222, 0.1)", "rgb(91, 192, 222)", data["totalRefusedPerInterval"]);
  209. WriteChartDataSet(jsonWriter, "Authoritative", "rgba(150, 150, 0, 0.1)", "rgb(150, 150, 0)", data["totalAuthHitPerInterval"]);
  210. WriteChartDataSet(jsonWriter, "Recursive", "rgba(23, 162, 184, 0.1)", "rgb(23, 162, 184)", data["totalRecursionsPerInterval"]);
  211. WriteChartDataSet(jsonWriter, "Cached", "rgba(111, 84, 153, 0.1)", "rgb(111, 84, 153)", data["totalCacheHitPerInterval"]);
  212. WriteChartDataSet(jsonWriter, "Blocked", "rgba(255, 165, 0, 0.1)", "rgb(255, 165, 0)", data["totalBlockedPerInterval"]);
  213. WriteChartDataSet(jsonWriter, "Dropped", "rgba(30, 30, 30, 0.1)", "rgb(30, 30, 30)", data["totalDroppedPerInterval"]);
  214. WriteChartDataSet(jsonWriter, "Clients", "rgba(51, 122, 183, 0.1)", "rgb(51, 122, 183)", data["totalClientsPerInterval"]);
  215. jsonWriter.WriteEndArray();
  216. }
  217. jsonWriter.WriteEndObject();
  218. }
  219. //query response chart
  220. {
  221. jsonWriter.WritePropertyName("queryResponseChartData");
  222. jsonWriter.WriteStartObject();
  223. List<KeyValuePair<string, long>> stats = data["stats"];
  224. //labels
  225. {
  226. jsonWriter.WritePropertyName("labels");
  227. jsonWriter.WriteStartArray();
  228. foreach (KeyValuePair<string, long> item in stats)
  229. {
  230. switch (item.Key)
  231. {
  232. case "totalAuthoritative":
  233. jsonWriter.WriteStringValue("Authoritative");
  234. break;
  235. case "totalRecursive":
  236. jsonWriter.WriteStringValue("Recursive");
  237. break;
  238. case "totalCached":
  239. jsonWriter.WriteStringValue("Cached");
  240. break;
  241. case "totalBlocked":
  242. jsonWriter.WriteStringValue("Blocked");
  243. break;
  244. case "totalDropped":
  245. jsonWriter.WriteStringValue("Dropped");
  246. break;
  247. }
  248. }
  249. jsonWriter.WriteEndArray();
  250. }
  251. //datasets
  252. {
  253. jsonWriter.WritePropertyName("datasets");
  254. jsonWriter.WriteStartArray();
  255. jsonWriter.WriteStartObject();
  256. jsonWriter.WritePropertyName("data");
  257. jsonWriter.WriteStartArray();
  258. foreach (KeyValuePair<string, long> item in stats)
  259. {
  260. switch (item.Key)
  261. {
  262. case "totalAuthoritative":
  263. case "totalRecursive":
  264. case "totalCached":
  265. case "totalBlocked":
  266. case "totalDropped":
  267. jsonWriter.WriteNumberValue(item.Value);
  268. break;
  269. }
  270. }
  271. jsonWriter.WriteEndArray();
  272. jsonWriter.WritePropertyName("backgroundColor");
  273. jsonWriter.WriteStartArray();
  274. jsonWriter.WriteStringValue("rgba(150, 150, 0, 0.5)");
  275. jsonWriter.WriteStringValue("rgba(23, 162, 184, 0.5)");
  276. jsonWriter.WriteStringValue("rgba(111, 84, 153, 0.5)");
  277. jsonWriter.WriteStringValue("rgba(255, 165, 0, 0.5)");
  278. jsonWriter.WriteStringValue("rgba(7, 7, 7, 0.5)");
  279. jsonWriter.WriteEndArray();
  280. jsonWriter.WriteEndObject();
  281. jsonWriter.WriteEndArray();
  282. }
  283. jsonWriter.WriteEndObject();
  284. }
  285. //query type chart
  286. {
  287. jsonWriter.WritePropertyName("queryTypeChartData");
  288. jsonWriter.WriteStartObject();
  289. List<KeyValuePair<string, long>> queryTypes = data["queryTypes"];
  290. //labels
  291. {
  292. jsonWriter.WritePropertyName("labels");
  293. jsonWriter.WriteStartArray();
  294. foreach (KeyValuePair<string, long> item in queryTypes)
  295. jsonWriter.WriteStringValue(item.Key);
  296. jsonWriter.WriteEndArray();
  297. }
  298. //datasets
  299. {
  300. jsonWriter.WritePropertyName("datasets");
  301. jsonWriter.WriteStartArray();
  302. jsonWriter.WriteStartObject();
  303. jsonWriter.WritePropertyName("data");
  304. jsonWriter.WriteStartArray();
  305. foreach (KeyValuePair<string, long> item in queryTypes)
  306. jsonWriter.WriteNumberValue(item.Value);
  307. jsonWriter.WriteEndArray();
  308. jsonWriter.WritePropertyName("backgroundColor");
  309. jsonWriter.WriteStartArray();
  310. jsonWriter.WriteStringValue("rgba(102, 153, 255, 0.5)");
  311. jsonWriter.WriteStringValue("rgba(92, 184, 92, 0.5)");
  312. jsonWriter.WriteStringValue("rgba(7, 7, 7, 0.5)");
  313. jsonWriter.WriteStringValue("rgba(91, 192, 222, 0.5)");
  314. jsonWriter.WriteStringValue("rgba(150, 150, 0, 0.5)");
  315. jsonWriter.WriteStringValue("rgba(23, 162, 184, 0.5)");
  316. jsonWriter.WriteStringValue("rgba(111, 84, 153, 0.5)");
  317. jsonWriter.WriteStringValue("rgba(255, 165, 0, 0.5)");
  318. jsonWriter.WriteStringValue("rgba(51, 122, 183, 0.5)");
  319. jsonWriter.WriteStringValue("rgba(150, 150, 150, 0.5)");
  320. jsonWriter.WriteEndArray();
  321. jsonWriter.WriteEndObject();
  322. jsonWriter.WriteEndArray();
  323. }
  324. jsonWriter.WriteEndObject();
  325. }
  326. //protocol type chart
  327. {
  328. jsonWriter.WritePropertyName("protocolTypeChartData");
  329. jsonWriter.WriteStartObject();
  330. List<KeyValuePair<string, long>> protocolTypes = data["protocolTypes"];
  331. //labels
  332. {
  333. jsonWriter.WritePropertyName("labels");
  334. jsonWriter.WriteStartArray();
  335. foreach (KeyValuePair<string, long> item in protocolTypes)
  336. jsonWriter.WriteStringValue(item.Key);
  337. jsonWriter.WriteEndArray();
  338. }
  339. //datasets
  340. {
  341. jsonWriter.WritePropertyName("datasets");
  342. jsonWriter.WriteStartArray();
  343. jsonWriter.WriteStartObject();
  344. jsonWriter.WritePropertyName("data");
  345. jsonWriter.WriteStartArray();
  346. foreach (KeyValuePair<string, long> item in protocolTypes)
  347. jsonWriter.WriteNumberValue(item.Value);
  348. jsonWriter.WriteEndArray();
  349. jsonWriter.WritePropertyName("backgroundColor");
  350. jsonWriter.WriteStartArray();
  351. jsonWriter.WriteStringValue("rgba(111, 84, 153, 0.5)");
  352. jsonWriter.WriteStringValue("rgba(150, 150, 0, 0.5)");
  353. jsonWriter.WriteStringValue("rgba(23, 162, 184, 0.5)"); ;
  354. jsonWriter.WriteStringValue("rgba(255, 165, 0, 0.5)");
  355. jsonWriter.WriteStringValue("rgba(91, 192, 222, 0.5)");
  356. jsonWriter.WriteEndArray();
  357. jsonWriter.WriteEndObject();
  358. jsonWriter.WriteEndArray();
  359. }
  360. jsonWriter.WriteEndObject();
  361. }
  362. //top clients
  363. {
  364. List<KeyValuePair<string, long>> topClients = data["topClients"];
  365. IDictionary<string, string> clientIpMap = await ResolvePtrTopClientsAsync(topClients);
  366. jsonWriter.WritePropertyName("topClients");
  367. jsonWriter.WriteStartArray();
  368. foreach (KeyValuePair<string, long> item in topClients)
  369. {
  370. jsonWriter.WriteStartObject();
  371. jsonWriter.WriteString("name", item.Key);
  372. if (clientIpMap.TryGetValue(item.Key, out string clientDomain) && !string.IsNullOrEmpty(clientDomain))
  373. jsonWriter.WriteString("domain", clientDomain);
  374. jsonWriter.WriteNumber("hits", item.Value);
  375. jsonWriter.WriteBoolean("rateLimited", _dnsWebService.DnsServer.IsQpmLimitCrossed(IPAddress.Parse(item.Key)));
  376. jsonWriter.WriteEndObject();
  377. }
  378. jsonWriter.WriteEndArray();
  379. }
  380. //top domains
  381. {
  382. List<KeyValuePair<string, long>> topDomains = data["topDomains"];
  383. jsonWriter.WritePropertyName("topDomains");
  384. jsonWriter.WriteStartArray();
  385. foreach (KeyValuePair<string, long> item in topDomains)
  386. {
  387. jsonWriter.WriteStartObject();
  388. jsonWriter.WriteString("name", item.Key);
  389. if (DnsClient.TryConvertDomainNameToUnicode(item.Key, out string idn))
  390. jsonWriter.WriteString("nameIdn", idn);
  391. jsonWriter.WriteNumber("hits", item.Value);
  392. jsonWriter.WriteEndObject();
  393. }
  394. jsonWriter.WriteEndArray();
  395. }
  396. //top blocked domains
  397. {
  398. List<KeyValuePair<string, long>> topBlockedDomains = data["topBlockedDomains"];
  399. jsonWriter.WritePropertyName("topBlockedDomains");
  400. jsonWriter.WriteStartArray();
  401. foreach (KeyValuePair<string, long> item in topBlockedDomains)
  402. {
  403. jsonWriter.WriteStartObject();
  404. jsonWriter.WriteString("name", item.Key);
  405. if (DnsClient.TryConvertDomainNameToUnicode(item.Key, out string idn))
  406. jsonWriter.WriteString("nameIdn", idn);
  407. jsonWriter.WriteNumber("hits", item.Value);
  408. jsonWriter.WriteEndObject();
  409. }
  410. jsonWriter.WriteEndArray();
  411. }
  412. }
  413. public async Task GetTopStats(HttpContext context)
  414. {
  415. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Dashboard, context.GetCurrentSession().User, PermissionFlag.View))
  416. throw new DnsWebServiceException("Access was denied.");
  417. HttpRequest request = context.Request;
  418. string strType = request.GetQueryOrForm("type", "lastHour");
  419. TopStatsType statsType = request.GetQueryOrFormEnum<TopStatsType>("statsType");
  420. int limit = request.GetQueryOrForm("limit", int.Parse, 1000);
  421. List<KeyValuePair<string, long>> topStatsData;
  422. switch (strType.ToLowerInvariant())
  423. {
  424. case "lasthour":
  425. topStatsData = _dnsWebService.DnsServer.StatsManager.GetLastHourTopStats(statsType, limit);
  426. break;
  427. case "lastday":
  428. topStatsData = _dnsWebService.DnsServer.StatsManager.GetLastDayTopStats(statsType, limit);
  429. break;
  430. case "lastweek":
  431. topStatsData = _dnsWebService.DnsServer.StatsManager.GetLastWeekTopStats(statsType, limit);
  432. break;
  433. case "lastmonth":
  434. topStatsData = _dnsWebService.DnsServer.StatsManager.GetLastMonthTopStats(statsType, limit);
  435. break;
  436. case "lastyear":
  437. topStatsData = _dnsWebService.DnsServer.StatsManager.GetLastYearTopStats(statsType, limit);
  438. break;
  439. case "custom":
  440. string strStartDate = request.GetQueryOrForm("start");
  441. string strEndDate = request.GetQueryOrForm("end");
  442. if (!DateTime.TryParseExact(strStartDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime startDate))
  443. throw new DnsWebServiceException("Invalid start date format.");
  444. if (!DateTime.TryParseExact(strEndDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime endDate))
  445. throw new DnsWebServiceException("Invalid end date format.");
  446. if (startDate > endDate)
  447. throw new DnsWebServiceException("Start date must be less than or equal to end date.");
  448. if ((Convert.ToInt32((endDate - startDate).TotalDays) + 1) > 7)
  449. topStatsData = _dnsWebService.DnsServer.StatsManager.GetDayWiseTopStats(startDate, endDate, statsType, limit);
  450. else
  451. topStatsData = _dnsWebService.DnsServer.StatsManager.GetHourWiseTopStats(startDate, endDate, statsType, limit);
  452. break;
  453. default:
  454. throw new DnsWebServiceException("Unknown stats type requested: " + strType);
  455. }
  456. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  457. switch (statsType)
  458. {
  459. case TopStatsType.TopClients:
  460. {
  461. bool noReverseLookup = request.GetQueryOrForm("noReverseLookup", bool.Parse, false);
  462. bool onlyRateLimitedClients = request.GetQueryOrForm("onlyRateLimitedClients", bool.Parse, false);
  463. IDictionary<string, string> clientIpMap = null;
  464. if (!noReverseLookup)
  465. clientIpMap = await ResolvePtrTopClientsAsync(topStatsData);
  466. jsonWriter.WritePropertyName("topClients");
  467. jsonWriter.WriteStartArray();
  468. foreach (KeyValuePair<string, long> item in topStatsData)
  469. {
  470. bool rateLimited = _dnsWebService.DnsServer.IsQpmLimitCrossed(IPAddress.Parse(item.Key));
  471. if (onlyRateLimitedClients && !rateLimited)
  472. continue;
  473. jsonWriter.WriteStartObject();
  474. jsonWriter.WriteString("name", item.Key);
  475. if ((clientIpMap is not null) && clientIpMap.TryGetValue(item.Key, out string clientDomain) && !string.IsNullOrEmpty(clientDomain))
  476. jsonWriter.WriteString("domain", clientDomain);
  477. jsonWriter.WriteNumber("hits", item.Value);
  478. jsonWriter.WriteBoolean("rateLimited", rateLimited);
  479. jsonWriter.WriteEndObject();
  480. }
  481. jsonWriter.WriteEndArray();
  482. }
  483. break;
  484. case TopStatsType.TopDomains:
  485. {
  486. jsonWriter.WritePropertyName("topDomains");
  487. jsonWriter.WriteStartArray();
  488. foreach (KeyValuePair<string, long> item in topStatsData)
  489. {
  490. jsonWriter.WriteStartObject();
  491. jsonWriter.WriteString("name", item.Key);
  492. if (DnsClient.TryConvertDomainNameToUnicode(item.Key, out string idn))
  493. jsonWriter.WriteString("nameIdn", idn);
  494. jsonWriter.WriteNumber("hits", item.Value);
  495. jsonWriter.WriteEndObject();
  496. }
  497. jsonWriter.WriteEndArray();
  498. }
  499. break;
  500. case TopStatsType.TopBlockedDomains:
  501. {
  502. jsonWriter.WritePropertyName("topBlockedDomains");
  503. jsonWriter.WriteStartArray();
  504. foreach (KeyValuePair<string, long> item in topStatsData)
  505. {
  506. jsonWriter.WriteStartObject();
  507. jsonWriter.WriteString("name", item.Key);
  508. if (DnsClient.TryConvertDomainNameToUnicode(item.Key, out string idn))
  509. jsonWriter.WriteString("nameIdn", idn);
  510. jsonWriter.WriteNumber("hits", item.Value);
  511. jsonWriter.WriteEndObject();
  512. }
  513. jsonWriter.WriteEndArray();
  514. }
  515. break;
  516. default:
  517. throw new NotSupportedException();
  518. }
  519. }
  520. #endregion
  521. }
  522. }