< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.Plugins.PluginManager
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/Plugins/PluginManager.cs
Line coverage
51%
Covered lines: 188
Uncovered lines: 180
Coverable lines: 368
Total lines: 926
Line coverage: 51%
Branch coverage
49%
Covered branches: 86
Total branches: 174
Branch coverage: 49.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/6/2026 - 12:15:23 AM Line coverage: 43.9% (160/364) Branch coverage: 40.5% (69/170) Total lines: 9135/20/2026 - 12:15:44 AM Line coverage: 43.9% (160/364) Branch coverage: 40% (68/170) Total lines: 9135/22/2026 - 12:15:17 AM Line coverage: 44.1% (161/365) Branch coverage: 40.6% (70/172) Total lines: 9146/11/2026 - 12:16:04 AM Line coverage: 45.2% (165/365) Branch coverage: 41.8% (72/172) Total lines: 9146/28/2026 - 12:15:35 AM Line coverage: 44.1% (161/365) Branch coverage: 40.6% (70/172) Total lines: 9148/9/2026 - 12:16:58 AM Line coverage: 51% (188/368) Branch coverage: 49.4% (86/174) Total lines: 926 5/6/2026 - 12:15:23 AM Line coverage: 43.9% (160/364) Branch coverage: 40.5% (69/170) Total lines: 9135/20/2026 - 12:15:44 AM Line coverage: 43.9% (160/364) Branch coverage: 40% (68/170) Total lines: 9135/22/2026 - 12:15:17 AM Line coverage: 44.1% (161/365) Branch coverage: 40.6% (70/172) Total lines: 9146/11/2026 - 12:16:04 AM Line coverage: 45.2% (165/365) Branch coverage: 41.8% (72/172) Total lines: 9146/28/2026 - 12:15:35 AM Line coverage: 44.1% (161/365) Branch coverage: 40.6% (70/172) Total lines: 9148/9/2026 - 12:16:58 AM Line coverage: 51% (188/368) Branch coverage: 49.4% (86/174) Total lines: 926

Coverage delta

Coverage delta 9 -9

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)80%1010100%
get_HttpClientFactory()0%620%
get_Plugins()100%11100%
LoadAssemblies()50%1401621.42%
CreatePlugins()100%11100%
RegisterServices(...)20%771012.5%
ImportPluginFrom(...)0%2040%
RemovePlugin(...)0%2040%
GetPlugin(...)25%5460%
EnablePlugin(...)0%620%
DisablePlugin(...)50%22100%
FailPlugin(...)0%620%
SaveManifest(...)100%1157.14%
PopulateManifest()50%341453.65%
Dispose()50%2266.66%
ReconcileManifest()69.23%272689.28%
ChangePluginState(...)50%4475%
GetPluginByAssembly(...)100%11100%
CreatePluginInstance(...)30%702050%
UpdatePluginSupersededStatus(...)75%4477.77%
DeletePlugin(...)100%210%
LoadManifest(...)50%481237.14%
DiscoverPlugins()75%301661.76%
TryGetPluginDlls(...)100%1010100%
ProcessAlternative(...)10%181057.14%

File(s)

