DnsApplicationManager.cs 11 KB

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