InstallationManager.cs 23 KB

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