/srv/git/jellyfin/Emby.Server.Implementations/Plugins/PluginManager.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.IO;
 5using System.Linq;
 6using System.Net.Http;
 7using System.Reflection;
 8using System.Runtime.Loader;
 9using System.Text;
 10using System.Text.Json;
 11using System.Threading.Tasks;
 12using Emby.Server.Implementations.Library;
 13using Jellyfin.Extensions.Json;
 14using Jellyfin.Extensions.Json.Converters;
 15using MediaBrowser.Common.Extensions;
 16using MediaBrowser.Common.Net;
 17using MediaBrowser.Common.Plugins;
 18using MediaBrowser.Controller;
 19using MediaBrowser.Controller.Plugins;
 20using MediaBrowser.Model.Configuration;
 21using MediaBrowser.Model.IO;
 22using MediaBrowser.Model.Plugins;
 23using MediaBrowser.Model.Updates;
 24using Microsoft.Extensions.DependencyInjection;
 25using Microsoft.Extensions.Logging;
 26
 27namespace Emby.Server.Implementations.Plugins
 28{
 29    /// <summary>
 30    /// Defines the <see cref="PluginManager" />.
 31    /// </summary>
 32    public sealed class PluginManager : IPluginManager, IDisposable
 33    {
 34        private const string MetafileName = "meta.json";
 35
 36        private readonly string _pluginsPath;
 37        private readonly Version _appVersion;
 38        private readonly List<AssemblyLoadContext> _assemblyLoadContexts;
 39        private readonly JsonSerializerOptions _jsonOptions;
 40        private readonly ILogger<PluginManager> _logger;
 41        private readonly IServerApplicationHost _appHost;
 42        private readonly ServerConfiguration _config;
 43        private readonly List<LocalPlugin> _plugins;
 44        private readonly Version _minimumVersion;
 45
 46        private IHttpClientFactory? _httpClientFactory;
 47
 48        /// <summary>
 49        /// Initializes a new instance of the <see cref="PluginManager"/> class.
 50        /// </summary>
 51        /// <param name="logger">The <see cref="ILogger{PluginManager}"/>.</param>
 52        /// <param name="appHost">The <see cref="IServerApplicationHost"/>.</param>
 53        /// <param name="config">The <see cref="ServerConfiguration"/>.</param>
 54        /// <param name="pluginsPath">The plugin path.</param>
 55        /// <param name="appVersion">The application version.</param>
 56        public PluginManager(
 57            ILogger<PluginManager> logger,
 58            IServerApplicationHost appHost,
 59            ServerConfiguration config,
 60            string pluginsPath,
 61            Version appVersion)
 62        {
 4263            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 4264            _pluginsPath = pluginsPath;
 4265            _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion));
 4266            _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options)
 4267            {
 4268                WriteIndented = true
 4269            };
 70
 71            // We need to use the default GUID converter, so we need to remove any custom ones.
 75672            for (int a = _jsonOptions.Converters.Count - 1; a >= 0; a--)
 73            {
 37874                if (_jsonOptions.Converters[a] is JsonGuidConverter convertor)
 75                {
 4276                    _jsonOptions.Converters.Remove(convertor);
 4277                    break;
 78                }
 79            }
 80
 4281            _config = config;
 4282            _appHost = appHost;
 4283            _minimumVersion = new Version(0, 0, 0, 1);
 4284            _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>();
 85
 4286            _assemblyLoadContexts = new List<AssemblyLoadContext>();
 4287        }
 88
 89        private IHttpClientFactory HttpClientFactory
 90        {
 91            get
 92            {
 093                return _httpClientFactory ??= _appHost.Resolve<IHttpClientFactory>();
 94            }
 95        }
 96
 97        /// <summary>
 98        /// Gets the Plugins.
 99        /// </summary>
 26100        public IReadOnlyList<LocalPlugin> Plugins => _plugins;
 101
 102        /// <summary>
 103        /// Returns all the assemblies.
 104        /// </summary>
 105        /// <returns>An IEnumerable{Assembly}.</returns>
 106        public IEnumerable<Assembly> LoadAssemblies()
 107        {
 108            // Attempt to remove any deleted plugins and change any successors to be active.
 50109            for (int i = _plugins.Count - 1; i >= 0; i--)
 110            {
 2111                var plugin = _plugins[i];
 2112                if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin))
 113                {
 114                    // See if there is another version, and if so make that active.
 0115                    ProcessAlternative(plugin);
 116                }
 117            }
 118
 119            // Now load the assemblies..
 50120            foreach (var plugin in _plugins)
 121            {
 2122                UpdatePluginSupersededStatus(plugin);
 123
 2124                if (plugin.IsEnabledAndSupported == false)
 125                {
 2126                    _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name)
 2127                    continue;
 128                }
 129
 0130                var assemblyLoadContext = new PluginLoadContext(plugin.Path);
 0131                _assemblyLoadContexts.Add(assemblyLoadContext);
 132
 0133                var assemblies = new List<Assembly>(plugin.DllFiles.Count);
 0134                var loadedAll = true;
 135
 0136                foreach (var file in plugin.DllFiles)
 137                {
 138                    try
 139                    {
 0140                        assemblies.Add(assemblyLoadContext.LoadFromAssemblyPath(file));
 0141                    }
 0142                    catch (FileLoadException ex)
 143                    {
 0144                        _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin", file);
 0145                        ChangePluginState(plugin, PluginStatus.Malfunctioned);
 0146                        loadedAll = false;
 0147                        break;
 148                    }
 149#pragma warning disable CA1031 // Do not catch general exception types
 0150                    catch (Exception ex)
 151#pragma warning restore CA1031 // Do not catch general exception types
 152                    {
 0153                        _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling pl
 0154                        ChangePluginState(plugin, PluginStatus.Malfunctioned);
 0155                        loadedAll = false;
 0156                        break;
 157                    }
 158                }
 159
 0160                if (!loadedAll)
 161                {
 162                    continue;
 163                }
 164
 0165                foreach (var assembly in assemblies)
 166                {
 167                    try
 168                    {
 169                        // Load all required types to verify that the plugin will load
 0170                        assembly.GetTypes();
 0171                    }
 0172                    catch (SystemException ex) when (ex is TypeLoadException or ReflectionTypeLoadException) // Undocume
 173                    {
 0174                        _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references
 0175                        ChangePluginState(plugin, PluginStatus.NotSupported);
 0176                        break;
 177                    }
 178#pragma warning disable CA1031 // Do not catch general exception types
 0179                    catch (Exception ex)
 180#pragma warning restore CA1031 // Do not catch general exception types
 181                    {
 0182                        _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling pl
 0183                        ChangePluginState(plugin, PluginStatus.Malfunctioned);
 0184                        break;
 185                    }
 186
 0187                    _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, assembly.Locatio
 0188                    yield return assembly;
 189                }
 0190            }
 23191        }
 192
 193        /// <summary>
 194        /// Creates all the plugin instances.
 195        /// </summary>
 196        public void CreatePlugins()
 197        {
 22198            _ = _appHost.GetExports<IPlugin>(CreatePluginInstance);
 22199        }
 200
 201        /// <summary>
 202        /// Registers the plugin's services with the DI.
 203        /// Note: DI is not yet instantiated yet.
 204        /// </summary>
 205        /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param>
 206        public void RegisterServices(IServiceCollection serviceCollection)
 207        {
 44208            foreach (var pluginServiceRegistrator in _appHost.GetExportTypes<IPluginServiceRegistrator>())
 209            {
 0210                var plugin = GetPluginByAssembly(pluginServiceRegistrator.Assembly);
 0211                if (plugin is null)
 212                {
 0213                    _logger.LogError("Unable to find plugin in assembly {Assembly}", pluginServiceRegistrator.Assembly.F
 0214                    continue;
 215                }
 216
 0217                UpdatePluginSupersededStatus(plugin);
 0218                if (!plugin.IsEnabledAndSupported)
 219                {
 220                    continue;
 221                }
 222
 223                try
 224                {
 0225                    var instance = (IPluginServiceRegistrator?)Activator.CreateInstance(pluginServiceRegistrator);
 0226                    instance?.RegisterServices(serviceCollection, _appHost);
 0227                }
 228#pragma warning disable CA1031 // Do not catch general exception types
 0229                catch (Exception ex)
 230#pragma warning restore CA1031 // Do not catch general exception types
 231                {
 0232                    _logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.
 0233                    if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
 234                    {
 0235                        _logger.LogInformation("Disabling plugin {Path}", plugin.Path);
 236                    }
 0237                }
 238            }
 22239        }
 240
 241        /// <summary>
 242        /// Imports a plugin manifest from <paramref name="folder"/>.
 243        /// </summary>
 244        /// <param name="folder">Folder of the plugin.</param>
 245        public void ImportPluginFrom(string folder)
 246        {
 0247            ArgumentException.ThrowIfNullOrEmpty(folder);
 248
 249            // Load the plugin.
 0250            var plugin = LoadManifest(folder);
 251            // Make sure we haven't already loaded this.
 0252            if (_plugins.Any(p => p.Manifest.Equals(plugin.Manifest)))
 253            {
 0254                return;
 255            }
 256
 0257            _plugins.Add(plugin);
 258
 259            // Updating a disabled plugin must not enable it again.
 0260            if (plugin.Manifest.Status == PluginStatus.Disabled)
 261            {
 0262                ProcessAlternative(plugin);
 0263                return;
 264            }
 265
 0266            EnablePlugin(plugin);
 0267        }
 268
 269        /// <summary>
 270        /// Removes the plugin reference '<paramref name="plugin"/>.
 271        /// </summary>
 272        /// <param name="plugin">The plugin.</param>
 273        /// <returns>Outcome of the operation.</returns>
 274        public bool RemovePlugin(LocalPlugin plugin)
 275        {
 0276            ArgumentNullException.ThrowIfNull(plugin);
 277
 0278            if (DeletePlugin(plugin))
 279            {
 0280                ProcessAlternative(plugin);
 0281                return true;
 282            }
 283
 0284            _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path);
 285            // Unable to delete, so disable.
 0286            if (ChangePluginState(plugin, PluginStatus.Deleted))
 287            {
 0288                ProcessAlternative(plugin);
 0289                return true;
 290            }
 291
 0292            return false;
 293        }
 294
 295        /// <summary>
 296        /// Attempts to find the plugin with and id of <paramref name="id"/>.
 297        /// </summary>
 298        /// <param name="id">The <see cref="Guid"/> of plugin.</param>
 299        /// <param name="version">Optional <see cref="Version"/> of the plugin to locate.</param>
 300        /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns>
 301        public LocalPlugin? GetPlugin(Guid id, Version? version = null)
 302        {
 303            LocalPlugin? plugin;
 304
 831305            if (version is null)
 306            {
 307                // If no version is given, return the current instance.
 0308                var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList();
 309
 0310                plugin = plugins.FirstOrDefault(p => p.Instance is not null) ?? plugins.MaxBy(p => p.Version);
 311            }
 312            else
 313            {
 314                // Match id and version number.
 831315                plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version));
 316            }
 317
 831318            return plugin;
 319        }
 320
 321        /// <summary>
 322        /// Enables the plugin, disabling all other versions.
 323        /// </summary>
 324        /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
 325        public void EnablePlugin(LocalPlugin plugin)
 326        {
 0327            ArgumentNullException.ThrowIfNull(plugin);
 328
 0329            if (ChangePluginState(plugin, PluginStatus.Active))
 330            {
 331                // See if there is another version, and if so, supercede it.
 0332                ProcessAlternative(plugin);
 333            }
 0334        }
 335
 336        /// <summary>
 337        /// Disable the plugin.
 338        /// </summary>
 339        /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
 340        public void DisablePlugin(LocalPlugin plugin)
 341        {
 1342            ArgumentNullException.ThrowIfNull(plugin);
 343
 344            // Update the manifest on disk
 1345            if (ChangePluginState(plugin, PluginStatus.Disabled))
 346            {
 347                // If there is another version, activate it.
 1348                ProcessAlternative(plugin);
 349            }
 1350        }
 351
 352        /// <summary>
 353        /// Disable the plugin.
 354        /// </summary>
 355        /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param>
 356        public void FailPlugin(Assembly assembly)
 357        {
 358            // Only save if disabled.
 0359            ArgumentNullException.ThrowIfNull(assembly);
 360
 0361            var plugin = _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location));
 0362            if (plugin is null)
 363            {
 364                // A plugin's assembly didn't cause this issue, so ignore it.
 0365                return;
 366            }
 367
 0368            ChangePluginState(plugin, PluginStatus.Malfunctioned);
 0369        }
 370
 371        /// <inheritdoc/>
 372        public bool SaveManifest(PluginManifest manifest, string path)
 373        {
 374            try
 375            {
 16376                var data = JsonSerializer.Serialize(manifest, _jsonOptions);
 16377                File.WriteAllText(Path.Combine(path, MetafileName), data);
 16378                return true;
 379            }
 0380            catch (ArgumentException e)
 381            {
 0382                _logger.LogWarning(e, "Unable to save plugin manifest due to invalid value. {Path}", path);
 0383                return false;
 384            }
 16385        }
 386
 387        /// <inheritdoc/>
 388        public async Task<bool> PopulateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus sta
 389        {
 5390            var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString());
 5391            var imagePath = string.Empty;
 392
 5393            if (!string.IsNullOrEmpty(packageInfo.ImageUrl))
 394            {
 0395                var url = new Uri(packageInfo.ImageUrl);
 0396                imagePath = Path.Join(path, url.Segments[^1]);
 397
 0398                var fileStream = AsyncFile.OpenWrite(imagePath);
 0399                Stream? downloadStream = null;
 400                try
 401                {
 0402                    downloadStream = await HttpClientFactory
 0403                        .CreateClient(NamedClient.Default)
 0404                        .GetStreamAsync(url)
 0405                        .ConfigureAwait(false);
 406
 0407                    await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false);
 0408                }
 0409                catch (HttpRequestException ex)
 410                {
 0411                    _logger.LogError(ex, "Failed to download image to path {Path} on disk.", imagePath);
 0412                    imagePath = string.Empty;
 0413                }
 414                finally
 415                {
 0416                    await fileStream.DisposeAsync().ConfigureAwait(false);
 0417                    if (downloadStream is not null)
 418                    {
 0419                        await downloadStream.DisposeAsync().ConfigureAwait(false);
 420                    }
 421                }
 0422            }
 423
 5424            var manifest = new PluginManifest
 5425            {
 5426                Category = packageInfo.Category,
 5427                Changelog = versionInfo.Changelog ?? string.Empty,
 5428                Description = packageInfo.Description,
 5429                Id = packageInfo.Id,
 5430                Name = packageInfo.Name,
 5431                Overview = packageInfo.Overview,
 5432                Owner = packageInfo.Owner,
 5433                TargetAbi = versionInfo.TargetAbi ?? string.Empty,
 5434                Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo
 5435                Version = versionInfo.Version,
 5436                Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled
 5437                AutoUpdate = true,
 5438                ImagePath = imagePath
 5439            };
 440
 5441            if (!await ReconcileManifest(manifest, path).ConfigureAwait(false))
 442            {
 443                // An error occurred during reconciliation and saving could be undesirable.
 0444                return false;
 445            }
 446
 5447            return SaveManifest(manifest, path);
 5448        }
 449
 450        /// <inheritdoc />
 451        public void Dispose()
 452        {
 44453            foreach (var assemblyLoadContext in _assemblyLoadContexts)
 454            {
 0455                assemblyLoadContext.Unload();
 456            }
 22457        }
 458
 459        /// <summary>
 460        /// Reconciles the manifest against any properties that exist locally in a pre-packaged meta.json found at the p
 461        /// If no file is found, no reconciliation occurs.
 462        /// </summary>
 463        /// <param name="manifest">The <see cref="PluginManifest"/> to reconcile against.</param>
 464        /// <param name="path">The plugin path.</param>
 465        /// <returns>The reconciled <see cref="PluginManifest"/>.</returns>
 466        private async Task<bool> ReconcileManifest(PluginManifest manifest, string path)
 467        {
 468            try
 469            {
 5470                var metafile = Path.Combine(path, MetafileName);
 5471                if (!File.Exists(metafile))
 472                {
 1473                    _logger.LogInformation("No local manifest exists for plugin {Plugin}. Skipping manifest reconciliati
 1474                    return true;
 475                }
 476
 4477                using var metaStream = File.OpenRead(metafile);
 4478                var localManifest = await JsonSerializer.DeserializeAsync<PluginManifest>(metaStream, _jsonOptions).Conf
 4479                localManifest ??= new PluginManifest();
 480
 4481                if (!Equals(localManifest.Id, manifest.Id))
 482                {
 1483                    _logger.LogError("The manifest ID {LocalUUID} did not match the package info ID {PackageUUID}.", loc
 1484                    manifest.Status = PluginStatus.Malfunctioned;
 485                }
 486
 4487                if (localManifest.Version != manifest.Version)
 488                {
 489                    // Package information provides the version and is the source of truth. Pre-packages meta.json is as
 3490                    _logger.LogWarning("The version of the local manifest was {LocalVersion}, but {PackageVersion} was e
 491                }
 492
 493                // Explicitly mapping properties instead of using reflection is preferred here.
 4494                manifest.Category = string.IsNullOrEmpty(localManifest.Category) ? manifest.Category : localManifest.Cat
 4495                manifest.AutoUpdate = localManifest.AutoUpdate; // Preserve whatever is local. Package info does not hav
 4496                manifest.Changelog = string.IsNullOrEmpty(localManifest.Changelog) ? manifest.Changelog : localManifest.
 4497                manifest.Description = string.IsNullOrEmpty(localManifest.Description) ? manifest.Description : localMan
 4498                manifest.Name = string.IsNullOrEmpty(localManifest.Name) ? manifest.Name : localManifest.Name;
 4499                manifest.Overview = string.IsNullOrEmpty(localManifest.Overview) ? manifest.Overview : localManifest.Ove
 4500                manifest.Owner = string.IsNullOrEmpty(localManifest.Owner) ? manifest.Owner : localManifest.Owner;
 4501                manifest.TargetAbi = string.IsNullOrEmpty(localManifest.TargetAbi) ? manifest.TargetAbi : localManifest.
 4502                manifest.Timestamp = localManifest.Timestamp.Equals(default) ? manifest.Timestamp : localManifest.Timest
 4503                manifest.ImagePath = string.IsNullOrEmpty(localManifest.ImagePath) ? manifest.ImagePath : localManifest.
 4504                manifest.Assemblies = localManifest.Assemblies;
 505
 4506                return true;
 507            }
 0508            catch (Exception e)
 509            {
 0510                _logger.LogWarning(e, "Unable to reconcile plugin manifest due to an error. {Path}", path);
 0511                return false;
 512            }
 5513        }
 514
 515        /// <summary>
 516        /// Changes a plugin's load status.
 517        /// </summary>
 518        /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param>
 519        /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param>
 520        /// <returns>Success of the task.</returns>
 521        private bool ChangePluginState(LocalPlugin plugin, PluginStatus state)
 522        {
 10523            if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path))
 524            {
 525                // No need to save as the state hasn't changed.
 0526                return true;
 527            }
 528
 10529            plugin.Manifest.Status = state;
 10530            return SaveManifest(plugin.Manifest, plugin.Path);
 531        }
 532
 533        /// <summary>
 534        /// Finds the plugin record using the assembly.
 535        /// </summary>
 536        /// <param name="assembly">The <see cref="Assembly"/> being sought.</param>
 537        /// <returns>The matching record, or null if not found.</returns>
 538        private LocalPlugin? GetPluginByAssembly(Assembly assembly)
 539        {
 540            // Find which plugin it is by the path.
 176541            return _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location, StringComparer.Ordinal));
 542        }
 543
 544        /// <summary>
 545        /// Creates the instance safe.
 546        /// </summary>
 547        /// <param name="type">The type.</param>
 548        /// <returns>System.Object.</returns>
 549        private IPlugin? CreatePluginInstance(Type type)
 550        {
 551            // Find the record for this plugin.
 176552            var plugin = GetPluginByAssembly(type.Assembly);
 176553            if (plugin?.Manifest.Status < PluginStatus.Active)
 554            {
 0555                return null;
 556            }
 557
 558            try
 559            {
 176560                _logger.LogDebug("Creating instance of {Type}", type);
 561                // _appHost.ServiceProvider is already assigned when we create the plugins
 176562                var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider!, type);
 176563                if (plugin is null)
 564                {
 565                    // Create a dummy record for the providers.
 566                    // TODO: remove this code once all provided have been released as separate plugins.
 176567                    plugin = new LocalPlugin(
 176568                        instance.AssemblyFilePath,
 176569                        true,
 176570                        new PluginManifest
 176571                        {
 176572                            Id = instance.Id,
 176573                            Status = PluginStatus.Active,
 176574                            Name = instance.Name,
 176575                            Version = instance.Version.ToString(),
 176576                            ImageResourceName = (instance as IHasEmbeddedImage)?.ImageResourceName
 176577                        })
 176578                    {
 176579                        Instance = instance
 176580                    };
 581
 176582                    _plugins.Add(plugin);
 583
 176584                    plugin.Manifest.Status = PluginStatus.Active;
 585                }
 586                else
 587                {
 0588                    plugin.Instance = instance;
 0589                    var manifest = plugin.Manifest;
 0590                    var pluginStr = instance.Version.ToString();
 0591                    bool changed = false;
 0592                    if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)
 0593                        || !manifest.Id.Equals(instance.Id))
 594                    {
 595                        // If a plugin without a manifest failed to load due to an external issue (eg config),
 596                        // this updates the manifest to the actual plugin values.
 0597                        manifest.Version = pluginStr;
 0598                        manifest.Name = plugin.Instance.Name;
 0599                        manifest.Description = plugin.Instance.Description;
 0600                        manifest.Id = plugin.Instance.Id;
 0601                        changed = true;
 602                    }
 603
 0604                    changed = changed || manifest.Status != PluginStatus.Active;
 0605                    manifest.Status = PluginStatus.Active;
 606
 0607                    if (changed)
 608                    {
 0609                        SaveManifest(manifest, plugin.Path);
 610                    }
 611                }
 612
 176613                _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
 614
 176615                return instance;
 616            }
 617#pragma warning disable CA1031 // Do not catch general exception types
 0618            catch (Exception ex)
 619#pragma warning restore CA1031 // Do not catch general exception types
 620            {
 0621                _logger.LogError(ex, "Error creating {Type}", type.FullName);
 0622                if (plugin is not null)
 623                {
 0624                    if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
 625                    {
 0626                        _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
 0627                        return null;
 628                    }
 629                }
 630
 0631                _logger.LogDebug("Unable to auto-disable.");
 0632                return null;
 633            }
 176634        }
 635
 636        private void UpdatePluginSupersededStatus(LocalPlugin plugin)
 637        {
 2638            if (plugin.Manifest.Status != PluginStatus.Superseded)
 639            {
 1640                return;
 641            }
 642
 1643            var successor = _plugins.FirstOrDefault(p => p.Id.Equals(plugin.Id)
 1644                && p.Version > plugin.Version
 1645                && (p.IsEnabledAndSupported || p.Manifest.Status == PluginStatus.Disabled));
 1646            if (successor is not null)
 647            {
 1648                return;
 649            }
 650
 0651            plugin.Manifest.Status = PluginStatus.Active;
 0652        }
 653
 654        /// <summary>
 655        /// Attempts to delete a plugin.
 656        /// </summary>
 657        /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
 658        /// <returns>True if successful.</returns>
 659        private bool DeletePlugin(LocalPlugin plugin)
 660        {
 661            // Attempt a cleanup of old folders.
 662            try
 663            {
 0664                Directory.Delete(plugin.Path, true);
 0665                _logger.LogDebug("Deleted {Path}", plugin.Path);
 0666            }
 667#pragma warning disable CA1031 // Do not catch general exception types
 0668            catch
 669#pragma warning restore CA1031 // Do not catch general exception types
 670            {
 0671                return false;
 672            }
 673
 0674            return _plugins.Remove(plugin);
 0675        }
 676
 677        internal LocalPlugin LoadManifest(string dir)
 678        {
 679            Version? version;
 25680            PluginManifest? manifest = null;
 25681            var metafile = Path.Combine(dir, MetafileName);
 25682            if (File.Exists(metafile))
 683            {
 684                // Only path where this stays null is when File.ReadAllBytes throws an IOException
 25685                byte[] data = null!;
 686                try
 687                {
 25688                    data = File.ReadAllBytes(metafile);
 25689                    manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
 25690                }
 0691                catch (IOException ex)
 692                {
 0693                    _logger.LogError(ex, "Error reading file {Path}.", dir);
 0694                }
 0695                catch (JsonException ex)
 696                {
 0697                    _logger.LogError(ex, "Error deserializing {Json}.", Encoding.UTF8.GetString(data));
 0698                }
 699
 25700                if (manifest is not null)
 701                {
 25702                    if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
 703                    {
 16704                        targetAbi = _minimumVersion;
 705                    }
 706
 25707                    if (!Version.TryParse(manifest.Version, out version))
 708                    {
 12709                        manifest.Version = _minimumVersion.ToString();
 710                    }
 711
 25712                    return new LocalPlugin(dir, _appVersion >= targetAbi, manifest);
 713                }
 714            }
 715
 716            // No metafile, so lets see if the folder is versioned.
 717            // TODO: Phase this support out in future versions.
 0718            metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
 0719            int versionIndex = dir.LastIndexOf('_');
 0720            if (versionIndex != -1)
 721            {
 722                // Get the version number from the filename if possible.
 0723                metafile = Path.GetFileName(dir[..versionIndex]);
 0724                version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersi
 725            }
 726            else
 727            {
 728                // Un-versioned folder - Add it under the path name and version it suitable for this instance.
 0729                version = _appVersion;
 730            }
 731
 732            // Auto-create a plugin manifest, so we can disable it, if it fails to load.
 0733            manifest = new PluginManifest
 0734            {
 0735                Status = PluginStatus.Active,
 0736                Name = metafile,
 0737                AutoUpdate = false,
 0738                Id = metafile.GetMD5(),
 0739                TargetAbi = _appVersion.ToString(),
 0740                Version = version.ToString()
 0741            };
 742
 0743            return new LocalPlugin(dir, true, manifest);
 744        }
 745
 746        /// <summary>
 747        /// Gets the list of local plugins.
 748        /// </summary>
 749        /// <returns>Enumerable of local plugins.</returns>
 750        private IEnumerable<LocalPlugin> DiscoverPlugins()
 751        {
 18752            var versions = new List<LocalPlugin>();
 753
 18754            if (!Directory.Exists(_pluginsPath))
 755            {
 756                // Plugin path doesn't exist, don't try to enumerate sub-folders.
 0757                return Enumerable.Empty<LocalPlugin>();
 758            }
 759
 18760            var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
 76761            foreach (var dir in directories)
 762            {
 20763                versions.Add(LoadManifest(dir));
 764            }
 765
 18766            string lastName = string.Empty;
 18767            versions.Sort(LocalPlugin.Compare);
 768            // Traverse backwards through the list.
 769            // The first item will be the latest version.
 76770            for (int x = versions.Count - 1; x >= 0; x--)
 771            {
 20772                var entry = versions[x];
 20773                if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
 774                {
 17775                    lastName = string.Empty;
 776
 17777                    if (!TryGetPluginDlls(entry, out var allowedDlls))
 778                    {
 9779                        _logger.LogError("One or more assembly paths was invalid. Marking plugin {Plugin} as \"Malfuncti
 9780                        ChangePluginState(entry, PluginStatus.Malfunctioned);
 9781                        continue;
 782                    }
 783
 8784                    entry.DllFiles = allowedDlls;
 785
 786                    // Only clean up older versions when this version will actually be loaded.
 8787                    if (entry.IsEnabledAndSupported)
 788                    {
 5789                        lastName = entry.Name;
 790                    }
 791
 5792                    continue;
 793                }
 794
 3795                if (string.IsNullOrEmpty(lastName))
 796                {
 797                    // Unnamed plugin, so there is nothing to match older versions against.
 798                    continue;
 799                }
 800
 0801                var cleaned = false;
 0802                var path = entry.Path;
 803                // Attempt a cleanup of old folders.
 804                try
 805                {
 0806                    _logger.LogDebug("Deleting {Path}", path);
 0807                    Directory.Delete(path, true);
 0808                    cleaned = true;
 0809                }
 810#pragma warning disable CA1031 // Do not catch general exception types
 0811                catch (Exception e)
 812#pragma warning restore CA1031 // Do not catch general exception types
 813                {
 0814                    _logger.LogWarning(e, "Unable to delete {Path}", path);
 0815                }
 816
 0817                if (cleaned)
 818                {
 0819                    versions.RemoveAt(x);
 820                }
 821                else
 822                {
 0823                    ChangePluginState(entry, PluginStatus.Deleted);
 824                }
 825            }
 826
 827            // Only want plugin folders which have files.
 18828            return versions.Where(p => p.DllFiles.Count != 0);
 829        }
 830
 831        /// <summary>
 832        /// Attempts to retrieve valid DLLs from the plugin path. This method will consider the assembly whitelist
 833        /// from the manifest.
 834        /// </summary>
 835        /// <remarks>
 836        /// Loading DLLs from externally supplied paths introduces a path traversal risk. This method
 837        /// uses a safelisting tactic of considering DLLs from the plugin directory and only using
 838        /// the plugin's canonicalized assembly whitelist for comparison. See
 839        /// <see href="https://owasp.org/www-community/attacks/Path_Traversal"/> for more details.
 840        /// </remarks>
 841        /// <param name="plugin">The plugin.</param>
 842        /// <param name="whitelistedDlls">The whitelisted DLLs. If the method returns <see langword="false"/>, this will
 843        /// <returns>
 844        /// <see langword="true"/> if all assemblies listed in the manifest were available in the plugin directory.
 845        /// <see langword="false"/> if any assemblies were invalid or missing from the plugin directory.
 846        /// </returns>
 847        /// <exception cref="ArgumentNullException">If the <see cref="LocalPlugin"/> is null.</exception>
 848        private bool TryGetPluginDlls(LocalPlugin plugin, out IReadOnlyList<string> whitelistedDlls)
 849        {
 17850            ArgumentNullException.ThrowIfNull(plugin);
 851
 17852            IReadOnlyList<string> pluginDlls = Directory.GetFiles(plugin.Path, "*.dll", SearchOption.AllDirectories);
 853
 17854            whitelistedDlls = Array.Empty<string>();
 17855            if (pluginDlls.Count > 0 && plugin.Manifest.Assemblies.Count > 0)
 856            {
 12857                _logger.LogInformation("Registering whitelisted assemblies for plugin \"{Plugin}\"...", plugin.Name);
 858
 12859                var canonicalizedPaths = new List<string>();
 45860                foreach (var path in plugin.Manifest.Assemblies)
 861                {
 12862                    var canonicalized = Path.Combine(plugin.Path, path).Canonicalize();
 863
 864                    // Ensure we stay in the plugin directory.
 12865                    if (!canonicalized.StartsWith(plugin.Path.NormalizePath(), StringComparison.Ordinal))
 866                    {
 3867                        _logger.LogError("Assembly path {Path} is not inside the plugin directory.", path);
 3868                        return false;
 869                    }
 870
 9871                    canonicalizedPaths.Add(canonicalized);
 872                }
 873
 9874                var intersected = pluginDlls.Intersect(canonicalizedPaths).ToList();
 875
 9876                if (intersected.Count != canonicalizedPaths.Count)
 877                {
 6878                    _logger.LogError("Plugin {Plugin} contained assembly paths that were not found in the directory.", p
 6879                    return false;
 880                }
 881
 3882                whitelistedDlls = intersected;
 883            }
 884            else
 885            {
 886                // No whitelist, default to loading all DLLs in plugin directory.
 5887                whitelistedDlls = pluginDlls;
 888            }
 889
 8890            return true;
 3891        }
 892
 893        /// <summary>
 894        /// Changes the status of the other versions of the plugin to "Superseded".
 895        /// </summary>
 896        /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param>
 897        private void ProcessAlternative(LocalPlugin plugin)
 898        {
 899            // Detect whether there is another version of this plugin that needs disabling.
 1900            var previousVersion = _plugins.OrderByDescending(p => p.Version)
 1901                .FirstOrDefault(
 1902                    p => p.Id.Equals(plugin.Id)
 1903                    && p.IsEnabledAndSupported
 1904                    && p.Version != plugin.Version);
 905
 1906            if (previousVersion is null)
 907            {
 908                // Memory only, so that the web will show restart required. The manifest must keep
 909                // holding the persisted state, or a later save would write the wrong state to disk.
 1910                plugin.RestartRequired = true;
 1911                return;
 912            }
 913
 0914            if (plugin.Manifest.Status == PluginStatus.Active && !ChangePluginState(previousVersion, PluginStatus.Supers
 915            {
 0916                _logger.LogError("Unable to enable version {Version} of {Name}", previousVersion.Version, previousVersio
 917            }
 0918            else if (plugin.Manifest.Status == PluginStatus.Superseded && !ChangePluginState(previousVersion, PluginStat
 919            {
 0920                _logger.LogError("Unable to supercede version {Version} of {Name}", previousVersion.Version, previousVer
 921            }
 922
 0923            plugin.RestartRequired = true;
 0924        }
 925    }
 926}