DnsApplicationManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 System;
  17. using System.Collections.Concurrent;
  18. using System.Collections.Generic;
  19. using System.IO;
  20. using System.IO.Compression;
  21. using System.Text;
  22. using System.Threading.Tasks;
  23. namespace DnsServerCore.Dns.Applications
  24. {
  25. public sealed class DnsApplicationManager : IDisposable
  26. {
  27. #region variables
  28. readonly DnsServer _dnsServer;
  29. readonly string _appsPath;
  30. readonly ConcurrentDictionary<string, DnsApplication> _applications = new ConcurrentDictionary<string, DnsApplication>();
  31. IReadOnlyList<IDnsRequestController> _dnsRequestControllers = Array.Empty<IDnsRequestController>();
  32. IReadOnlyList<IDnsAuthoritativeRequestHandler> _dnsAuthoritativeRequestHandlers = Array.Empty<IDnsAuthoritativeRequestHandler>();
  33. IReadOnlyList<IDnsRequestBlockingHandler> _dnsRequestBlockingHandlers = Array.Empty<IDnsRequestBlockingHandler>();
  34. IReadOnlyList<IDnsQueryLogger> _dnsQueryLoggers = Array.Empty<IDnsQueryLogger>();
  35. IReadOnlyList<IDnsPostProcessor> _dnsPostProcessors = Array.Empty<IDnsPostProcessor>();
  36. #endregion
  37. #region constructor
  38. public DnsApplicationManager(DnsServer dnsServer)
  39. {
  40. _dnsServer = dnsServer;
  41. _appsPath = Path.Combine(_dnsServer.ConfigFolder, "apps");
  42. if (!Directory.Exists(_appsPath))
  43. Directory.CreateDirectory(_appsPath);
  44. }
  45. #endregion
  46. #region IDisposable
  47. bool _disposed;
  48. private void Dispose(bool disposing)
  49. {
  50. if (_disposed)
  51. return;
  52. if (disposing)
  53. {
  54. if (_applications != null)
  55. UnloadAllApplications();
  56. }
  57. _disposed = true;
  58. }
  59. public void Dispose()
  60. {
  61. Dispose(true);
  62. }
  63. #endregion
  64. #region private
  65. private async Task<DnsApplication> LoadApplicationAsync(string applicationFolder, bool refreshAppObjectList)
  66. {
  67. string applicationName = Path.GetFileName(applicationFolder);
  68. DnsApplication application = new DnsApplication(new DnsServerInternal(_dnsServer, applicationName, applicationFolder), applicationName);
  69. await application.InitializeAsync();
  70. if (!_applications.TryAdd(application.Name, application))
  71. {
  72. application.Dispose();
  73. throw new DnsServerException("DNS application already exists: " + application.Name);
  74. }
  75. if (refreshAppObjectList)
  76. RefreshAppObjectLists();
  77. return application;
  78. }
  79. private void UnloadApplication(string applicationName)
  80. {
  81. if (!_applications.TryRemove(applicationName, out DnsApplication existingApp))
  82. throw new DnsServerException("DNS application does not exists: " + applicationName);
  83. RefreshAppObjectLists();
  84. existingApp.Dispose();
  85. }
  86. private void RefreshAppObjectLists()
  87. {
  88. List<IDnsRequestController> dnsRequestControllers = new List<IDnsRequestController>(1);
  89. List<IDnsAuthoritativeRequestHandler> dnsAuthoritativeRequestHandlers = new List<IDnsAuthoritativeRequestHandler>(1);
  90. List<IDnsRequestBlockingHandler> dnsRequestBlockingHandlers = new List<IDnsRequestBlockingHandler>(1);
  91. List<IDnsQueryLogger> dnsQueryLoggers = new List<IDnsQueryLogger>(1);
  92. List<IDnsPostProcessor> dnsPostProcessors = new List<IDnsPostProcessor>(1);
  93. foreach (KeyValuePair<string, DnsApplication> application in _applications)
  94. {
  95. foreach (KeyValuePair<string, IDnsRequestController> controller in application.Value.DnsRequestControllers)
  96. dnsRequestControllers.Add(controller.Value);
  97. foreach (KeyValuePair<string, IDnsAuthoritativeRequestHandler> handler in application.Value.DnsAuthoritativeRequestHandlers)
  98. dnsAuthoritativeRequestHandlers.Add(handler.Value);
  99. foreach (KeyValuePair<string, IDnsRequestBlockingHandler> blocker in application.Value.DnsRequestBlockingHandler)
  100. dnsRequestBlockingHandlers.Add(blocker.Value);
  101. foreach (KeyValuePair<string, IDnsQueryLogger> logger in application.Value.DnsQueryLoggers)
  102. dnsQueryLoggers.Add(logger.Value);
  103. foreach (KeyValuePair<string, IDnsPostProcessor> processor in application.Value.DnsPostProcessors)
  104. dnsPostProcessors.Add(processor.Value);
  105. }
  106. _dnsRequestControllers = dnsRequestControllers;
  107. _dnsAuthoritativeRequestHandlers = dnsAuthoritativeRequestHandlers;
  108. _dnsRequestBlockingHandlers = dnsRequestBlockingHandlers;
  109. _dnsQueryLoggers = dnsQueryLoggers;
  110. _dnsPostProcessors = dnsPostProcessors;
  111. }
  112. #endregion
  113. #region public
  114. public void UnloadAllApplications()
  115. {
  116. foreach (KeyValuePair<string, DnsApplication> application in _applications)
  117. {
  118. try
  119. {
  120. application.Value.Dispose();
  121. }
  122. catch (Exception ex)
  123. {
  124. LogManager log = _dnsServer.LogManager;
  125. if (log != null)
  126. log.Write(ex);
  127. }
  128. }
  129. _applications.Clear();
  130. _dnsRequestControllers = Array.Empty<IDnsRequestController>();
  131. _dnsAuthoritativeRequestHandlers = Array.Empty<IDnsAuthoritativeRequestHandler>();
  132. _dnsRequestBlockingHandlers = Array.Empty<IDnsRequestBlockingHandler>();
  133. _dnsQueryLoggers = Array.Empty<IDnsQueryLogger>();
  134. _dnsPostProcessors = Array.Empty<IDnsPostProcessor>();
  135. }
  136. public void LoadAllApplications()
  137. {
  138. UnloadAllApplications();
  139. foreach (string applicationFolder in Directory.GetDirectories(_appsPath))
  140. {
  141. Task.Run(async delegate ()
  142. {
  143. try
  144. {
  145. _ = await LoadApplicationAsync(applicationFolder, false);
  146. RefreshAppObjectLists();
  147. LogManager log = _dnsServer.LogManager;
  148. if (log != null)
  149. log.Write("DNS Server successfully loaded DNS application: " + Path.GetFileName(applicationFolder));
  150. }
  151. catch (Exception ex)
  152. {
  153. LogManager log = _dnsServer.LogManager;
  154. if (log != null)
  155. log.Write("DNS Server failed to load DNS application: " + Path.GetFileName(applicationFolder) + "\r\n" + ex.ToString());
  156. }
  157. });
  158. }
  159. }
  160. public async Task<DnsApplication> InstallApplicationAsync(string applicationName, Stream appStream)
  161. {
  162. foreach (char invalidChar in Path.GetInvalidFileNameChars())
  163. {
  164. if (applicationName.Contains(invalidChar))
  165. throw new DnsServerException("The application name contains an invalid character: " + invalidChar);
  166. }
  167. if (_applications.ContainsKey(applicationName))
  168. throw new DnsServerException("DNS application already exists: " + applicationName);
  169. using (ZipArchive appZip = new ZipArchive(appStream, ZipArchiveMode.Read, false, Encoding.UTF8))
  170. {
  171. string applicationFolder = Path.Combine(_appsPath, applicationName);
  172. if (Directory.Exists(applicationFolder))
  173. Directory.Delete(applicationFolder, true);
  174. try
  175. {
  176. appZip.ExtractToDirectory(applicationFolder, true);
  177. return await LoadApplicationAsync(applicationFolder, true);
  178. }
  179. catch
  180. {
  181. if (Directory.Exists(applicationFolder))
  182. Directory.Delete(applicationFolder, true);
  183. throw;
  184. }
  185. }
  186. }
  187. public async Task<DnsApplication> UpdateApplicationAsync(string applicationName, Stream appStream)
  188. {
  189. if (!_applications.ContainsKey(applicationName))
  190. throw new DnsServerException("DNS application does not exists: " + applicationName);
  191. using (ZipArchive appZip = new ZipArchive(appStream, ZipArchiveMode.Read, false, Encoding.UTF8))
  192. {
  193. UnloadApplication(applicationName);
  194. string applicationFolder = Path.Combine(_appsPath, applicationName);
  195. foreach (ZipArchiveEntry entry in appZip.Entries)
  196. {
  197. string entryPath = entry.FullName;
  198. if (Path.DirectorySeparatorChar != '/')
  199. entryPath = entryPath.Replace('/', '\\');
  200. string filePath = Path.Combine(applicationFolder, entryPath);
  201. if ((entry.Name == "dnsApp.config") && File.Exists(filePath))
  202. continue; //avoid overwriting existing config file
  203. Directory.CreateDirectory(Path.GetDirectoryName(filePath));
  204. entry.ExtractToFile(filePath, true);
  205. }
  206. return await LoadApplicationAsync(applicationFolder, true);
  207. }
  208. }
  209. public void UninstallApplication(string applicationName)
  210. {
  211. if (_applications.TryRemove(applicationName, out DnsApplication app))
  212. {
  213. RefreshAppObjectLists();
  214. app.Dispose();
  215. if (Directory.Exists(app.DnsServer.ApplicationFolder))
  216. Directory.Delete(app.DnsServer.ApplicationFolder, true);
  217. }
  218. }
  219. #endregion
  220. #region properties
  221. public IReadOnlyDictionary<string, DnsApplication> Applications
  222. { get { return _applications; } }
  223. public IReadOnlyList<IDnsRequestController> DnsRequestControllers
  224. { get { return _dnsRequestControllers; } }
  225. public IReadOnlyList<IDnsAuthoritativeRequestHandler> DnsAuthoritativeRequestHandlers
  226. { get { return _dnsAuthoritativeRequestHandlers; } }
  227. public IReadOnlyList<IDnsRequestBlockingHandler> DnsRequestBlockingHandlers
  228. { get { return _dnsRequestBlockingHandlers; } }
  229. public IReadOnlyList<IDnsQueryLogger> DnsQueryLoggers
  230. { get { return _dnsQueryLoggers; } }
  231. public IReadOnlyList<IDnsPostProcessor> DnsPostProcessors
  232. { get { return _dnsPostProcessors; } }
  233. #endregion
  234. }
  235. }