DnsApplicationAssemblyLoadContext.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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.ApplicationCommon;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Reflection;
  20. using System.Runtime.InteropServices;
  21. using System.Runtime.Loader;
  22. namespace DnsServerCore.Dns
  23. {
  24. class DnsApplicationAssemblyLoadContext : AssemblyLoadContext
  25. {
  26. #region variables
  27. readonly static Type _dnsApplicationInterface = typeof(IDnsApplication);
  28. readonly IDnsServer _dnsServer;
  29. readonly List<Assembly> _appAssemblies;
  30. readonly AssemblyDependencyResolver _dependencyResolver;
  31. readonly Dictionary<string, IntPtr> _loadedUnmanagedDlls = new Dictionary<string, IntPtr>();
  32. readonly List<string> _unmanagedDllTempPaths = new List<string>();
  33. #endregion
  34. #region constructor
  35. public DnsApplicationAssemblyLoadContext(IDnsServer dnsServer)
  36. : base(true)
  37. {
  38. _dnsServer = dnsServer;
  39. Unloading += delegate (AssemblyLoadContext obj)
  40. {
  41. foreach (string unmanagedDllTempPath in _unmanagedDllTempPaths)
  42. {
  43. try
  44. {
  45. File.Delete(unmanagedDllTempPath);
  46. }
  47. catch
  48. { }
  49. }
  50. };
  51. _appAssemblies = new List<Assembly>();
  52. IEnumerable<Assembly> loadedAssemblies = Default.Assemblies;
  53. foreach (string dllFile in Directory.GetFiles(_dnsServer.ApplicationFolder, "*.dll", SearchOption.TopDirectoryOnly))
  54. {
  55. string dllFileName = Path.GetFileNameWithoutExtension(dllFile);
  56. bool isLoaded = false;
  57. foreach (Assembly loadedAssembly in loadedAssemblies)
  58. {
  59. if (!string.IsNullOrEmpty(loadedAssembly.Location))
  60. {
  61. if (Path.GetFileNameWithoutExtension(loadedAssembly.Location).Equals(dllFileName, StringComparison.OrdinalIgnoreCase))
  62. {
  63. isLoaded = true;
  64. break;
  65. }
  66. }
  67. else
  68. {
  69. AssemblyName assemblyName = loadedAssembly.GetName();
  70. if ((assemblyName.Name != null) && assemblyName.Name.Equals(dllFileName, StringComparison.OrdinalIgnoreCase))
  71. {
  72. isLoaded = true;
  73. break;
  74. }
  75. }
  76. }
  77. if (isLoaded)
  78. continue;
  79. try
  80. {
  81. Assembly appAssembly;
  82. string pdbFile = Path.Combine(_dnsServer.ApplicationFolder, Path.GetFileNameWithoutExtension(dllFile) + ".pdb");
  83. if (File.Exists(pdbFile))
  84. {
  85. using (FileStream dllStream = new FileStream(dllFile, FileMode.Open, FileAccess.Read))
  86. {
  87. using (FileStream pdbStream = new FileStream(pdbFile, FileMode.Open, FileAccess.Read))
  88. {
  89. appAssembly = LoadFromStream(dllStream, pdbStream);
  90. }
  91. }
  92. }
  93. else
  94. {
  95. using (FileStream dllStream = new FileStream(dllFile, FileMode.Open, FileAccess.Read))
  96. {
  97. appAssembly = LoadFromStream(dllStream);
  98. }
  99. }
  100. if (_dependencyResolver is null)
  101. {
  102. bool isMainAssembly = false;
  103. foreach (Type classType in appAssembly.ExportedTypes)
  104. {
  105. foreach (Type interfaceType in classType.GetInterfaces())
  106. {
  107. if (interfaceType == _dnsApplicationInterface)
  108. {
  109. isMainAssembly = true;
  110. break;
  111. }
  112. }
  113. if (isMainAssembly)
  114. break;
  115. }
  116. if (isMainAssembly)
  117. _dependencyResolver = new AssemblyDependencyResolver(dllFile);
  118. }
  119. _appAssemblies.Add(appAssembly);
  120. }
  121. catch (Exception ex)
  122. {
  123. _dnsServer.WriteLog(ex);
  124. }
  125. }
  126. }
  127. #endregion
  128. #region overrides
  129. protected override Assembly Load(AssemblyName assemblyName)
  130. {
  131. return null;
  132. }
  133. protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
  134. {
  135. string unmanagedDllPath = null;
  136. if (_dependencyResolver is not null)
  137. {
  138. string resolvedPath = _dependencyResolver.ResolveUnmanagedDllToPath(unmanagedDllName);
  139. if (!string.IsNullOrEmpty(resolvedPath) && File.Exists(resolvedPath))
  140. unmanagedDllPath = resolvedPath;
  141. }
  142. if (unmanagedDllPath is null)
  143. {
  144. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  145. {
  146. string runtime = "win-" + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
  147. string[] prefixes = new string[] { "" };
  148. string[] extensions = new string[] { ".dll" };
  149. unmanagedDllPath = FindUnmanagedDllPath(unmanagedDllName, runtime, prefixes, extensions);
  150. }
  151. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  152. {
  153. bool isAlpine = false;
  154. try
  155. {
  156. string osReleaseFile = "/etc/os-release";
  157. if (File.Exists(osReleaseFile))
  158. isAlpine = File.ReadAllText(osReleaseFile).Contains("alpine", StringComparison.OrdinalIgnoreCase);
  159. }
  160. catch
  161. { }
  162. string runtimeAlpine = "linux-musl-" + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
  163. string runtimeLinux = "linux-" + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
  164. string[] prefixes = new string[] { "", "lib" };
  165. string[] extensions = new string[] { ".so", ".so.1" };
  166. if (isAlpine)
  167. {
  168. unmanagedDllPath = FindUnmanagedDllPath(unmanagedDllName, runtimeAlpine, prefixes, extensions);
  169. if (unmanagedDllPath is null)
  170. unmanagedDllPath = FindUnmanagedDllPath(unmanagedDllName, runtimeLinux, prefixes, extensions);
  171. }
  172. else
  173. {
  174. unmanagedDllPath = FindUnmanagedDllPath(unmanagedDllName, runtimeLinux, prefixes, extensions);
  175. }
  176. }
  177. else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  178. {
  179. string runtime = "osx-" + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
  180. string[] prefixes = new string[] { "", "lib" };
  181. string[] extensions = new string[] { ".dylib" };
  182. unmanagedDllPath = FindUnmanagedDllPath(unmanagedDllName, runtime, prefixes, extensions);
  183. }
  184. if (unmanagedDllPath is null)
  185. return IntPtr.Zero;
  186. }
  187. lock (_loadedUnmanagedDlls)
  188. {
  189. if (!_loadedUnmanagedDlls.TryGetValue(unmanagedDllPath.ToLowerInvariant(), out IntPtr value))
  190. {
  191. //load the unmanaged DLL
  192. //copy unmanaged dll into temp file for loading to allow uninstalling/updating app at runtime.
  193. string tempPath = Path.GetTempFileName();
  194. using (FileStream srcFile = new FileStream(unmanagedDllPath, FileMode.Open, FileAccess.Read))
  195. {
  196. using (FileStream dstFile = new FileStream(tempPath, FileMode.Create, FileAccess.Write))
  197. {
  198. srcFile.CopyTo(dstFile);
  199. }
  200. }
  201. _unmanagedDllTempPaths.Add(tempPath);
  202. value = LoadUnmanagedDllFromPath(tempPath);
  203. _loadedUnmanagedDlls.Add(unmanagedDllPath.ToLowerInvariant(), value);
  204. }
  205. return value;
  206. }
  207. }
  208. #endregion
  209. #region private
  210. private string FindUnmanagedDllPath(string unmanagedDllName, string runtime, string[] prefixes, string[] extensions)
  211. {
  212. foreach (string prefix in prefixes)
  213. {
  214. foreach (string extension in extensions)
  215. {
  216. string path = Path.Combine(_dnsServer.ApplicationFolder, "runtimes", runtime, "native", prefix + unmanagedDllName + extension);
  217. if (File.Exists(path))
  218. return path;
  219. }
  220. }
  221. return null;
  222. }
  223. #endregion
  224. #region properties
  225. public IReadOnlyList<Assembly> AppAssemblies
  226. { get { return _appAssemblies; } }
  227. #endregion
  228. }
  229. }