DnsApplication.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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.Generic;
  18. using System.IO;
  19. using System.Reflection;
  20. using System.Runtime.Loader;
  21. using System.Threading.Tasks;
  22. namespace DnsServerCore.Dns.Applications
  23. {
  24. public sealed class DnsApplication : IDisposable
  25. {
  26. #region variables
  27. readonly IDnsServer _dnsServer;
  28. readonly string _name;
  29. readonly DnsApplicationAssemblyLoadContext _appContext;
  30. readonly string _description;
  31. readonly Version _version;
  32. readonly IReadOnlyDictionary<string, IDnsApplication> _dnsApplications;
  33. readonly IReadOnlyDictionary<string, IDnsAppRecordRequestHandler> _dnsAppRecordRequestHandlers;
  34. readonly IReadOnlyDictionary<string, IDnsRequestController> _dnsRequestControllers;
  35. readonly IReadOnlyDictionary<string, IDnsAuthoritativeRequestHandler> _dnsAuthoritativeRequestHandlers;
  36. readonly IReadOnlyDictionary<string, IDnsQueryLogger> _dnsQueryLoggers;
  37. readonly IReadOnlyDictionary<string, IDnsPostProcessor> _dnsPostProcessors;
  38. #endregion
  39. #region constructor
  40. public DnsApplication(IDnsServer dnsServer, string name)
  41. {
  42. _dnsServer = dnsServer;
  43. _name = name;
  44. _appContext = new DnsApplicationAssemblyLoadContext(_dnsServer.ApplicationFolder);
  45. //load app assemblies
  46. IEnumerable<Assembly> loadedAssemblies = AssemblyLoadContext.Default.Assemblies;
  47. List<Assembly> appAssemblies = new List<Assembly>();
  48. foreach (string dllFile in Directory.GetFiles(_dnsServer.ApplicationFolder, "*.dll", SearchOption.TopDirectoryOnly))
  49. {
  50. string dllFileName = Path.GetFileNameWithoutExtension(dllFile);
  51. bool isLoaded = false;
  52. foreach (Assembly loadedAssembly in loadedAssemblies)
  53. {
  54. if (!string.IsNullOrEmpty(loadedAssembly.Location))
  55. {
  56. if (Path.GetFileNameWithoutExtension(loadedAssembly.Location).Equals(dllFileName, StringComparison.OrdinalIgnoreCase))
  57. {
  58. isLoaded = true;
  59. break;
  60. }
  61. }
  62. else
  63. {
  64. AssemblyName assemblyName = loadedAssembly.GetName();
  65. if ((assemblyName.Name != null) && assemblyName.Name.Equals(dllFileName, StringComparison.OrdinalIgnoreCase))
  66. {
  67. isLoaded = true;
  68. break;
  69. }
  70. }
  71. }
  72. if (isLoaded)
  73. continue;
  74. try
  75. {
  76. string pdbFile = Path.Combine(_dnsServer.ApplicationFolder, Path.GetFileNameWithoutExtension(dllFile) + ".pdb");
  77. if (File.Exists(pdbFile))
  78. {
  79. using (FileStream dllStream = new FileStream(dllFile, FileMode.Open, FileAccess.Read))
  80. {
  81. using (FileStream pdbStream = new FileStream(pdbFile, FileMode.Open, FileAccess.Read))
  82. {
  83. appAssemblies.Add(_appContext.LoadFromStream(dllStream, pdbStream));
  84. }
  85. }
  86. }
  87. else
  88. {
  89. using (FileStream dllStream = new FileStream(dllFile, FileMode.Open, FileAccess.Read))
  90. {
  91. appAssemblies.Add(_appContext.LoadFromStream(dllStream));
  92. }
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. _dnsServer.WriteLog(ex);
  98. }
  99. }
  100. //load apps
  101. Dictionary<string, IDnsApplication> dnsApplications = new Dictionary<string, IDnsApplication>();
  102. Dictionary<string, IDnsAppRecordRequestHandler> dnsAppRecordRequestHandlers = new Dictionary<string, IDnsAppRecordRequestHandler>(2);
  103. Dictionary<string, IDnsRequestController> dnsRequestControllers = new Dictionary<string, IDnsRequestController>(1);
  104. Dictionary<string, IDnsAuthoritativeRequestHandler> dnsAuthoritativeRequestHandlers = new Dictionary<string, IDnsAuthoritativeRequestHandler>(1);
  105. Dictionary<string, IDnsQueryLogger> dnsQueryLoggers = new Dictionary<string, IDnsQueryLogger>(1);
  106. Dictionary<string, IDnsPostProcessor> dnsPostProcessors = new Dictionary<string, IDnsPostProcessor>(1);
  107. Type dnsApplicationInterface = typeof(IDnsApplication);
  108. foreach (Assembly appAssembly in appAssemblies)
  109. {
  110. try
  111. {
  112. foreach (Type classType in appAssembly.ExportedTypes)
  113. {
  114. bool isDnsApp = false;
  115. foreach (Type interfaceType in classType.GetInterfaces())
  116. {
  117. if (interfaceType == dnsApplicationInterface)
  118. {
  119. isDnsApp = true;
  120. break;
  121. }
  122. }
  123. if (isDnsApp)
  124. {
  125. try
  126. {
  127. IDnsApplication app = Activator.CreateInstance(classType) as IDnsApplication;
  128. dnsApplications.Add(classType.FullName, app);
  129. if (app is IDnsAppRecordRequestHandler appRecordHandler)
  130. dnsAppRecordRequestHandlers.Add(classType.FullName, appRecordHandler);
  131. if (app is IDnsRequestController requestController)
  132. dnsRequestControllers.Add(classType.FullName, requestController);
  133. if (app is IDnsAuthoritativeRequestHandler requestHandler)
  134. dnsAuthoritativeRequestHandlers.Add(classType.FullName, requestHandler);
  135. if (app is IDnsQueryLogger logger)
  136. dnsQueryLoggers.Add(classType.FullName, logger);
  137. if (app is IDnsPostProcessor postProcessor)
  138. dnsPostProcessors.Add(classType.FullName, postProcessor);
  139. if (_description is null)
  140. {
  141. AssemblyDescriptionAttribute attribute = appAssembly.GetCustomAttribute<AssemblyDescriptionAttribute>();
  142. if (attribute is not null)
  143. _description = attribute.Description.Replace("\\n", "\n");
  144. }
  145. if (_version is null)
  146. _version = appAssembly.GetName().Version;
  147. }
  148. catch (Exception ex)
  149. {
  150. _dnsServer.WriteLog(ex);
  151. }
  152. }
  153. }
  154. }
  155. catch (Exception ex)
  156. {
  157. _dnsServer.WriteLog(ex);
  158. }
  159. }
  160. if (_version is null)
  161. {
  162. if (dnsApplications.Count > 0)
  163. _version = new Version(1, 0);
  164. else
  165. _version = new Version(0, 0);
  166. }
  167. _dnsApplications = dnsApplications;
  168. _dnsAppRecordRequestHandlers = dnsAppRecordRequestHandlers;
  169. _dnsRequestControllers = dnsRequestControllers;
  170. _dnsAuthoritativeRequestHandlers = dnsAuthoritativeRequestHandlers;
  171. _dnsQueryLoggers = dnsQueryLoggers;
  172. _dnsPostProcessors = dnsPostProcessors;
  173. }
  174. #endregion
  175. #region IDisposable
  176. bool _disposed;
  177. private void Dispose(bool disposing)
  178. {
  179. if (_disposed)
  180. return;
  181. if (disposing)
  182. {
  183. if (_dnsApplications is not null)
  184. {
  185. foreach (KeyValuePair<string, IDnsApplication> app in _dnsApplications)
  186. app.Value.Dispose();
  187. }
  188. if (_appContext != null)
  189. _appContext.Unload();
  190. }
  191. _disposed = true;
  192. }
  193. public void Dispose()
  194. {
  195. Dispose(true);
  196. }
  197. #endregion
  198. #region internal
  199. internal async Task InitializeAsync()
  200. {
  201. string config = await GetConfigAsync();
  202. foreach (KeyValuePair<string, IDnsApplication> app in _dnsApplications)
  203. {
  204. try
  205. {
  206. await app.Value.InitializeAsync(_dnsServer, config);
  207. }
  208. catch (Exception ex)
  209. {
  210. _dnsServer.WriteLog(ex);
  211. }
  212. }
  213. }
  214. #endregion
  215. #region public
  216. public Task<string> GetConfigAsync()
  217. {
  218. string configFile = Path.Combine(_dnsServer.ApplicationFolder, "dnsApp.config");
  219. if (File.Exists(configFile))
  220. return File.ReadAllTextAsync(configFile);
  221. return Task.FromResult<string>(null);
  222. }
  223. public async Task SetConfigAsync(string config)
  224. {
  225. string configFile = Path.Combine(_dnsServer.ApplicationFolder, "dnsApp.config");
  226. foreach (KeyValuePair<string, IDnsApplication> app in _dnsApplications)
  227. await app.Value.InitializeAsync(_dnsServer, config);
  228. if (string.IsNullOrEmpty(config))
  229. File.Delete(configFile);
  230. else
  231. await File.WriteAllTextAsync(configFile, config);
  232. }
  233. #endregion
  234. #region properties
  235. public IDnsServer DnsServer
  236. { get { return _dnsServer; } }
  237. public string Name
  238. { get { return _name; } }
  239. public string Description
  240. { get { return _description; } }
  241. public Version Version
  242. { get { return _version; } }
  243. public IReadOnlyDictionary<string, IDnsApplication> DnsApplications
  244. { get { return _dnsApplications; } }
  245. public IReadOnlyDictionary<string, IDnsAppRecordRequestHandler> DnsAppRecordRequestHandlers
  246. { get { return _dnsAppRecordRequestHandlers; } }
  247. public IReadOnlyDictionary<string, IDnsRequestController> DnsRequestControllers
  248. { get { return _dnsRequestControllers; } }
  249. public IReadOnlyDictionary<string, IDnsAuthoritativeRequestHandler> DnsAuthoritativeRequestHandlers
  250. { get { return _dnsAuthoritativeRequestHandlers; } }
  251. public IReadOnlyDictionary<string, IDnsQueryLogger> DnsQueryLoggers
  252. { get { return _dnsQueryLoggers; } }
  253. public IReadOnlyDictionary<string, IDnsPostProcessor> DnsPostProcessors
  254. { get { return _dnsPostProcessors; } }
  255. #endregion
  256. }
  257. }