< 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
44%
Covered lines: 161
Uncovered lines: 204
Coverable lines: 365
Total lines: 914
Line coverage: 44.1%
Branch coverage
40%
Covered branches: 70
Total branches: 172
Branch coverage: 40.6%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 2/13/2026 - 12:11:21 AM Line coverage: 43.4% (110/253) Branch coverage: 38.5% (44/114) Total lines: 9134/19/2026 - 12:14:27 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: 914 2/13/2026 - 12:11:21 AM Line coverage: 43.4% (110/253) Branch coverage: 38.5% (44/114) Total lines: 9134/19/2026 - 12:14:27 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: 914

Coverage delta

Coverage delta 2 -2

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)80%1010100%
get_HttpClientFactory()0%620%
get_Plugins()100%11100%
LoadAssemblies()18.75%221167.14%
CreatePlugins()100%11100%
RegisterServices(...)20%771012.5%
ImportPluginFrom(...)0%620%
RemovePlugin(...)0%2040%
GetPlugin(...)25%5460%
EnablePlugin(...)0%620%
DisablePlugin(...)0%620%
FailPlugin(...)0%620%
SaveManifest(...)100%1157.14%
PopulateManifest()42.85%341453.65%
Dispose()50%2266.66%
ReconcileManifest()61.53%272689.28%
ChangePluginState(...)50%4475%
GetPluginByAssembly(...)100%11100%
CreatePluginInstance(...)30%702050%
UpdatePluginSupersededStatus(...)0%2040%
DeletePlugin(...)100%210%
LoadManifest(...)41.66%481237.14%
DiscoverPlugins()75%321660.6%
TryGetPluginDlls(...)80%101095%
ProcessAlternative(...)0%110100%

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        {
 3863            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 3864            _pluginsPath = pluginsPath;
 3865            _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion));
 3866            _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options)
 3867            {
 3868                WriteIndented = true
 3869            };
 70
 71            // We need to use the default GUID converter, so we need to remove any custom ones.
 68472            for (int a = _jsonOptions.Converters.Count - 1; a >= 0; a--)
 73            {
 34274                if (_jsonOptions.Converters[a] is JsonGuidConverter convertor)
 75                {
 3876                    _jsonOptions.Converters.Remove(convertor);
 3877                    break;
 78                }
 79            }
 80
 3881            _config = config;
 3882            _appHost = appHost;
 3883            _minimumVersion = new Version(0, 0, 0, 1);
 3884            _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>();
 85
 3886            _assemblyLoadContexts = new List<AssemblyLoadContext>();
 3887        }
 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>
 24100        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.
 42109            for (int i = _plugins.Count - 1; i >= 0; i--)
 110            {
 0111                var plugin = _plugins[i];
 0112                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..
 42120            foreach (var plugin in _plugins)
 121            {
 0122                UpdatePluginSupersededStatus(plugin);
 123
 0124                if (plugin.IsEnabledAndSupported == false)
 125                {
 0126                    _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name)
 0127                    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            }
 21191        }
 192
 193        /// <summary>
 194        /// Creates all the plugin instances.
 195        /// </summary>
 196        public void CreatePlugins()
 197        {
 21198            _ = _appHost.GetExports<IPlugin>(CreatePluginInstance);
 21199        }
 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        {
 42208            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            }
 21239        }
 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);
 0258            EnablePlugin(plugin);
 0259        }
 260
 261        /// <summary>
 262        /// Removes the plugin reference '<paramref name="plugin"/>.
 263        /// </summary>
 264        /// <param name="plugin">The plugin.</param>
 265        /// <returns>Outcome of the operation.</returns>
 266        public bool RemovePlugin(LocalPlugin plugin)
 267        {
 0268            ArgumentNullException.ThrowIfNull(plugin);
 269
 0270            if (DeletePlugin(plugin))
 271            {
 0272                ProcessAlternative(plugin);
 0273                return true;
 274            }
 275
 0276            _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path);
 277            // Unable to delete, so disable.
 0278            if (ChangePluginState(plugin, PluginStatus.Deleted))
 279            {
 0280                ProcessAlternative(plugin);
 0281                return true;
 282            }
 283
 0284            return false;
 285        }
 286
 287        /// <summary>
 288        /// Attempts to find the plugin with and id of <paramref name="id"/>.
 289        /// </summary>
 290        /// <param name="id">The <see cref="Guid"/> of plugin.</param>
 291        /// <param name="version">Optional <see cref="Version"/> of the plugin to locate.</param>
 292        /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns>
 293        public LocalPlugin? GetPlugin(Guid id, Version? version = null)
 294        {
 295            LocalPlugin? plugin;
 296
 831297            if (version is null)
 298            {
 299                // If no version is given, return the current instance.
 0300                var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList();
 301
 0302                plugin = plugins.FirstOrDefault(p => p.Instance is not null) ?? plugins.MaxBy(p => p.Version);
 303            }
 304            else
 305            {
 306                // Match id and version number.
 831307                plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version));
 308            }
 309
 831310            return plugin;
 311        }
 312
 313        /// <summary>
 314        /// Enables the plugin, disabling all other versions.
 315        /// </summary>
 316        /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
 317        public void EnablePlugin(LocalPlugin plugin)
 318        {
 0319            ArgumentNullException.ThrowIfNull(plugin);
 320
 0321            if (ChangePluginState(plugin, PluginStatus.Active))
 322            {
 323                // See if there is another version, and if so, supercede it.
 0324                ProcessAlternative(plugin);
 325            }
 0326        }
 327
 328        /// <summary>
 329        /// Disable the plugin.
 330        /// </summary>
 331        /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
 332        public void DisablePlugin(LocalPlugin plugin)
 333        {
 0334            ArgumentNullException.ThrowIfNull(plugin);
 335
 336            // Update the manifest on disk
 0337            if (ChangePluginState(plugin, PluginStatus.Disabled))
 338            {
 339                // If there is another version, activate it.
 0340                ProcessAlternative(plugin);
 341            }
 0342        }
 343
 344        /// <summary>
 345        /// Disable the plugin.
 346        /// </summary>
 347        /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param>
 348        public void FailPlugin(Assembly assembly)
 349        {
 350            // Only save if disabled.
 0351            ArgumentNullException.ThrowIfNull(assembly);
 352
 0353            var plugin = _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location));
 0354            if (plugin is null)
 355            {
 356                // A plugin's assembly didn't cause this issue, so ignore it.
 0357                return;
 358            }
 359
 0360            ChangePluginState(plugin, PluginStatus.Malfunctioned);
 0361        }
 362
 363        /// <inheritdoc/>
 364        public bool SaveManifest(PluginManifest manifest, string path)
 365        {
 366            try
 367            {
 14368                var data = JsonSerializer.Serialize(manifest, _jsonOptions);
 14369                File.WriteAllText(Path.Combine(path, MetafileName), data);
 14370                return true;
 371            }
 0372            catch (ArgumentException e)
 373            {
 0374                _logger.LogWarning(e, "Unable to save plugin manifest due to invalid value. {Path}", path);
 0375                return false;
 376            }
 14377        }
 378
 379        /// <inheritdoc/>
 380        public async Task<bool> PopulateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus sta
 381        {
 4382            var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString());
 4383            var imagePath = string.Empty;
 384
 4385            if (!string.IsNullOrEmpty(packageInfo.ImageUrl))
 386            {
 0387                var url = new Uri(packageInfo.ImageUrl);
 0388                imagePath = Path.Join(path, url.Segments[^1]);
 389
 0390                var fileStream = AsyncFile.OpenWrite(imagePath);
 0391                Stream? downloadStream = null;
 392                try
 393                {
 0394                    downloadStream = await HttpClientFactory
 0395                        .CreateClient(NamedClient.Default)
 0396                        .GetStreamAsync(url)
 0397                        .ConfigureAwait(false);
 398
 0399                    await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false);
 0400                }
 0401                catch (HttpRequestException ex)
 402                {
 0403                    _logger.LogError(ex, "Failed to download image to path {Path} on disk.", imagePath);
 0404                    imagePath = string.Empty;
 0405                }
 406                finally
 407                {
 0408                    await fileStream.DisposeAsync().ConfigureAwait(false);
 0409                    if (downloadStream is not null)
 410                    {
 0411                        await downloadStream.DisposeAsync().ConfigureAwait(false);
 412                    }
 413                }
 0414            }
 415
 4416            var manifest = new PluginManifest
 4417            {
 4418                Category = packageInfo.Category,
 4419                Changelog = versionInfo.Changelog ?? string.Empty,
 4420                Description = packageInfo.Description,
 4421                Id = packageInfo.Id,
 4422                Name = packageInfo.Name,
 4423                Overview = packageInfo.Overview,
 4424                Owner = packageInfo.Owner,
 4425                TargetAbi = versionInfo.TargetAbi ?? string.Empty,
 4426                Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo
 4427                Version = versionInfo.Version,
 4428                Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled
 4429                AutoUpdate = true,
 4430                ImagePath = imagePath
 4431            };
 432
 4433            if (!await ReconcileManifest(manifest, path).ConfigureAwait(false))
 434            {
 435                // An error occurred during reconciliation and saving could be undesirable.
 0436                return false;
 437            }
 438
 4439            return SaveManifest(manifest, path);
 4440        }
 441
 442        /// <inheritdoc />
 443        public void Dispose()
 444        {
 42445            foreach (var assemblyLoadContext in _assemblyLoadContexts)
 446            {
 0447                assemblyLoadContext.Unload();
 448            }
 21449        }
 450
 451        /// <summary>
 452        /// Reconciles the manifest against any properties that exist locally in a pre-packaged meta.json found at the p
 453        /// If no file is found, no reconciliation occurs.
 454        /// </summary>
 455        /// <param name="manifest">The <see cref="PluginManifest"/> to reconcile against.</param>
 456        /// <param name="path">The plugin path.</param>
 457        /// <returns>The reconciled <see cref="PluginManifest"/>.</returns>
 458        private async Task<bool> ReconcileManifest(PluginManifest manifest, string path)
 459        {
 460            try
 461            {
 4462                var metafile = Path.Combine(path, MetafileName);
 4463                if (!File.Exists(metafile))
 464                {
 1465                    _logger.LogInformation("No local manifest exists for plugin {Plugin}. Skipping manifest reconciliati
 1466                    return true;
 467                }
 468
 3469                using var metaStream = File.OpenRead(metafile);
 3470                var localManifest = await JsonSerializer.DeserializeAsync<PluginManifest>(metaStream, _jsonOptions).Conf
 3471                localManifest ??= new PluginManifest();
 472
 3473                if (!Equals(localManifest.Id, manifest.Id))
 474                {
 1475                    _logger.LogError("The manifest ID {LocalUUID} did not match the package info ID {PackageUUID}.", loc
 1476                    manifest.Status = PluginStatus.Malfunctioned;
 477                }
 478
 3479                if (localManifest.Version != manifest.Version)
 480                {
 481                    // Package information provides the version and is the source of truth. Pre-packages meta.json is as
 3482                    _logger.LogWarning("The version of the local manifest was {LocalVersion}, but {PackageVersion} was e
 483                }
 484
 485                // Explicitly mapping properties instead of using reflection is preferred here.
 3486                manifest.Category = string.IsNullOrEmpty(localManifest.Category) ? manifest.Category : localManifest.Cat
 3487                manifest.AutoUpdate = localManifest.AutoUpdate; // Preserve whatever is local. Package info does not hav
 3488                manifest.Changelog = string.IsNullOrEmpty(localManifest.Changelog) ? manifest.Changelog : localManifest.
 3489                manifest.Description = string.IsNullOrEmpty(localManifest.Description) ? manifest.Description : localMan
 3490                manifest.Name = string.IsNullOrEmpty(localManifest.Name) ? manifest.Name : localManifest.Name;
 3491                manifest.Overview = string.IsNullOrEmpty(localManifest.Overview) ? manifest.Overview : localManifest.Ove
 3492                manifest.Owner = string.IsNullOrEmpty(localManifest.Owner) ? manifest.Owner : localManifest.Owner;
 3493                manifest.TargetAbi = string.IsNullOrEmpty(localManifest.TargetAbi) ? manifest.TargetAbi : localManifest.
 3494                manifest.Timestamp = localManifest.Timestamp.Equals(default) ? manifest.Timestamp : localManifest.Timest
 3495                manifest.ImagePath = string.IsNullOrEmpty(localManifest.ImagePath) ? manifest.ImagePath : localManifest.
 3496                manifest.Assemblies = localManifest.Assemblies;
 497
 3498                return true;
 499            }
 0500            catch (Exception e)
 501            {
 0502                _logger.LogWarning(e, "Unable to reconcile plugin manifest due to an error. {Path}", path);
 0503                return false;
 504            }
 4505        }
 506
 507        /// <summary>
 508        /// Changes a plugin's load status.
 509        /// </summary>
 510        /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param>
 511        /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param>
 512        /// <returns>Success of the task.</returns>
 513        private bool ChangePluginState(LocalPlugin plugin, PluginStatus state)
 514        {
 9515            if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path))
 516            {
 517                // No need to save as the state hasn't changed.
 0518                return true;
 519            }
 520
 9521            plugin.Manifest.Status = state;
 9522            return SaveManifest(plugin.Manifest, plugin.Path);
 523        }
 524
 525        /// <summary>
 526        /// Finds the plugin record using the assembly.
 527        /// </summary>
 528        /// <param name="assembly">The <see cref="Assembly"/> being sought.</param>
 529        /// <returns>The matching record, or null if not found.</returns>
 530        private LocalPlugin? GetPluginByAssembly(Assembly assembly)
 531        {
 532            // Find which plugin it is by the path.
 168533            return _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location, StringComparer.Ordinal));
 534        }
 535
 536        /// <summary>
 537        /// Creates the instance safe.
 538        /// </summary>
 539        /// <param name="type">The type.</param>
 540        /// <returns>System.Object.</returns>
 541        private IPlugin? CreatePluginInstance(Type type)
 542        {
 543            // Find the record for this plugin.
 168544            var plugin = GetPluginByAssembly(type.Assembly);
 168545            if (plugin?.Manifest.Status < PluginStatus.Active)
 546            {
 0547                return null;
 548            }
 549
 550            try
 551            {
 168552                _logger.LogDebug("Creating instance of {Type}", type);
 553                // _appHost.ServiceProvider is already assigned when we create the plugins
 168554                var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider!, type);
 168555                if (plugin is null)
 556                {
 557                    // Create a dummy record for the providers.
 558                    // TODO: remove this code once all provided have been released as separate plugins.
 168559                    plugin = new LocalPlugin(
 168560                        instance.AssemblyFilePath,
 168561                        true,
 168562                        new PluginManifest
 168563                        {
 168564                            Id = instance.Id,
 168565                            Status = PluginStatus.Active,
 168566                            Name = instance.Name,
 168567                            Version = instance.Version.ToString(),
 168568                            ImageResourceName = (instance as IHasEmbeddedImage)?.ImageResourceName
 168569                        })
 168570                    {
 168571                        Instance = instance
 168572                    };
 573
 168574                    _plugins.Add(plugin);
 575
 168576                    plugin.Manifest.Status = PluginStatus.Active;
 577                }
 578                else
 579                {
 0580                    plugin.Instance = instance;
 0581                    var manifest = plugin.Manifest;
 0582                    var pluginStr = instance.Version.ToString();
 0583                    bool changed = false;
 0584                    if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)
 0585                        || !manifest.Id.Equals(instance.Id))
 586                    {
 587                        // If a plugin without a manifest failed to load due to an external issue (eg config),
 588                        // this updates the manifest to the actual plugin values.
 0589                        manifest.Version = pluginStr;
 0590                        manifest.Name = plugin.Instance.Name;
 0591                        manifest.Description = plugin.Instance.Description;
 0592                        manifest.Id = plugin.Instance.Id;
 0593                        changed = true;
 594                    }
 595
 0596                    changed = changed || manifest.Status != PluginStatus.Active;
 0597                    manifest.Status = PluginStatus.Active;
 598
 0599                    if (changed)
 600                    {
 0601                        SaveManifest(manifest, plugin.Path);
 602                    }
 603                }
 604
 168605                _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
 606
 168607                return instance;
 608            }
 609#pragma warning disable CA1031 // Do not catch general exception types
 0610            catch (Exception ex)
 611#pragma warning restore CA1031 // Do not catch general exception types
 612            {
 0613                _logger.LogError(ex, "Error creating {Type}", type.FullName);
 0614                if (plugin is not null)
 615                {
 0616                    if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
 617                    {
 0618                        _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
 0619                        return null;
 620                    }
 621                }
 622
 0623                _logger.LogDebug("Unable to auto-disable.");
 0624                return null;
 625            }
 168626        }
 627
 628        private void UpdatePluginSupersededStatus(LocalPlugin plugin)
 629        {
 0630            if (plugin.Manifest.Status != PluginStatus.Superseded)
 631            {
 0632                return;
 633            }
 634
 0635            var predecessor = _plugins.OrderByDescending(p => p.Version)
 0636                .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version);
 0637            if (predecessor is not null)
 638            {
 0639                return;
 640            }
 641
 0642            plugin.Manifest.Status = PluginStatus.Active;
 0643        }
 644
 645        /// <summary>
 646        /// Attempts to delete a plugin.
 647        /// </summary>
 648        /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
 649        /// <returns>True if successful.</returns>
 650        private bool DeletePlugin(LocalPlugin plugin)
 651        {
 652            // Attempt a cleanup of old folders.
 653            try
 654            {
 0655                Directory.Delete(plugin.Path, true);
 0656                _logger.LogDebug("Deleted {Path}", plugin.Path);
 0657            }
 658#pragma warning disable CA1031 // Do not catch general exception types
 0659            catch
 660#pragma warning restore CA1031 // Do not catch general exception types
 661            {
 0662                return false;
 663            }
 664
 0665            return _plugins.Remove(plugin);
 0666        }
 667
 668        internal LocalPlugin LoadManifest(string dir)
 669        {
 670            Version? version;
 16671            PluginManifest? manifest = null;
 16672            var metafile = Path.Combine(dir, MetafileName);
 16673            if (File.Exists(metafile))
 674            {
 675                // Only path where this stays null is when File.ReadAllBytes throws an IOException
 16676                byte[] data = null!;
 677                try
 678                {
 16679                    data = File.ReadAllBytes(metafile);
 16680                    manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
 16681                }
 0682                catch (IOException ex)
 683                {
 0684                    _logger.LogError(ex, "Error reading file {Path}.", dir);
 0685                }
 0686                catch (JsonException ex)
 687                {
 0688                    _logger.LogError(ex, "Error deserializing {Json}.", Encoding.UTF8.GetString(data));
 0689                }
 690
 16691                if (manifest is not null)
 692                {
 16693                    if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
 694                    {
 16695                        targetAbi = _minimumVersion;
 696                    }
 697
 16698                    if (!Version.TryParse(manifest.Version, out version))
 699                    {
 12700                        manifest.Version = _minimumVersion.ToString();
 701                    }
 702
 16703                    return new LocalPlugin(dir, _appVersion >= targetAbi, manifest);
 704                }
 705            }
 706
 707            // No metafile, so lets see if the folder is versioned.
 708            // TODO: Phase this support out in future versions.
 0709            metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
 0710            int versionIndex = dir.LastIndexOf('_');
 0711            if (versionIndex != -1)
 712            {
 713                // Get the version number from the filename if possible.
 0714                metafile = Path.GetFileName(dir[..versionIndex]);
 0715                version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersi
 716            }
 717            else
 718            {
 719                // Un-versioned folder - Add it under the path name and version it suitable for this instance.
 0720                version = _appVersion;
 721            }
 722
 723            // Auto-create a plugin manifest, so we can disable it, if it fails to load.
 0724            manifest = new PluginManifest
 0725            {
 0726                Status = PluginStatus.Active,
 0727                Name = metafile,
 0728                AutoUpdate = false,
 0729                Id = metafile.GetMD5(),
 0730                TargetAbi = _appVersion.ToString(),
 0731                Version = version.ToString()
 0732            };
 733
 0734            return new LocalPlugin(dir, true, manifest);
 735        }
 736
 737        /// <summary>
 738        /// Gets the list of local plugins.
 739        /// </summary>
 740        /// <returns>Enumerable of local plugins.</returns>
 741        private IEnumerable<LocalPlugin> DiscoverPlugins()
 742        {
 15743            var versions = new List<LocalPlugin>();
 744
 15745            if (!Directory.Exists(_pluginsPath))
 746            {
 747                // Plugin path doesn't exist, don't try to enumerate sub-folders.
 0748                return Enumerable.Empty<LocalPlugin>();
 749            }
 750
 15751            var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
 60752            foreach (var dir in directories)
 753            {
 15754                versions.Add(LoadManifest(dir));
 755            }
 756
 15757            string lastName = string.Empty;
 15758            versions.Sort(LocalPlugin.Compare);
 759            // Traverse backwards through the list.
 760            // The first item will be the latest version.
 60761            for (int x = versions.Count - 1; x >= 0; x--)
 762            {
 15763                var entry = versions[x];
 15764                if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
 765                {
 12766                    if (!TryGetPluginDlls(entry, out var allowedDlls))
 767                    {
 9768                        _logger.LogError("One or more assembly paths was invalid. Marking plugin {Plugin} as \"Malfuncti
 9769                        ChangePluginState(entry, PluginStatus.Malfunctioned);
 9770                        continue;
 771                    }
 772
 3773                    entry.DllFiles = allowedDlls;
 774
 3775                    if (entry.IsEnabledAndSupported)
 776                    {
 3777                        lastName = entry.Name;
 3778                        continue;
 779                    }
 780                }
 781
 3782                if (string.IsNullOrEmpty(lastName))
 783                {
 784                    continue;
 785                }
 786
 0787                var cleaned = false;
 0788                var path = entry.Path;
 789                // Attempt a cleanup of old folders.
 790                try
 791                {
 0792                    _logger.LogDebug("Deleting {Path}", path);
 0793                    Directory.Delete(path, true);
 0794                    cleaned = true;
 0795                }
 796#pragma warning disable CA1031 // Do not catch general exception types
 0797                catch (Exception e)
 798#pragma warning restore CA1031 // Do not catch general exception types
 799                {
 0800                    _logger.LogWarning(e, "Unable to delete {Path}", path);
 0801                }
 802
 0803                if (cleaned)
 804                {
 0805                    versions.RemoveAt(x);
 806                }
 807                else
 808                {
 0809                    ChangePluginState(entry, PluginStatus.Deleted);
 810                }
 811            }
 812
 813            // Only want plugin folders which have files.
 15814            return versions.Where(p => p.DllFiles.Count != 0);
 815        }
 816
 817        /// <summary>
 818        /// Attempts to retrieve valid DLLs from the plugin path. This method will consider the assembly whitelist
 819        /// from the manifest.
 820        /// </summary>
 821        /// <remarks>
 822        /// Loading DLLs from externally supplied paths introduces a path traversal risk. This method
 823        /// uses a safelisting tactic of considering DLLs from the plugin directory and only using
 824        /// the plugin's canonicalized assembly whitelist for comparison. See
 825        /// <see href="https://owasp.org/www-community/attacks/Path_Traversal"/> for more details.
 826        /// </remarks>
 827        /// <param name="plugin">The plugin.</param>
 828        /// <param name="whitelistedDlls">The whitelisted DLLs. If the method returns <see langword="false"/>, this will
 829        /// <returns>
 830        /// <see langword="true"/> if all assemblies listed in the manifest were available in the plugin directory.
 831        /// <see langword="false"/> if any assemblies were invalid or missing from the plugin directory.
 832        /// </returns>
 833        /// <exception cref="ArgumentNullException">If the <see cref="LocalPlugin"/> is null.</exception>
 834        private bool TryGetPluginDlls(LocalPlugin plugin, out IReadOnlyList<string> whitelistedDlls)
 835        {
 12836            ArgumentNullException.ThrowIfNull(plugin);
 837
 12838            IReadOnlyList<string> pluginDlls = Directory.GetFiles(plugin.Path, "*.dll", SearchOption.AllDirectories);
 839
 12840            whitelistedDlls = Array.Empty<string>();
 12841            if (pluginDlls.Count > 0 && plugin.Manifest.Assemblies.Count > 0)
 842            {
 12843                _logger.LogInformation("Registering whitelisted assemblies for plugin \"{Plugin}\"...", plugin.Name);
 844
 12845                var canonicalizedPaths = new List<string>();
 45846                foreach (var path in plugin.Manifest.Assemblies)
 847                {
 12848                    var canonicalized = Path.Combine(plugin.Path, path).Canonicalize();
 849
 850                    // Ensure we stay in the plugin directory.
 12851                    if (!canonicalized.StartsWith(plugin.Path.NormalizePath(), StringComparison.Ordinal))
 852                    {
 3853                        _logger.LogError("Assembly path {Path} is not inside the plugin directory.", path);
 3854                        return false;
 855                    }
 856
 9857                    canonicalizedPaths.Add(canonicalized);
 858                }
 859
 9860                var intersected = pluginDlls.Intersect(canonicalizedPaths).ToList();
 861
 9862                if (intersected.Count != canonicalizedPaths.Count)
 863                {
 6864                    _logger.LogError("Plugin {Plugin} contained assembly paths that were not found in the directory.", p
 6865                    return false;
 866                }
 867
 3868                whitelistedDlls = intersected;
 869            }
 870            else
 871            {
 872                // No whitelist, default to loading all DLLs in plugin directory.
 0873                whitelistedDlls = pluginDlls;
 874            }
 875
 3876            return true;
 3877        }
 878
 879        /// <summary>
 880        /// Changes the status of the other versions of the plugin to "Superseded".
 881        /// </summary>
 882        /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param>
 883        private void ProcessAlternative(LocalPlugin plugin)
 884        {
 885            // Detect whether there is another version of this plugin that needs disabling.
 0886            var previousVersion = _plugins.OrderByDescending(p => p.Version)
 0887                .FirstOrDefault(
 0888                    p => p.Id.Equals(plugin.Id)
 0889                    && p.IsEnabledAndSupported
 0890                    && p.Version != plugin.Version);
 891
 0892            if (previousVersion is null)
 893            {
 894                // This value is memory only - so that the web will show restart required.
 0895                plugin.Manifest.Status = PluginStatus.Restart;
 0896                plugin.Manifest.AutoUpdate = false;
 0897                return;
 898            }
 899
 0900            if (plugin.Manifest.Status == PluginStatus.Active && !ChangePluginState(previousVersion, PluginStatus.Supers
 901            {
 0902                _logger.LogError("Unable to enable version {Version} of {Name}", previousVersion.Version, previousVersio
 903            }
 0904            else if (plugin.Manifest.Status == PluginStatus.Superseded && !ChangePluginState(previousVersion, PluginStat
 905            {
 0906                _logger.LogError("Unable to supercede version {Version} of {Name}", previousVersion.Version, previousVer
 907            }
 908
 909            // This value is memory only - so that the web will show restart required.
 0910            plugin.Manifest.Status = PluginStatus.Restart;
 0911            plugin.Manifest.AutoUpdate = false;
 0912        }
 913    }
 914}