WebServiceLogsApi.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2023 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 DnsServerCore.Auth;
  17. using DnsServerCore.Dns.Applications;
  18. using Microsoft.AspNetCore.Http;
  19. using System;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Net;
  23. using System.Text.Json;
  24. using System.Threading.Tasks;
  25. using TechnitiumLibrary.Net;
  26. using TechnitiumLibrary.Net.Dns;
  27. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  28. namespace DnsServerCore
  29. {
  30. class WebServiceLogsApi
  31. {
  32. #region variables
  33. readonly DnsWebService _dnsWebService;
  34. #endregion
  35. #region constructor
  36. public WebServiceLogsApi(DnsWebService dnsWebService)
  37. {
  38. _dnsWebService = dnsWebService;
  39. }
  40. #endregion
  41. #region public
  42. public void ListLogs(HttpContext context)
  43. {
  44. UserSession session = context.GetCurrentSession();
  45. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View))
  46. throw new DnsWebServiceException("Access was denied.");
  47. string[] logFiles = _dnsWebService._log.ListLogFiles();
  48. Array.Sort(logFiles);
  49. Array.Reverse(logFiles);
  50. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  51. jsonWriter.WritePropertyName("logFiles");
  52. jsonWriter.WriteStartArray();
  53. foreach (string logFile in logFiles)
  54. {
  55. jsonWriter.WriteStartObject();
  56. jsonWriter.WriteString("fileName", Path.GetFileNameWithoutExtension(logFile));
  57. jsonWriter.WriteString("size", WebUtilities.GetFormattedSize(new FileInfo(logFile).Length));
  58. jsonWriter.WriteEndObject();
  59. }
  60. jsonWriter.WriteEndArray();
  61. }
  62. public Task DownloadLogAsync(HttpContext context)
  63. {
  64. UserSession session = context.GetCurrentSession();
  65. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View))
  66. throw new DnsWebServiceException("Access was denied.");
  67. HttpRequest request = context.Request;
  68. string fileName = request.GetQueryOrForm("fileName");
  69. int limit = request.GetQueryOrForm("limit", int.Parse, 0);
  70. return _dnsWebService._log.DownloadLogAsync(context, fileName, limit * 1024 * 1024);
  71. }
  72. public void DeleteLog(HttpContext context)
  73. {
  74. UserSession session = context.GetCurrentSession();
  75. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.Delete))
  76. throw new DnsWebServiceException("Access was denied.");
  77. HttpRequest request = context.Request;
  78. string log = request.GetQueryOrForm("log");
  79. _dnsWebService._log.DeleteLog(log);
  80. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] Log file was deleted: " + log);
  81. }
  82. public void DeleteAllLogs(HttpContext context)
  83. {
  84. UserSession session = context.GetCurrentSession();
  85. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.Delete))
  86. throw new DnsWebServiceException("Access was denied.");
  87. _dnsWebService._log.DeleteAllLogs();
  88. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] All log files were deleted.");
  89. }
  90. public void DeleteAllStats(HttpContext context)
  91. {
  92. UserSession session = context.GetCurrentSession();
  93. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Dashboard, session.User, PermissionFlag.Delete))
  94. throw new DnsWebServiceException("Access was denied.");
  95. _dnsWebService.DnsServer.StatsManager.DeleteAllStats();
  96. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] All stats files were deleted.");
  97. }
  98. public async Task QueryLogsAsync(HttpContext context)
  99. {
  100. UserSession session = context.GetCurrentSession();
  101. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View))
  102. throw new DnsWebServiceException("Access was denied.");
  103. HttpRequest request = context.Request;
  104. string name = request.GetQueryOrForm("name");
  105. string classPath = request.GetQueryOrForm("classPath");
  106. if (!_dnsWebService.DnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
  107. throw new DnsWebServiceException("DNS application was not found: " + name);
  108. if (!application.DnsQueryLoggers.TryGetValue(classPath, out IDnsQueryLogger logger))
  109. throw new DnsWebServiceException("DNS application '" + classPath + "' class path was not found: " + name);
  110. long pageNumber = request.GetQueryOrForm("pageNumber", long.Parse, 1);
  111. int entriesPerPage = request.GetQueryOrForm("entriesPerPage", int.Parse, 25);
  112. bool descendingOrder = request.GetQueryOrForm("descendingOrder", bool.Parse, true);
  113. DateTime? start = null;
  114. string strStart = request.QueryOrForm("start");
  115. if (!string.IsNullOrEmpty(strStart))
  116. start = DateTime.Parse(strStart, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
  117. DateTime? end = null;
  118. string strEnd = request.QueryOrForm("end");
  119. if (!string.IsNullOrEmpty(strEnd))
  120. end = DateTime.Parse(strEnd, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
  121. IPAddress clientIpAddress = request.GetQueryOrForm("clientIpAddress", IPAddress.Parse, null);
  122. DnsTransportProtocol? protocol = null;
  123. string strProtocol = request.QueryOrForm("protocol");
  124. if (!string.IsNullOrEmpty(strProtocol))
  125. protocol = Enum.Parse<DnsTransportProtocol>(strProtocol, true);
  126. DnsServerResponseType? responseType = null;
  127. string strResponseType = request.QueryOrForm("responseType");
  128. if (!string.IsNullOrEmpty(strResponseType))
  129. responseType = Enum.Parse<DnsServerResponseType>(strResponseType, true);
  130. DnsResponseCode? rcode = null;
  131. string strRcode = request.QueryOrForm("rcode");
  132. if (!string.IsNullOrEmpty(strRcode))
  133. rcode = Enum.Parse<DnsResponseCode>(strRcode, true);
  134. string qname = request.GetQueryOrForm("qname", null);
  135. DnsResourceRecordType? qtype = null;
  136. string strQtype = request.QueryOrForm("qtype");
  137. if (!string.IsNullOrEmpty(strQtype))
  138. qtype = Enum.Parse<DnsResourceRecordType>(strQtype, true);
  139. DnsClass? qclass = null;
  140. string strQclass = request.QueryOrForm("qclass");
  141. if (!string.IsNullOrEmpty(strQclass))
  142. qclass = Enum.Parse<DnsClass>(strQclass, true);
  143. DnsLogPage page = await logger.QueryLogsAsync(pageNumber, entriesPerPage, descendingOrder, start, end, clientIpAddress, protocol, responseType, rcode, qname, qtype, qclass);
  144. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  145. jsonWriter.WriteNumber("pageNumber", page.PageNumber);
  146. jsonWriter.WriteNumber("totalPages", page.TotalPages);
  147. jsonWriter.WriteNumber("totalEntries", page.TotalEntries);
  148. jsonWriter.WritePropertyName("entries");
  149. jsonWriter.WriteStartArray();
  150. foreach (DnsLogEntry entry in page.Entries)
  151. {
  152. jsonWriter.WriteStartObject();
  153. jsonWriter.WriteNumber("rowNumber", entry.RowNumber);
  154. jsonWriter.WriteString("timestamp", entry.Timestamp);
  155. jsonWriter.WriteString("clientIpAddress", entry.ClientIpAddress.ToString());
  156. jsonWriter.WriteString("protocol", entry.Protocol.ToString());
  157. jsonWriter.WriteString("responseType", entry.ResponseType.ToString());
  158. jsonWriter.WriteString("rcode", entry.RCODE.ToString());
  159. jsonWriter.WriteString("qname", entry.Question?.Name);
  160. jsonWriter.WriteString("qtype", entry.Question?.Type.ToString());
  161. jsonWriter.WriteString("qclass", entry.Question?.Class.ToString());
  162. jsonWriter.WriteString("answer", entry.Answer);
  163. jsonWriter.WriteEndObject();
  164. }
  165. jsonWriter.WriteEndArray();
  166. }
  167. #endregion
  168. }
  169. }