2
0

InstallationManager.cs 24 KB

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