InstallationManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. #nullable enable
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Net.Http.Json;
  9. using System.Security.Cryptography;
  10. using System.Text.Json;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using Jellyfin.Data.Events;
  14. using MediaBrowser.Common.Configuration;
  15. using MediaBrowser.Common.Json;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Common.Plugins;
  18. using MediaBrowser.Common.Updates;
  19. using MediaBrowser.Controller;
  20. using MediaBrowser.Controller.Configuration;
  21. using MediaBrowser.Controller.Events;
  22. using MediaBrowser.Controller.Events.Updates;
  23. using MediaBrowser.Model.IO;
  24. using MediaBrowser.Model.Plugins;
  25. using MediaBrowser.Model.Updates;
  26. using Microsoft.Extensions.Logging;
  27. namespace Emby.Server.Implementations.Updates
  28. {
  29. /// <summary>
  30. /// Manages all install, uninstall, and update operations for the system and individual plugins.
  31. /// </summary>
  32. public class InstallationManager : IInstallationManager
  33. {
  34. /// <summary>
  35. /// The logger.
  36. /// </summary>
  37. private readonly ILogger<InstallationManager> _logger;
  38. private readonly IApplicationPaths _appPaths;
  39. private readonly IEventManager _eventManager;
  40. private readonly IHttpClientFactory _httpClientFactory;
  41. private readonly IServerConfigurationManager _config;
  42. private readonly JsonSerializerOptions _jsonSerializerOptions;
  43. private readonly IPluginManager _pluginManager;
  44. /// <summary>
  45. /// Gets the application host.
  46. /// </summary>
  47. /// <value>The application host.</value>
  48. private readonly IServerApplicationHost _applicationHost;
  49. private readonly IZipClient _zipClient;
  50. private readonly object _currentInstallationsLock = new object();
  51. /// <summary>
  52. /// The current installations.
  53. /// </summary>
  54. private readonly List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations;
  55. /// <summary>
  56. /// The completed installations.
  57. /// </summary>
  58. private readonly ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
  59. /// <summary>
  60. /// Initializes a new instance of the <see cref="InstallationManager"/> class.
  61. /// </summary>
  62. /// <param name="logger">The <see cref="ILogger{InstallationManager}"/>.</param>
  63. /// <param name="appHost">The <see cref="IServerApplicationHost"/>.</param>
  64. /// <param name="appPaths">The <see cref="IApplicationPaths"/>.</param>
  65. /// <param name="eventManager">The <see cref="IEventManager"/>.</param>
  66. /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/>.</param>
  67. /// <param name="config">The <see cref="IServerConfigurationManager"/>.</param>
  68. /// <param name="zipClient">The <see cref="IZipClient"/>.</param>
  69. /// <param name="pluginManager">The <see cref="IPluginManager"/>.</param>
  70. public InstallationManager(
  71. ILogger<InstallationManager> logger,
  72. IServerApplicationHost appHost,
  73. IApplicationPaths appPaths,
  74. IEventManager eventManager,
  75. IHttpClientFactory httpClientFactory,
  76. IServerConfigurationManager config,
  77. IZipClient zipClient,
  78. IPluginManager pluginManager)
  79. {
  80. _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
  81. _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  82. _logger = logger;
  83. _applicationHost = appHost;
  84. _appPaths = appPaths;
  85. _eventManager = eventManager;
  86. _httpClientFactory = httpClientFactory;
  87. _config = config;
  88. _zipClient = zipClient;
  89. _jsonSerializerOptions = JsonDefaults.GetOptions();
  90. _pluginManager = pluginManager;
  91. }
  92. /// <inheritdoc />
  93. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  94. /// <inheritdoc />
  95. public async Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, bool filterIncompatible, CancellationToken cancellationToken = default)
  96. {
  97. try
  98. {
  99. List<PackageInfo>? packages = await _httpClientFactory.CreateClient(NamedClient.Default)
  100. .GetFromJsonAsync<List<PackageInfo>>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false);
  101. if (packages == null)
  102. {
  103. return Array.Empty<PackageInfo>();
  104. }
  105. var minimumVersion = new Version(0, 0, 0, 1);
  106. // Store the repository and repository url with each version, as they may be spread apart.
  107. foreach (var entry in packages)
  108. {
  109. for (int a = entry.Versions.Count - 1; a >= 0; a--)
  110. {
  111. var ver = entry.Versions[a];
  112. ver.RepositoryName = manifestName;
  113. ver.RepositoryUrl = manifest;
  114. if (!filterIncompatible)
  115. {
  116. continue;
  117. }
  118. if (!Version.TryParse(ver.TargetAbi, out var targetAbi))
  119. {
  120. targetAbi = minimumVersion;
  121. }
  122. // Only show plugins that are greater than or equal to targetAbi.
  123. if (_applicationHost.ApplicationVersion >= targetAbi)
  124. {
  125. continue;
  126. }
  127. // Not compatible with this version so remove it.
  128. entry.Versions.Remove(ver);
  129. }
  130. }
  131. return packages;
  132. }
  133. catch (IOException ex)
  134. {
  135. _logger.LogError(ex, "Cannot locate the plugin manifest {Manifest}", manifest);
  136. return Array.Empty<PackageInfo>();
  137. }
  138. catch (JsonException ex)
  139. {
  140. _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
  141. return Array.Empty<PackageInfo>();
  142. }
  143. catch (UriFormatException ex)
  144. {
  145. _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
  146. return Array.Empty<PackageInfo>();
  147. }
  148. catch (HttpRequestException ex)
  149. {
  150. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  151. return Array.Empty<PackageInfo>();
  152. }
  153. }
  154. /// <inheritdoc />
  155. public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
  156. {
  157. var result = new List<PackageInfo>();
  158. foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
  159. {
  160. if (repository.Enabled && repository.Url != null)
  161. {
  162. // Where repositories have the same content, the details from the first is taken.
  163. foreach (var package in await GetPackages(repository.Name ?? "Unnamed Repo", repository.Url, true, cancellationToken).ConfigureAwait(true))
  164. {
  165. if (!Guid.TryParse(package.Id, out var packageGuid))
  166. {
  167. // Package doesn't have a valid GUID, skip.
  168. continue;
  169. }
  170. var existing = FilterPackages(result, package.Name, packageGuid).FirstOrDefault();
  171. // Remove invalid versions from the valid package.
  172. for (var i = package.Versions.Count - 1; i >= 0; i--)
  173. {
  174. var version = package.Versions[i];
  175. var plugin = _pluginManager.GetPlugin(packageGuid, version.VersionNumber);
  176. if (plugin != null)
  177. {
  178. await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path, plugin.Manifest.Status).ConfigureAwait(false);
  179. }
  180. // Remove versions with a target ABI greater then the current application version.
  181. if (Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi)
  182. {
  183. package.Versions.RemoveAt(i);
  184. }
  185. }
  186. // Don't add a package that doesn't have any compatible versions.
  187. if (package.Versions.Count == 0)
  188. {
  189. continue;
  190. }
  191. if (existing != null)
  192. {
  193. // Assumption is both lists are ordered, so slot these into the correct place.
  194. MergeSortedList(existing.Versions, package.Versions);
  195. }
  196. else
  197. {
  198. result.Add(package);
  199. }
  200. }
  201. }
  202. }
  203. return result;
  204. }
  205. /// <inheritdoc />
  206. public IEnumerable<PackageInfo> FilterPackages(
  207. IEnumerable<PackageInfo> availablePackages,
  208. string? name = null,
  209. Guid? id = default,
  210. Version? specificVersion = null)
  211. {
  212. if (name != null)
  213. {
  214. availablePackages = availablePackages.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  215. }
  216. if (id != Guid.Empty)
  217. {
  218. availablePackages = availablePackages.Where(x => Guid.Parse(x.Id) == id);
  219. }
  220. if (specificVersion != null)
  221. {
  222. availablePackages = availablePackages.Where(x => x.Versions.Any(y => y.VersionNumber.Equals(specificVersion)));
  223. }
  224. return availablePackages;
  225. }
  226. /// <inheritdoc />
  227. public IEnumerable<InstallationInfo> GetCompatibleVersions(
  228. IEnumerable<PackageInfo> availablePackages,
  229. string? name = null,
  230. Guid? id = default,
  231. Version? minVersion = null,
  232. Version? specificVersion = null)
  233. {
  234. var package = FilterPackages(availablePackages, name, id, specificVersion).FirstOrDefault();
  235. // Package not found in repository
  236. if (package == null)
  237. {
  238. yield break;
  239. }
  240. var appVer = _applicationHost.ApplicationVersion;
  241. var availableVersions = package.Versions
  242. .Where(x => string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer);
  243. if (specificVersion != null)
  244. {
  245. availableVersions = availableVersions.Where(x => x.VersionNumber.Equals(specificVersion));
  246. }
  247. else if (minVersion != null)
  248. {
  249. availableVersions = availableVersions.Where(x => x.VersionNumber >= minVersion);
  250. }
  251. foreach (var v in availableVersions.OrderByDescending(x => x.VersionNumber))
  252. {
  253. yield return new InstallationInfo
  254. {
  255. Changelog = v.Changelog,
  256. Id = new Guid(package.Id),
  257. Name = package.Name,
  258. Version = v.VersionNumber,
  259. SourceUrl = v.SourceUrl,
  260. Checksum = v.Checksum,
  261. PackageInfo = package
  262. };
  263. }
  264. }
  265. /// <inheritdoc />
  266. public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  267. {
  268. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  269. return GetAvailablePluginUpdates(catalog);
  270. }
  271. /// <inheritdoc />
  272. public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
  273. {
  274. if (package == null)
  275. {
  276. throw new ArgumentNullException(nameof(package));
  277. }
  278. var innerCancellationTokenSource = new CancellationTokenSource();
  279. var tuple = (package, innerCancellationTokenSource);
  280. // Add it to the in-progress list
  281. lock (_currentInstallationsLock)
  282. {
  283. _currentInstallations.Add(tuple);
  284. }
  285. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token);
  286. var linkedToken = linkedTokenSource.Token;
  287. await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false);
  288. try
  289. {
  290. var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  291. lock (_currentInstallationsLock)
  292. {
  293. _currentInstallations.Remove(tuple);
  294. }
  295. _completedInstallationsInternal.Add(package);
  296. await _eventManager.PublishAsync(isUpdate
  297. ? (GenericEventArgs<InstallationInfo>)new PluginUpdatedEventArgs(package)
  298. : new PluginInstalledEventArgs(package)).ConfigureAwait(false);
  299. _applicationHost.NotifyPendingRestart();
  300. }
  301. catch (OperationCanceledException)
  302. {
  303. lock (_currentInstallationsLock)
  304. {
  305. _currentInstallations.Remove(tuple);
  306. }
  307. _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
  308. await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false);
  309. throw;
  310. }
  311. catch (Exception ex)
  312. {
  313. _logger.LogError(ex, "Package installation failed");
  314. lock (_currentInstallationsLock)
  315. {
  316. _currentInstallations.Remove(tuple);
  317. }
  318. await _eventManager.PublishAsync(new InstallationFailedEventArgs
  319. {
  320. InstallationInfo = package,
  321. Exception = ex
  322. }).ConfigureAwait(false);
  323. throw;
  324. }
  325. finally
  326. {
  327. // Dispose the progress object and remove the installation from the in-progress list
  328. tuple.innerCancellationTokenSource.Dispose();
  329. }
  330. }
  331. /// <summary>
  332. /// Uninstalls a plugin.
  333. /// </summary>
  334. /// <param name="plugin">The <see cref="LocalPlugin"/> to uninstall.</param>
  335. public void UninstallPlugin(LocalPlugin plugin)
  336. {
  337. if (plugin == null)
  338. {
  339. return;
  340. }
  341. if (plugin.Instance?.CanUninstall == false)
  342. {
  343. _logger.LogWarning("Attempt to delete non removable plugin {PluginName}, ignoring request", plugin.Name);
  344. return;
  345. }
  346. plugin.Instance?.OnUninstalling();
  347. // Remove it the quick way for now
  348. _pluginManager.RemovePlugin(plugin);
  349. _eventManager.Publish(new PluginUninstalledEventArgs(plugin.GetPluginInfo()));
  350. _applicationHost.NotifyPendingRestart();
  351. }
  352. /// <inheritdoc/>
  353. public bool CancelInstallation(Guid id)
  354. {
  355. lock (_currentInstallationsLock)
  356. {
  357. var install = _currentInstallations.Find(x => x.info.Id == id);
  358. if (install == default((InstallationInfo, CancellationTokenSource)))
  359. {
  360. return false;
  361. }
  362. install.token.Cancel();
  363. _currentInstallations.Remove(install);
  364. return true;
  365. }
  366. }
  367. /// <inheritdoc />
  368. public void Dispose()
  369. {
  370. Dispose(true);
  371. GC.SuppressFinalize(this);
  372. }
  373. /// <summary>
  374. /// Releases unmanaged and optionally managed resources.
  375. /// </summary>
  376. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  377. protected virtual void Dispose(bool dispose)
  378. {
  379. if (dispose)
  380. {
  381. lock (_currentInstallationsLock)
  382. {
  383. foreach (var (info, token) in _currentInstallations)
  384. {
  385. token.Dispose();
  386. }
  387. _currentInstallations.Clear();
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// Merges two sorted lists.
  393. /// </summary>
  394. /// <param name="source">The source <see cref="IList{VersionInfo}"/> instance to merge.</param>
  395. /// <param name="dest">The destination <see cref="IList{VersionInfo}"/> instance to merge with.</param>
  396. private static void MergeSortedList(IList<VersionInfo> source, IList<VersionInfo> dest)
  397. {
  398. int sLength = source.Count - 1;
  399. int dLength = dest.Count;
  400. int s = 0, d = 0;
  401. var sourceVersion = source[0].VersionNumber;
  402. var destVersion = dest[0].VersionNumber;
  403. while (d < dLength)
  404. {
  405. if (sourceVersion.CompareTo(destVersion) >= 0)
  406. {
  407. if (s < sLength)
  408. {
  409. sourceVersion = source[++s].VersionNumber;
  410. }
  411. else
  412. {
  413. // Append all of destination to the end of source.
  414. while (d < dLength)
  415. {
  416. source.Add(dest[d++]);
  417. }
  418. break;
  419. }
  420. }
  421. else
  422. {
  423. source.Insert(s++, dest[d++]);
  424. if (d >= dLength)
  425. {
  426. break;
  427. }
  428. sLength++;
  429. destVersion = dest[d].VersionNumber;
  430. }
  431. }
  432. }
  433. private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  434. {
  435. var plugins = _pluginManager.Plugins;
  436. foreach (var plugin in plugins)
  437. {
  438. // Don't auto update when plugin marked not to, or when it's disabled.
  439. if (plugin.Manifest?.AutoUpdate == false || plugin.Manifest?.Status == PluginStatus.Disabled)
  440. {
  441. continue;
  442. }
  443. var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
  444. var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
  445. if (version != null && CompletedInstallations.All(x => x.Id != version.Id))
  446. {
  447. yield return version;
  448. }
  449. }
  450. }
  451. private async Task PerformPackageInstallation(InstallationInfo package, PluginStatus status, CancellationToken cancellationToken)
  452. {
  453. var extension = Path.GetExtension(package.SourceUrl);
  454. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  455. {
  456. _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
  457. return;
  458. }
  459. // Always override the passed-in target (which is a file) and figure it out again
  460. string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
  461. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  462. .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false);
  463. response.EnsureSuccessStatusCode();
  464. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  465. // CA5351: Do Not Use Broken Cryptographic Algorithms
  466. #pragma warning disable CA5351
  467. using var md5 = MD5.Create();
  468. cancellationToken.ThrowIfCancellationRequested();
  469. var hash = Convert.ToHexString(md5.ComputeHash(stream));
  470. if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
  471. {
  472. _logger.LogError(
  473. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  474. package.Name,
  475. package.Checksum,
  476. hash);
  477. throw new InvalidDataException("The checksum of the received data doesn't match.");
  478. }
  479. // Version folder as they cannot be overwritten in Windows.
  480. targetDir += "_" + package.Version;
  481. if (Directory.Exists(targetDir))
  482. {
  483. try
  484. {
  485. Directory.Delete(targetDir, true);
  486. }
  487. #pragma warning disable CA1031 // Do not catch general exception types
  488. catch
  489. #pragma warning restore CA1031 // Do not catch general exception types
  490. {
  491. // Ignore any exceptions.
  492. }
  493. }
  494. stream.Position = 0;
  495. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  496. await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir, status).ConfigureAwait(false);
  497. _pluginManager.ImportPluginFrom(targetDir);
  498. }
  499. private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
  500. {
  501. LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Id) && p.Version.Equals(package.Version))
  502. ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version));
  503. await PerformPackageInstallation(package, plugin?.Manifest.Status ?? PluginStatus.Active, cancellationToken).ConfigureAwait(false);
  504. _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version);
  505. return plugin != null;
  506. }
  507. }
  508. }