PluginManager.cs 37 KB

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