InstallationManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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.GetCamelCaseOptions();
  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;
  99. 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. if (!Version.TryParse(ver.MaxAbi, out var maxAbi))
  123. {
  124. maxAbi = _applicationHost.ApplicationVersion;
  125. }
  126. // Only show plugins that fall between targetAbi and maxAbi
  127. if (_applicationHost.ApplicationVersion >= targetAbi && _applicationHost.ApplicationVersion <= maxAbi)
  128. {
  129. continue;
  130. }
  131. // Not compatible with this version so remove it.
  132. entry.Versions.Remove(ver);
  133. }
  134. }
  135. return packages;
  136. }
  137. catch (IOException ex)
  138. {
  139. _logger.LogError(ex, "Cannot locate the plugin manifest {Manifest}", manifest);
  140. return Array.Empty<PackageInfo>();
  141. }
  142. catch (JsonException ex)
  143. {
  144. _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
  145. return Array.Empty<PackageInfo>();
  146. }
  147. catch (UriFormatException ex)
  148. {
  149. _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
  150. return Array.Empty<PackageInfo>();
  151. }
  152. catch (HttpRequestException ex)
  153. {
  154. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  155. return Array.Empty<PackageInfo>();
  156. }
  157. }
  158. /// <inheritdoc />
  159. public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
  160. {
  161. var result = new List<PackageInfo>();
  162. foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
  163. {
  164. if (repository.Enabled && repository.Url != null)
  165. {
  166. // Where repositories have the same content, the details from the first is taken.
  167. foreach (var package in await GetPackages(repository.Name ?? "Unnamed Repo", repository.Url, true, cancellationToken).ConfigureAwait(true))
  168. {
  169. if (!Guid.TryParse(package.Guid, out var packageGuid))
  170. {
  171. // Package doesn't have a valid GUID, skip.
  172. continue;
  173. }
  174. var existing = FilterPackages(result, package.Name, packageGuid).FirstOrDefault();
  175. // Remove invalid versions from the valid package.
  176. for (var i = package.Versions.Count - 1; i >= 0; i--)
  177. {
  178. var version = package.Versions[i];
  179. // Update the manifests, if anything changes.
  180. if (_pluginManager.TryGetPlugin(packageGuid, version.VersionNumber, out LocalPlugin? plugin))
  181. {
  182. bool noChange = string.Equals(plugin!.Manifest.MaxAbi, version.MaxAbi, StringComparison.Ordinal)
  183. || string.Equals(plugin.Manifest.TargetAbi, version.TargetAbi, StringComparison.Ordinal);
  184. if (!noChange)
  185. {
  186. plugin.Manifest.MaxAbi = version.MaxAbi ?? string.Empty;
  187. plugin.Manifest.TargetAbi = version.TargetAbi ?? string.Empty;
  188. _pluginManager.SaveManifest(plugin.Manifest, plugin.Path);
  189. }
  190. }
  191. // Remove versions with a target abi that is greater then the current application version.
  192. if ((Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi)
  193. || (Version.TryParse(version.MaxAbi, out var maxAbi) && _applicationHost.ApplicationVersion > maxAbi))
  194. {
  195. package.Versions.RemoveAt(i);
  196. }
  197. }
  198. // Don't add a package that doesn't have any compatible versions.
  199. if (package.Versions.Count == 0)
  200. {
  201. continue;
  202. }
  203. if (existing != null)
  204. {
  205. // Assumption is both lists are ordered, so slot these into the correct place.
  206. MergeSortedList(existing.Versions, package.Versions);
  207. }
  208. else
  209. {
  210. result.Add(package);
  211. }
  212. }
  213. }
  214. }
  215. return result;
  216. }
  217. /// <inheritdoc />
  218. public IEnumerable<PackageInfo> FilterPackages(
  219. IEnumerable<PackageInfo> availablePackages,
  220. string? name = null,
  221. Guid? guid = default,
  222. Version? specificVersion = null)
  223. {
  224. if (name != null)
  225. {
  226. availablePackages = availablePackages.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  227. }
  228. if (guid != Guid.Empty)
  229. {
  230. availablePackages = availablePackages.Where(x => Guid.Parse(x.Guid) == guid);
  231. }
  232. if (specificVersion != null)
  233. {
  234. availablePackages = availablePackages.Where(x => x.Versions.Any(y => y.VersionNumber.Equals(specificVersion)));
  235. }
  236. return availablePackages;
  237. }
  238. /// <inheritdoc />
  239. public IEnumerable<InstallationInfo> GetCompatibleVersions(
  240. IEnumerable<PackageInfo> availablePackages,
  241. string? name = null,
  242. Guid? guid = default,
  243. Version? minVersion = null,
  244. Version? specificVersion = null)
  245. {
  246. var package = FilterPackages(availablePackages, name, guid, specificVersion).FirstOrDefault();
  247. // Package not found in repository
  248. if (package == null)
  249. {
  250. yield break;
  251. }
  252. var appVer = _applicationHost.ApplicationVersion;
  253. var availableVersions = package.Versions
  254. .Where(x => (string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer)
  255. && (string.IsNullOrEmpty(x.MaxAbi) || Version.Parse(x.MaxAbi) >= appVer));
  256. if (specificVersion != null)
  257. {
  258. availableVersions = availableVersions.Where(x => x.VersionNumber.Equals(specificVersion));
  259. }
  260. else if (minVersion != null)
  261. {
  262. availableVersions = availableVersions.Where(x => x.VersionNumber >= minVersion);
  263. }
  264. foreach (var v in availableVersions.OrderByDescending(x => x.VersionNumber))
  265. {
  266. yield return new InstallationInfo
  267. {
  268. Changelog = v.Changelog,
  269. Guid = new Guid(package.Guid),
  270. Name = package.Name,
  271. Version = v.VersionNumber,
  272. SourceUrl = v.SourceUrl,
  273. Checksum = v.Checksum
  274. };
  275. }
  276. }
  277. /// <inheritdoc />
  278. public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  279. {
  280. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  281. return GetAvailablePluginUpdates(catalog);
  282. }
  283. /// <inheritdoc />
  284. public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
  285. {
  286. if (package == null)
  287. {
  288. throw new ArgumentNullException(nameof(package));
  289. }
  290. var innerCancellationTokenSource = new CancellationTokenSource();
  291. var tuple = (package, innerCancellationTokenSource);
  292. // Add it to the in-progress list
  293. lock (_currentInstallationsLock)
  294. {
  295. _currentInstallations.Add(tuple);
  296. }
  297. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token);
  298. var linkedToken = linkedTokenSource.Token;
  299. await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false);
  300. try
  301. {
  302. var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  303. lock (_currentInstallationsLock)
  304. {
  305. _currentInstallations.Remove(tuple);
  306. }
  307. _completedInstallationsInternal.Add(package);
  308. await _eventManager.PublishAsync(isUpdate
  309. ? (GenericEventArgs<InstallationInfo>)new PluginUpdatedEventArgs(package)
  310. : new PluginInstalledEventArgs(package)).ConfigureAwait(false);
  311. _applicationHost.NotifyPendingRestart();
  312. }
  313. catch (OperationCanceledException)
  314. {
  315. lock (_currentInstallationsLock)
  316. {
  317. _currentInstallations.Remove(tuple);
  318. }
  319. _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
  320. await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false);
  321. throw;
  322. }
  323. catch (Exception ex)
  324. {
  325. _logger.LogError(ex, "Package installation failed");
  326. lock (_currentInstallationsLock)
  327. {
  328. _currentInstallations.Remove(tuple);
  329. }
  330. await _eventManager.PublishAsync(new InstallationFailedEventArgs
  331. {
  332. InstallationInfo = package,
  333. Exception = ex
  334. }).ConfigureAwait(false);
  335. throw;
  336. }
  337. finally
  338. {
  339. // Dispose the progress object and remove the installation from the in-progress list
  340. tuple.innerCancellationTokenSource.Dispose();
  341. }
  342. }
  343. /// <summary>
  344. /// Uninstalls a plugin.
  345. /// </summary>
  346. /// <param name="plugin">The <see cref="LocalPlugin"/> to uninstall.</param>
  347. public void UninstallPlugin(LocalPlugin plugin)
  348. {
  349. if (plugin == null)
  350. {
  351. return;
  352. }
  353. if (plugin.Instance?.CanUninstall == false)
  354. {
  355. _logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name);
  356. return;
  357. }
  358. plugin.Instance?.OnUninstalling();
  359. // Remove it the quick way for now
  360. _pluginManager.RemovePlugin(plugin);
  361. _eventManager.Publish(new PluginUninstalledEventArgs(plugin.GetPluginInfo()));
  362. _applicationHost.NotifyPendingRestart();
  363. }
  364. /// <inheritdoc/>
  365. public bool CancelInstallation(Guid id)
  366. {
  367. lock (_currentInstallationsLock)
  368. {
  369. var install = _currentInstallations.Find(x => x.info.Guid == id);
  370. if (install == default((InstallationInfo, CancellationTokenSource)))
  371. {
  372. return false;
  373. }
  374. install.token.Cancel();
  375. _currentInstallations.Remove(install);
  376. return true;
  377. }
  378. }
  379. /// <inheritdoc />
  380. public void Dispose()
  381. {
  382. Dispose(true);
  383. GC.SuppressFinalize(this);
  384. }
  385. /// <summary>
  386. /// Releases unmanaged and optionally managed resources.
  387. /// </summary>
  388. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  389. protected virtual void Dispose(bool dispose)
  390. {
  391. if (dispose)
  392. {
  393. lock (_currentInstallationsLock)
  394. {
  395. foreach (var (info, token) in _currentInstallations)
  396. {
  397. token.Dispose();
  398. }
  399. _currentInstallations.Clear();
  400. }
  401. }
  402. }
  403. /// <summary>
  404. /// Merges two sorted lists.
  405. /// </summary>
  406. /// <param name="source">The source <see cref="IList{VersionInfo}"/> instance to merge.</param>
  407. /// <param name="dest">The destination <see cref="IList{VersionInfo}"/> instance to merge with.</param>
  408. private static void MergeSortedList(IList<VersionInfo> source, IList<VersionInfo> dest)
  409. {
  410. int sLength = source.Count - 1;
  411. int dLength = dest.Count;
  412. int s = 0, d = 0;
  413. var sourceVersion = source[0].VersionNumber;
  414. var destVersion = dest[0].VersionNumber;
  415. while (d < dLength)
  416. {
  417. if (sourceVersion.CompareTo(destVersion) >= 0)
  418. {
  419. if (s < sLength)
  420. {
  421. sourceVersion = source[++s].VersionNumber;
  422. }
  423. else
  424. {
  425. // Append all of destination to the end of source.
  426. while (d < dLength)
  427. {
  428. source.Add(dest[d++]);
  429. }
  430. break;
  431. }
  432. }
  433. else
  434. {
  435. source.Insert(s++, dest[d++]);
  436. if (d >= dLength)
  437. {
  438. break;
  439. }
  440. sLength++;
  441. destVersion = dest[d].VersionNumber;
  442. }
  443. }
  444. }
  445. private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  446. {
  447. var plugins = _pluginManager.Plugins;
  448. foreach (var plugin in plugins)
  449. {
  450. if (plugin.Manifest?.AutoUpdate == false)
  451. {
  452. continue;
  453. }
  454. var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
  455. var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
  456. if (version != null && CompletedInstallations.All(x => x.Guid != version.Guid))
  457. {
  458. yield return version;
  459. }
  460. }
  461. }
  462. private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken)
  463. {
  464. var extension = Path.GetExtension(package.SourceUrl);
  465. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  466. {
  467. _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
  468. return;
  469. }
  470. // Always override the passed-in target (which is a file) and figure it out again
  471. string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
  472. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  473. .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false);
  474. response.EnsureSuccessStatusCode();
  475. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  476. // CA5351: Do Not Use Broken Cryptographic Algorithms
  477. #pragma warning disable CA5351
  478. using var md5 = MD5.Create();
  479. cancellationToken.ThrowIfCancellationRequested();
  480. var hash = Convert.ToHexString(md5.ComputeHash(stream));
  481. if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
  482. {
  483. _logger.LogError(
  484. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  485. package.Name,
  486. package.Checksum,
  487. hash);
  488. throw new InvalidDataException("The checksum of the received data doesn't match.");
  489. }
  490. // Version folder as they cannot be overwritten in Windows.
  491. targetDir += "_" + package.Version;
  492. if (Directory.Exists(targetDir))
  493. {
  494. try
  495. {
  496. Directory.Delete(targetDir, true);
  497. }
  498. #pragma warning disable CA1031 // Do not catch general exception types
  499. catch
  500. #pragma warning restore CA1031 // Do not catch general exception types
  501. {
  502. // Ignore any exceptions.
  503. }
  504. }
  505. stream.Position = 0;
  506. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  507. _pluginManager.ImportPluginFrom(targetDir);
  508. }
  509. private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
  510. {
  511. // Set last update time if we were installed before
  512. LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Guid) && p.Version.Equals(package.Version))
  513. ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version));
  514. if (plugin != null)
  515. {
  516. plugin.Manifest.Timestamp = DateTime.UtcNow;
  517. _pluginManager.SaveManifest(plugin.Manifest, plugin.Path);
  518. }
  519. // Do the install
  520. await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false);
  521. // Do plugin-specific processing
  522. _logger.LogInformation(plugin == null ? "New plugin installed: {0} {1}" : "Plugin updated: {0} {1}", package.Name, package.Version);
  523. return plugin != null;
  524. }
  525. }
  526. }