InstallationManager.cs 24 KB

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