PluginManager.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Reflection;
  9. using System.Runtime.Loader;
  10. using System.Text;
  11. using System.Text.Json;
  12. using System.Threading.Tasks;
  13. using Emby.Server.Implementations.Library;
  14. using Jellyfin.Extensions;
  15. using Jellyfin.Extensions.Json;
  16. using Jellyfin.Extensions.Json.Converters;
  17. using MediaBrowser.Common;
  18. using MediaBrowser.Common.Extensions;
  19. using MediaBrowser.Common.Net;
  20. using MediaBrowser.Common.Plugins;
  21. using MediaBrowser.Model.Configuration;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.Plugins;
  24. using MediaBrowser.Model.Updates;
  25. using Microsoft.Extensions.DependencyInjection;
  26. using Microsoft.Extensions.Logging;
  27. namespace Emby.Server.Implementations.Plugins
  28. {
  29. /// <summary>
  30. /// Defines the <see cref="PluginManager" />.
  31. /// </summary>
  32. public class PluginManager : IPluginManager
  33. {
  34. private const string MetafileName = "meta.json";
  35. private readonly string _pluginsPath;
  36. private readonly Version _appVersion;
  37. private readonly List<AssemblyLoadContext> _assemblyLoadContexts;
  38. private readonly JsonSerializerOptions _jsonOptions;
  39. private readonly ILogger<PluginManager> _logger;
  40. private readonly IApplicationHost _appHost;
  41. private readonly ServerConfiguration _config;
  42. private readonly List<LocalPlugin> _plugins;
  43. private readonly Version _minimumVersion;
  44. private IHttpClientFactory? _httpClientFactory;
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="PluginManager"/> class.
  47. /// </summary>
  48. /// <param name="logger">The <see cref="ILogger{PluginManager}"/>.</param>
  49. /// <param name="appHost">The <see cref="IApplicationHost"/>.</param>
  50. /// <param name="config">The <see cref="ServerConfiguration"/>.</param>
  51. /// <param name="pluginsPath">The plugin path.</param>
  52. /// <param name="appVersion">The application version.</param>
  53. public PluginManager(
  54. ILogger<PluginManager> logger,
  55. IApplicationHost appHost,
  56. ServerConfiguration config,
  57. string pluginsPath,
  58. Version appVersion)
  59. {
  60. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  61. _pluginsPath = pluginsPath;
  62. _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion));
  63. _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options)
  64. {
  65. WriteIndented = true
  66. };
  67. // We need to use the default GUID converter, so we need to remove any custom ones.
  68. for (int a = _jsonOptions.Converters.Count - 1; a >= 0; a--)
  69. {
  70. if (_jsonOptions.Converters[a] is JsonGuidConverter convertor)
  71. {
  72. _jsonOptions.Converters.Remove(convertor);
  73. break;
  74. }
  75. }
  76. _config = config;
  77. _appHost = appHost;
  78. _minimumVersion = new Version(0, 0, 0, 1);
  79. _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>();
  80. _assemblyLoadContexts = new List<AssemblyLoadContext>();
  81. }
  82. private IHttpClientFactory HttpClientFactory
  83. {
  84. get
  85. {
  86. return _httpClientFactory ??= _appHost.Resolve<IHttpClientFactory>();
  87. }
  88. }
  89. /// <summary>
  90. /// Gets the Plugins.
  91. /// </summary>
  92. public IReadOnlyList<LocalPlugin> Plugins => _plugins;
  93. /// <summary>
  94. /// Returns all the assemblies.
  95. /// </summary>
  96. /// <returns>An IEnumerable{Assembly}.</returns>
  97. public IEnumerable<Assembly> LoadAssemblies()
  98. {
  99. // Attempt to remove any deleted plugins and change any successors to be active.
  100. for (int i = _plugins.Count - 1; i >= 0; i--)
  101. {
  102. var plugin = _plugins[i];
  103. if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin))
  104. {
  105. // See if there is another version, and if so make that active.
  106. ProcessAlternative(plugin);
  107. }
  108. }
  109. // Now load the assemblies..
  110. foreach (var plugin in _plugins)
  111. {
  112. UpdatePluginSuperceedStatus(plugin);
  113. if (plugin.IsEnabledAndSupported == false)
  114. {
  115. _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name);
  116. continue;
  117. }
  118. var assemblyLoadContext = new PluginLoadContext(plugin.Path);
  119. _assemblyLoadContexts.Add(assemblyLoadContext);
  120. var assemblies = new List<Assembly>(plugin.DllFiles.Count);
  121. var loadedAll = true;
  122. foreach (var file in plugin.DllFiles)
  123. {
  124. try
  125. {
  126. assemblies.Add(assemblyLoadContext.LoadFromAssemblyPath(file));
  127. }
  128. catch (FileLoadException ex)
  129. {
  130. _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin", file);
  131. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  132. loadedAll = false;
  133. break;
  134. }
  135. #pragma warning disable CA1031 // Do not catch general exception types
  136. catch (Exception ex)
  137. #pragma warning restore CA1031 // Do not catch general exception types
  138. {
  139. _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling plugin", file);
  140. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  141. loadedAll = false;
  142. break;
  143. }
  144. }
  145. if (!loadedAll)
  146. {
  147. continue;
  148. }
  149. foreach (var assembly in assemblies)
  150. {
  151. try
  152. {
  153. // Load all required types to verify that the plugin will load
  154. assembly.GetTypes();
  155. }
  156. catch (SystemException ex) when (ex is TypeLoadException or ReflectionTypeLoadException) // Undocumented exception
  157. {
  158. _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references an incompatible version of one of the shared libraries. Disabling plugin", assembly.Location);
  159. ChangePluginState(plugin, PluginStatus.NotSupported);
  160. break;
  161. }
  162. #pragma warning disable CA1031 // Do not catch general exception types
  163. catch (Exception ex)
  164. #pragma warning restore CA1031 // Do not catch general exception types
  165. {
  166. _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling plugin", assembly.Location);
  167. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  168. break;
  169. }
  170. _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, assembly.Location);
  171. yield return assembly;
  172. }
  173. }
  174. }
  175. /// <inheritdoc />
  176. public void UnloadAssemblies()
  177. {
  178. foreach (var assemblyLoadContext in _assemblyLoadContexts)
  179. {
  180. assemblyLoadContext.Unload();
  181. }
  182. }
  183. /// <summary>
  184. /// Creates all the plugin instances.
  185. /// </summary>
  186. public void CreatePlugins()
  187. {
  188. _ = _appHost.GetExports<IPlugin>(CreatePluginInstance);
  189. }
  190. /// <summary>
  191. /// Registers the plugin's services with the DI.
  192. /// Note: DI is not yet instantiated yet.
  193. /// </summary>
  194. /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param>
  195. public void RegisterServices(IServiceCollection serviceCollection)
  196. {
  197. foreach (var pluginServiceRegistrator in _appHost.GetExportTypes<IPluginServiceRegistrator>())
  198. {
  199. var plugin = GetPluginByAssembly(pluginServiceRegistrator.Assembly);
  200. if (plugin is null)
  201. {
  202. _logger.LogError("Unable to find plugin in assembly {Assembly}", pluginServiceRegistrator.Assembly.FullName);
  203. continue;
  204. }
  205. UpdatePluginSuperceedStatus(plugin);
  206. if (!plugin.IsEnabledAndSupported)
  207. {
  208. continue;
  209. }
  210. try
  211. {
  212. var instance = (IPluginServiceRegistrator?)Activator.CreateInstance(pluginServiceRegistrator);
  213. instance?.RegisterServices(serviceCollection);
  214. }
  215. #pragma warning disable CA1031 // Do not catch general exception types
  216. catch (Exception ex)
  217. #pragma warning restore CA1031 // Do not catch general exception types
  218. {
  219. _logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly.FullName);
  220. if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
  221. {
  222. _logger.LogInformation("Disabling plugin {Path}", plugin.Path);
  223. }
  224. }
  225. }
  226. }
  227. /// <summary>
  228. /// Imports a plugin manifest from <paramref name="folder"/>.
  229. /// </summary>
  230. /// <param name="folder">Folder of the plugin.</param>
  231. public void ImportPluginFrom(string folder)
  232. {
  233. ArgumentException.ThrowIfNullOrEmpty(folder);
  234. // Load the plugin.
  235. var plugin = LoadManifest(folder);
  236. // Make sure we haven't already loaded this.
  237. if (_plugins.Any(p => p.Manifest.Equals(plugin.Manifest)))
  238. {
  239. return;
  240. }
  241. _plugins.Add(plugin);
  242. EnablePlugin(plugin);
  243. }
  244. /// <summary>
  245. /// Removes the plugin reference '<paramref name="plugin"/>.
  246. /// </summary>
  247. /// <param name="plugin">The plugin.</param>
  248. /// <returns>Outcome of the operation.</returns>
  249. public bool RemovePlugin(LocalPlugin plugin)
  250. {
  251. ArgumentNullException.ThrowIfNull(plugin);
  252. if (DeletePlugin(plugin))
  253. {
  254. ProcessAlternative(plugin);
  255. return true;
  256. }
  257. _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path);
  258. // Unable to delete, so disable.
  259. if (ChangePluginState(plugin, PluginStatus.Deleted))
  260. {
  261. ProcessAlternative(plugin);
  262. return true;
  263. }
  264. return false;
  265. }
  266. /// <summary>
  267. /// Attempts to find the plugin with and id of <paramref name="id"/>.
  268. /// </summary>
  269. /// <param name="id">The <see cref="Guid"/> of plugin.</param>
  270. /// <param name="version">Optional <see cref="Version"/> of the plugin to locate.</param>
  271. /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns>
  272. public LocalPlugin? GetPlugin(Guid id, Version? version = null)
  273. {
  274. LocalPlugin? plugin;
  275. if (version is null)
  276. {
  277. // If no version is given, return the current instance.
  278. var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList();
  279. plugin = plugins.FirstOrDefault(p => p.Instance is not null) ?? plugins.MaxBy(p => p.Version);
  280. }
  281. else
  282. {
  283. // Match id and version number.
  284. plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version));
  285. }
  286. return plugin;
  287. }
  288. /// <summary>
  289. /// Enables the plugin, disabling all other versions.
  290. /// </summary>
  291. /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
  292. public void EnablePlugin(LocalPlugin plugin)
  293. {
  294. ArgumentNullException.ThrowIfNull(plugin);
  295. if (ChangePluginState(plugin, PluginStatus.Active))
  296. {
  297. // See if there is another version, and if so, supercede it.
  298. ProcessAlternative(plugin);
  299. }
  300. }
  301. /// <summary>
  302. /// Disable the plugin.
  303. /// </summary>
  304. /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
  305. public void DisablePlugin(LocalPlugin plugin)
  306. {
  307. ArgumentNullException.ThrowIfNull(plugin);
  308. // Update the manifest on disk
  309. if (ChangePluginState(plugin, PluginStatus.Disabled))
  310. {
  311. // If there is another version, activate it.
  312. ProcessAlternative(plugin);
  313. }
  314. }
  315. /// <summary>
  316. /// Disable the plugin.
  317. /// </summary>
  318. /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param>
  319. public void FailPlugin(Assembly assembly)
  320. {
  321. // Only save if disabled.
  322. ArgumentNullException.ThrowIfNull(assembly);
  323. var plugin = _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location));
  324. if (plugin is null)
  325. {
  326. // A plugin's assembly didn't cause this issue, so ignore it.
  327. return;
  328. }
  329. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  330. }
  331. /// <inheritdoc/>
  332. public bool SaveManifest(PluginManifest manifest, string path)
  333. {
  334. try
  335. {
  336. var data = JsonSerializer.Serialize(manifest, _jsonOptions);
  337. File.WriteAllText(Path.Combine(path, MetafileName), data);
  338. return true;
  339. }
  340. catch (ArgumentException e)
  341. {
  342. _logger.LogWarning(e, "Unable to save plugin manifest due to invalid value. {Path}", path);
  343. return false;
  344. }
  345. }
  346. /// <inheritdoc/>
  347. public async Task<bool> PopulateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status)
  348. {
  349. var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString());
  350. var imagePath = string.Empty;
  351. if (!string.IsNullOrEmpty(packageInfo.ImageUrl))
  352. {
  353. var url = new Uri(packageInfo.ImageUrl);
  354. imagePath = Path.Join(path, url.Segments[^1]);
  355. await using var fileStream = AsyncFile.OpenWrite(imagePath);
  356. try
  357. {
  358. await using var downloadStream = await HttpClientFactory
  359. .CreateClient(NamedClient.Default)
  360. .GetStreamAsync(url)
  361. .ConfigureAwait(false);
  362. await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false);
  363. }
  364. catch (HttpRequestException ex)
  365. {
  366. _logger.LogError(ex, "Failed to download image to path {Path} on disk.", imagePath);
  367. imagePath = string.Empty;
  368. }
  369. }
  370. var manifest = new PluginManifest
  371. {
  372. Category = packageInfo.Category,
  373. Changelog = versionInfo.Changelog ?? string.Empty,
  374. Description = packageInfo.Description,
  375. Id = packageInfo.Id,
  376. Name = packageInfo.Name,
  377. Overview = packageInfo.Overview,
  378. Owner = packageInfo.Owner,
  379. TargetAbi = versionInfo.TargetAbi ?? string.Empty,
  380. Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo.Timestamp, CultureInfo.InvariantCulture),
  381. Version = versionInfo.Version,
  382. Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled state.
  383. AutoUpdate = true,
  384. ImagePath = imagePath
  385. };
  386. if (!await ReconcileManifest(manifest, path))
  387. {
  388. // An error occurred during reconciliation and saving could be undesirable.
  389. return false;
  390. }
  391. return SaveManifest(manifest, path);
  392. }
  393. /// <summary>
  394. /// Reconciles the manifest against any properties that exist locally in a pre-packaged meta.json found at the path.
  395. /// If no file is found, no reconciliation occurs.
  396. /// </summary>
  397. /// <param name="manifest">The <see cref="PluginManifest"/> to reconcile against.</param>
  398. /// <param name="path">The plugin path.</param>
  399. /// <returns>The reconciled <see cref="PluginManifest"/>.</returns>
  400. private async Task<bool> ReconcileManifest(PluginManifest manifest, string path)
  401. {
  402. try
  403. {
  404. var metafile = Path.Combine(path, MetafileName);
  405. if (!File.Exists(metafile))
  406. {
  407. _logger.LogInformation("No local manifest exists for plugin {Plugin}. Skipping manifest reconciliation.", manifest.Name);
  408. return true;
  409. }
  410. using var metaStream = File.OpenRead(metafile);
  411. var localManifest = await JsonSerializer.DeserializeAsync<PluginManifest>(metaStream, _jsonOptions);
  412. localManifest ??= new PluginManifest();
  413. if (!Equals(localManifest.Id, manifest.Id))
  414. {
  415. _logger.LogError("The manifest ID {LocalUUID} did not match the package info ID {PackageUUID}.", localManifest.Id, manifest.Id);
  416. manifest.Status = PluginStatus.Malfunctioned;
  417. }
  418. if (localManifest.Version != manifest.Version)
  419. {
  420. // Package information provides the version and is the source of truth. Pre-packages meta.json is assumed to be a mistake in this regard.
  421. _logger.LogWarning("The version of the local manifest was {LocalVersion}, but {PackageVersion} was expected. The value will be replaced.", localManifest.Version, manifest.Version);
  422. }
  423. // Explicitly mapping properties instead of using reflection is preferred here.
  424. manifest.Category = string.IsNullOrEmpty(localManifest.Category) ? manifest.Category : localManifest.Category;
  425. manifest.AutoUpdate = localManifest.AutoUpdate; // Preserve whatever is local. Package info does not have this property.
  426. manifest.Changelog = string.IsNullOrEmpty(localManifest.Changelog) ? manifest.Changelog : localManifest.Changelog;
  427. manifest.Description = string.IsNullOrEmpty(localManifest.Description) ? manifest.Description : localManifest.Description;
  428. manifest.Name = string.IsNullOrEmpty(localManifest.Name) ? manifest.Name : localManifest.Name;
  429. manifest.Overview = string.IsNullOrEmpty(localManifest.Overview) ? manifest.Overview : localManifest.Overview;
  430. manifest.Owner = string.IsNullOrEmpty(localManifest.Owner) ? manifest.Owner : localManifest.Owner;
  431. manifest.TargetAbi = string.IsNullOrEmpty(localManifest.TargetAbi) ? manifest.TargetAbi : localManifest.TargetAbi;
  432. manifest.Timestamp = localManifest.Timestamp.Equals(default) ? manifest.Timestamp : localManifest.Timestamp;
  433. manifest.ImagePath = string.IsNullOrEmpty(localManifest.ImagePath) ? manifest.ImagePath : localManifest.ImagePath;
  434. manifest.Assemblies = localManifest.Assemblies;
  435. return true;
  436. }
  437. catch (Exception e)
  438. {
  439. _logger.LogWarning(e, "Unable to reconcile plugin manifest due to an error. {Path}", path);
  440. return false;
  441. }
  442. }
  443. /// <summary>
  444. /// Changes a plugin's load status.
  445. /// </summary>
  446. /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param>
  447. /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param>
  448. /// <returns>Success of the task.</returns>
  449. private bool ChangePluginState(LocalPlugin plugin, PluginStatus state)
  450. {
  451. if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path))
  452. {
  453. // No need to save as the state hasn't changed.
  454. return true;
  455. }
  456. plugin.Manifest.Status = state;
  457. return SaveManifest(plugin.Manifest, plugin.Path);
  458. }
  459. /// <summary>
  460. /// Finds the plugin record using the assembly.
  461. /// </summary>
  462. /// <param name="assembly">The <see cref="Assembly"/> being sought.</param>
  463. /// <returns>The matching record, or null if not found.</returns>
  464. private LocalPlugin? GetPluginByAssembly(Assembly assembly)
  465. {
  466. // Find which plugin it is by the path.
  467. return _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location, StringComparer.Ordinal));
  468. }
  469. /// <summary>
  470. /// Creates the instance safe.
  471. /// </summary>
  472. /// <param name="type">The type.</param>
  473. /// <returns>System.Object.</returns>
  474. private IPlugin? CreatePluginInstance(Type type)
  475. {
  476. // Find the record for this plugin.
  477. var plugin = GetPluginByAssembly(type.Assembly);
  478. if (plugin?.Manifest.Status < PluginStatus.Active)
  479. {
  480. return null;
  481. }
  482. try
  483. {
  484. _logger.LogDebug("Creating instance of {Type}", type);
  485. // _appHost.ServiceProvider is already assigned when we create the plugins
  486. var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider!, type);
  487. if (plugin is null)
  488. {
  489. // Create a dummy record for the providers.
  490. // TODO: remove this code once all provided have been released as separate plugins.
  491. plugin = new LocalPlugin(
  492. instance.AssemblyFilePath,
  493. true,
  494. new PluginManifest
  495. {
  496. Id = instance.Id,
  497. Status = PluginStatus.Active,
  498. Name = instance.Name,
  499. Version = instance.Version.ToString()
  500. })
  501. {
  502. Instance = instance
  503. };
  504. _plugins.Add(plugin);
  505. plugin.Manifest.Status = PluginStatus.Active;
  506. }
  507. else
  508. {
  509. plugin.Instance = instance;
  510. var manifest = plugin.Manifest;
  511. var pluginStr = instance.Version.ToString();
  512. bool changed = false;
  513. if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)
  514. || !manifest.Id.Equals(instance.Id))
  515. {
  516. // If a plugin without a manifest failed to load due to an external issue (eg config),
  517. // this updates the manifest to the actual plugin values.
  518. manifest.Version = pluginStr;
  519. manifest.Name = plugin.Instance.Name;
  520. manifest.Description = plugin.Instance.Description;
  521. manifest.Id = plugin.Instance.Id;
  522. changed = true;
  523. }
  524. changed = changed || manifest.Status != PluginStatus.Active;
  525. manifest.Status = PluginStatus.Active;
  526. if (changed)
  527. {
  528. SaveManifest(manifest, plugin.Path);
  529. }
  530. }
  531. _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
  532. return instance;
  533. }
  534. #pragma warning disable CA1031 // Do not catch general exception types
  535. catch (Exception ex)
  536. #pragma warning restore CA1031 // Do not catch general exception types
  537. {
  538. _logger.LogError(ex, "Error creating {Type}", type.FullName);
  539. if (plugin is not null)
  540. {
  541. if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
  542. {
  543. _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
  544. return null;
  545. }
  546. }
  547. _logger.LogDebug("Unable to auto-disable.");
  548. return null;
  549. }
  550. }
  551. private void UpdatePluginSuperceedStatus(LocalPlugin plugin)
  552. {
  553. if (plugin.Manifest.Status != PluginStatus.Superceded)
  554. {
  555. return;
  556. }
  557. var predecessor = _plugins.OrderByDescending(p => p.Version)
  558. .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version);
  559. if (predecessor is not null)
  560. {
  561. return;
  562. }
  563. plugin.Manifest.Status = PluginStatus.Active;
  564. }
  565. /// <summary>
  566. /// Attempts to delete a plugin.
  567. /// </summary>
  568. /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
  569. /// <returns>True if successful.</returns>
  570. private bool DeletePlugin(LocalPlugin plugin)
  571. {
  572. // Attempt a cleanup of old folders.
  573. try
  574. {
  575. Directory.Delete(plugin.Path, true);
  576. _logger.LogDebug("Deleted {Path}", plugin.Path);
  577. }
  578. #pragma warning disable CA1031 // Do not catch general exception types
  579. catch
  580. #pragma warning restore CA1031 // Do not catch general exception types
  581. {
  582. return false;
  583. }
  584. return _plugins.Remove(plugin);
  585. }
  586. internal LocalPlugin LoadManifest(string dir)
  587. {
  588. Version? version;
  589. PluginManifest? manifest = null;
  590. var metafile = Path.Combine(dir, MetafileName);
  591. if (File.Exists(metafile))
  592. {
  593. // Only path where this stays null is when File.ReadAllBytes throws an IOException
  594. byte[] data = null!;
  595. try
  596. {
  597. data = File.ReadAllBytes(metafile);
  598. manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
  599. }
  600. catch (IOException ex)
  601. {
  602. _logger.LogError(ex, "Error reading file {Path}.", dir);
  603. }
  604. catch (JsonException ex)
  605. {
  606. _logger.LogError(ex, "Error deserializing {Json}.", Encoding.UTF8.GetString(data!));
  607. }
  608. if (manifest is not null)
  609. {
  610. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  611. {
  612. targetAbi = _minimumVersion;
  613. }
  614. if (!Version.TryParse(manifest.Version, out version))
  615. {
  616. manifest.Version = _minimumVersion.ToString();
  617. }
  618. return new LocalPlugin(dir, _appVersion >= targetAbi, manifest);
  619. }
  620. }
  621. // No metafile, so lets see if the folder is versioned.
  622. // TODO: Phase this support out in future versions.
  623. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  624. int versionIndex = dir.LastIndexOf('_');
  625. if (versionIndex != -1)
  626. {
  627. // Get the version number from the filename if possible.
  628. metafile = Path.GetFileName(dir[..versionIndex]);
  629. version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion;
  630. }
  631. else
  632. {
  633. // Un-versioned folder - Add it under the path name and version it suitable for this instance.
  634. version = _appVersion;
  635. }
  636. // Auto-create a plugin manifest, so we can disable it, if it fails to load.
  637. manifest = new PluginManifest
  638. {
  639. Status = PluginStatus.Active,
  640. Name = metafile,
  641. AutoUpdate = false,
  642. Id = metafile.GetMD5(),
  643. TargetAbi = _appVersion.ToString(),
  644. Version = version.ToString()
  645. };
  646. return new LocalPlugin(dir, true, manifest);
  647. }
  648. /// <summary>
  649. /// Gets the list of local plugins.
  650. /// </summary>
  651. /// <returns>Enumerable of local plugins.</returns>
  652. private IEnumerable<LocalPlugin> DiscoverPlugins()
  653. {
  654. var versions = new List<LocalPlugin>();
  655. if (!Directory.Exists(_pluginsPath))
  656. {
  657. // Plugin path doesn't exist, don't try to enumerate sub-folders.
  658. return Enumerable.Empty<LocalPlugin>();
  659. }
  660. var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
  661. foreach (var dir in directories)
  662. {
  663. versions.Add(LoadManifest(dir));
  664. }
  665. string lastName = string.Empty;
  666. versions.Sort(LocalPlugin.Compare);
  667. // Traverse backwards through the list.
  668. // The first item will be the latest version.
  669. for (int x = versions.Count - 1; x >= 0; x--)
  670. {
  671. var entry = versions[x];
  672. if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
  673. {
  674. if (!TryGetPluginDlls(entry, out var allowedDlls))
  675. {
  676. _logger.LogError("One or more assembly paths was invalid. Marking plugin {Plugin} as \"Malfunctioned\".", entry.Name);
  677. ChangePluginState(entry, PluginStatus.Malfunctioned);
  678. continue;
  679. }
  680. entry.DllFiles = allowedDlls;
  681. if (entry.IsEnabledAndSupported)
  682. {
  683. lastName = entry.Name;
  684. continue;
  685. }
  686. }
  687. if (string.IsNullOrEmpty(lastName))
  688. {
  689. continue;
  690. }
  691. var cleaned = false;
  692. var path = entry.Path;
  693. if (_config.RemoveOldPlugins)
  694. {
  695. // Attempt a cleanup of old folders.
  696. try
  697. {
  698. _logger.LogDebug("Deleting {Path}", path);
  699. Directory.Delete(path, true);
  700. cleaned = true;
  701. }
  702. #pragma warning disable CA1031 // Do not catch general exception types
  703. catch (Exception e)
  704. #pragma warning restore CA1031 // Do not catch general exception types
  705. {
  706. _logger.LogWarning(e, "Unable to delete {Path}", path);
  707. }
  708. if (cleaned)
  709. {
  710. versions.RemoveAt(x);
  711. }
  712. else
  713. {
  714. ChangePluginState(entry, PluginStatus.Deleted);
  715. }
  716. }
  717. }
  718. // Only want plugin folders which have files.
  719. return versions.Where(p => p.DllFiles.Count != 0);
  720. }
  721. /// <summary>
  722. /// Attempts to retrieve valid DLLs from the plugin path. This method will consider the assembly whitelist
  723. /// from the manifest.
  724. /// </summary>
  725. /// <remarks>
  726. /// Loading DLLs from externally supplied paths introduces a path traversal risk. This method
  727. /// uses a safelisting tactic of considering DLLs from the plugin directory and only using
  728. /// the plugin's canonicalized assembly whitelist for comparison. See
  729. /// <see href="https://owasp.org/www-community/attacks/Path_Traversal"/> for more details.
  730. /// </remarks>
  731. /// <param name="plugin">The plugin.</param>
  732. /// <param name="whitelistedDlls">The whitelisted DLLs. If the method returns <see langword="false"/>, this will be empty.</param>
  733. /// <returns>
  734. /// <see langword="true"/> if all assemblies listed in the manifest were available in the plugin directory.
  735. /// <see langword="false"/> if any assemblies were invalid or missing from the plugin directory.
  736. /// </returns>
  737. /// <exception cref="ArgumentNullException">If the <see cref="LocalPlugin"/> is null.</exception>
  738. private bool TryGetPluginDlls(LocalPlugin plugin, out IReadOnlyList<string> whitelistedDlls)
  739. {
  740. ArgumentNullException.ThrowIfNull(nameof(plugin));
  741. IReadOnlyList<string> pluginDlls = Directory.GetFiles(plugin.Path, "*.dll", SearchOption.AllDirectories);
  742. whitelistedDlls = Array.Empty<string>();
  743. if (pluginDlls.Count > 0 && plugin.Manifest.Assemblies.Count > 0)
  744. {
  745. _logger.LogInformation("Registering whitelisted assemblies for plugin \"{Plugin}\"...", plugin.Name);
  746. var canonicalizedPaths = new List<string>();
  747. foreach (var path in plugin.Manifest.Assemblies)
  748. {
  749. var canonicalized = Path.Combine(plugin.Path, path).Canonicalize();
  750. // Ensure we stay in the plugin directory.
  751. if (!canonicalized.StartsWith(plugin.Path.NormalizePath(), StringComparison.Ordinal))
  752. {
  753. _logger.LogError("Assembly path {Path} is not inside the plugin directory.", path);
  754. return false;
  755. }
  756. canonicalizedPaths.Add(canonicalized);
  757. }
  758. var intersected = pluginDlls.Intersect(canonicalizedPaths).ToList();
  759. if (intersected.Count != canonicalizedPaths.Count)
  760. {
  761. _logger.LogError("Plugin {Plugin} contained assembly paths that were not found in the directory.", plugin.Name);
  762. return false;
  763. }
  764. whitelistedDlls = intersected;
  765. }
  766. else
  767. {
  768. // No whitelist, default to loading all DLLs in plugin directory.
  769. whitelistedDlls = pluginDlls;
  770. }
  771. return true;
  772. }
  773. /// <summary>
  774. /// Changes the status of the other versions of the plugin to "Superceded".
  775. /// </summary>
  776. /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param>
  777. private void ProcessAlternative(LocalPlugin plugin)
  778. {
  779. // Detect whether there is another version of this plugin that needs disabling.
  780. var previousVersion = _plugins.OrderByDescending(p => p.Version)
  781. .FirstOrDefault(
  782. p => p.Id.Equals(plugin.Id)
  783. && p.IsEnabledAndSupported
  784. && p.Version != plugin.Version);
  785. if (previousVersion is null)
  786. {
  787. // This value is memory only - so that the web will show restart required.
  788. plugin.Manifest.Status = PluginStatus.Restart;
  789. plugin.Manifest.AutoUpdate = false;
  790. return;
  791. }
  792. if (plugin.Manifest.Status == PluginStatus.Active && !ChangePluginState(previousVersion, PluginStatus.Superceded))
  793. {
  794. _logger.LogError("Unable to enable version {Version} of {Name}", previousVersion.Version, previousVersion.Name);
  795. }
  796. else if (plugin.Manifest.Status == PluginStatus.Superceded && !ChangePluginState(previousVersion, PluginStatus.Active))
  797. {
  798. _logger.LogError("Unable to supercede version {Version} of {Name}", previousVersion.Version, previousVersion.Name);
  799. }
  800. // This value is memory only - so that the web will show restart required.
  801. plugin.Manifest.Status = PluginStatus.Restart;
  802. plugin.Manifest.AutoUpdate = false;
  803. }
  804. }
  805. }