InstallationManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. #pragma warning disable CS1591
  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;
  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 IFileSystem _fileSystem;
  43. private readonly JsonSerializerOptions _jsonSerializerOptions;
  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. public InstallationManager(
  60. ILogger<InstallationManager> logger,
  61. IServerApplicationHost appHost,
  62. IApplicationPaths appPaths,
  63. IEventManager eventManager,
  64. IHttpClientFactory httpClientFactory,
  65. IServerConfigurationManager config,
  66. IFileSystem fileSystem,
  67. IZipClient zipClient)
  68. {
  69. _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
  70. _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  71. _logger = logger;
  72. _applicationHost = appHost;
  73. _appPaths = appPaths;
  74. _eventManager = eventManager;
  75. _httpClientFactory = httpClientFactory;
  76. _config = config;
  77. _fileSystem = fileSystem;
  78. _zipClient = zipClient;
  79. _jsonSerializerOptions = JsonDefaults.GetOptions();
  80. }
  81. /// <inheritdoc />
  82. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  83. /// <inheritdoc />
  84. public async Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, CancellationToken cancellationToken = default)
  85. {
  86. try
  87. {
  88. var packages = await _httpClientFactory.CreateClient(NamedClient.Default)
  89. .GetFromJsonAsync<List<PackageInfo>>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false);
  90. if (packages == null)
  91. {
  92. return Array.Empty<PackageInfo>();
  93. }
  94. // Store the repository and repository url with each version, as they may be spread apart.
  95. foreach (var entry in packages)
  96. {
  97. foreach (var ver in entry.versions)
  98. {
  99. ver.repositoryName = manifestName;
  100. ver.repositoryUrl = manifest;
  101. }
  102. }
  103. return packages;
  104. }
  105. catch (JsonException ex)
  106. {
  107. _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
  108. return Array.Empty<PackageInfo>();
  109. }
  110. catch (UriFormatException ex)
  111. {
  112. _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
  113. return Array.Empty<PackageInfo>();
  114. }
  115. catch (HttpRequestException ex)
  116. {
  117. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  118. return Array.Empty<PackageInfo>();
  119. }
  120. }
  121. private static void MergeSort(IList<VersionInfo> source, IList<VersionInfo> dest)
  122. {
  123. int sLength = source.Count - 1;
  124. int dLength = dest.Count;
  125. int s = 0, d = 0;
  126. var sourceVersion = source[0].VersionNumber;
  127. var destVersion = dest[0].VersionNumber;
  128. while (d < dLength)
  129. {
  130. if (sourceVersion.CompareTo(destVersion) >= 0)
  131. {
  132. if (s < sLength)
  133. {
  134. sourceVersion = source[++s].VersionNumber;
  135. }
  136. else
  137. {
  138. // Append all of destination to the end of source.
  139. while (d < dLength)
  140. {
  141. source.Add(dest[d++]);
  142. }
  143. break;
  144. }
  145. }
  146. else
  147. {
  148. source.Insert(s++, dest[d++]);
  149. if (d >= dLength)
  150. {
  151. break;
  152. }
  153. sLength++;
  154. destVersion = dest[d].VersionNumber;
  155. }
  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)
  165. {
  166. // Where repositories have the same content, the details of the first is taken.
  167. foreach (var package in await GetPackages(repository.Name, repository.Url, 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. if (existing != null)
  176. {
  177. // Assumption is both lists are ordered, so slot these into the correct place.
  178. MergeSort(existing.versions, package.versions);
  179. }
  180. else
  181. {
  182. result.Add(package);
  183. }
  184. }
  185. }
  186. }
  187. return result;
  188. }
  189. /// <inheritdoc />
  190. public IEnumerable<PackageInfo> FilterPackages(
  191. IEnumerable<PackageInfo> availablePackages,
  192. string name = null,
  193. Guid guid = default,
  194. Version specificVersion = null)
  195. {
  196. if (name != null)
  197. {
  198. availablePackages = availablePackages.Where(x => x.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  199. }
  200. if (guid != Guid.Empty)
  201. {
  202. availablePackages = availablePackages.Where(x => Guid.Parse(x.guid) == guid);
  203. }
  204. if (specificVersion != null)
  205. {
  206. availablePackages = availablePackages.Where(x => x.versions.Where(y => y.VersionNumber.Equals(specificVersion)).Any());
  207. }
  208. return availablePackages;
  209. }
  210. /// <inheritdoc />
  211. public IEnumerable<InstallationInfo> GetCompatibleVersions(
  212. IEnumerable<PackageInfo> availablePackages,
  213. string name = null,
  214. Guid guid = default,
  215. Version minVersion = null,
  216. Version specificVersion = null)
  217. {
  218. var package = FilterPackages(availablePackages, name, guid, specificVersion).FirstOrDefault();
  219. // Package not found in repository
  220. if (package == null)
  221. {
  222. yield break;
  223. }
  224. var appVer = _applicationHost.ApplicationVersion;
  225. var availableVersions = package.versions
  226. .Where(x => Version.Parse(x.targetAbi) <= appVer);
  227. if (specificVersion != null)
  228. {
  229. availableVersions = availableVersions.Where(x => x.VersionNumber.Equals(specificVersion));
  230. }
  231. else if (minVersion != null)
  232. {
  233. availableVersions = availableVersions.Where(x => x.VersionNumber >= minVersion);
  234. }
  235. foreach (var v in availableVersions.OrderByDescending(x => x.VersionNumber))
  236. {
  237. yield return new InstallationInfo
  238. {
  239. Changelog = v.changelog,
  240. Guid = new Guid(package.guid),
  241. Name = package.name,
  242. Version = v.VersionNumber,
  243. SourceUrl = v.sourceUrl,
  244. Checksum = v.checksum
  245. };
  246. }
  247. }
  248. /// <inheritdoc />
  249. public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  250. {
  251. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  252. return GetAvailablePluginUpdates(catalog);
  253. }
  254. private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  255. {
  256. var plugins = _applicationHost.GetLocalPlugins(_appPaths.PluginsPath);
  257. foreach (var plugin in plugins)
  258. {
  259. var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
  260. var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
  261. if (version != null && CompletedInstallations.All(x => x.Guid != version.Guid))
  262. {
  263. yield return version;
  264. }
  265. }
  266. }
  267. /// <inheritdoc />
  268. public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
  269. {
  270. if (package == null)
  271. {
  272. throw new ArgumentNullException(nameof(package));
  273. }
  274. var innerCancellationTokenSource = new CancellationTokenSource();
  275. var tuple = (package, innerCancellationTokenSource);
  276. // Add it to the in-progress list
  277. lock (_currentInstallationsLock)
  278. {
  279. _currentInstallations.Add(tuple);
  280. }
  281. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token);
  282. var linkedToken = linkedTokenSource.Token;
  283. await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false);
  284. try
  285. {
  286. var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  287. lock (_currentInstallationsLock)
  288. {
  289. _currentInstallations.Remove(tuple);
  290. }
  291. _completedInstallationsInternal.Add(package);
  292. await _eventManager.PublishAsync(isUpdate
  293. ? (GenericEventArgs<InstallationInfo>)new PluginUpdatedEventArgs(package)
  294. : new PluginInstalledEventArgs(package)).ConfigureAwait(false);
  295. _applicationHost.NotifyPendingRestart();
  296. }
  297. catch (OperationCanceledException)
  298. {
  299. lock (_currentInstallationsLock)
  300. {
  301. _currentInstallations.Remove(tuple);
  302. }
  303. _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
  304. await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false);
  305. throw;
  306. }
  307. catch (Exception ex)
  308. {
  309. _logger.LogError(ex, "Package installation failed");
  310. lock (_currentInstallationsLock)
  311. {
  312. _currentInstallations.Remove(tuple);
  313. }
  314. await _eventManager.PublishAsync(new InstallationFailedEventArgs
  315. {
  316. InstallationInfo = package,
  317. Exception = ex
  318. }).ConfigureAwait(false);
  319. throw;
  320. }
  321. finally
  322. {
  323. // Dispose the progress object and remove the installation from the in-progress list
  324. tuple.innerCancellationTokenSource.Dispose();
  325. }
  326. }
  327. /// <summary>
  328. /// Installs the package internal.
  329. /// </summary>
  330. /// <param name="package">The package.</param>
  331. /// <param name="cancellationToken">The cancellation token.</param>
  332. /// <returns><see cref="Task" />.</returns>
  333. private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
  334. {
  335. // Set last update time if we were installed before
  336. IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Id == package.Guid)
  337. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase));
  338. // Do the install
  339. await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false);
  340. // Do plugin-specific processing
  341. _logger.LogInformation(plugin == null ? "New plugin installed: {0} {1}" : "Plugin updated: {0} {1}", package.Name, package.Version);
  342. return plugin != null;
  343. }
  344. private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken)
  345. {
  346. var extension = Path.GetExtension(package.SourceUrl);
  347. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  348. {
  349. _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
  350. return;
  351. }
  352. // Always override the passed-in target (which is a file) and figure it out again
  353. string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
  354. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  355. .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false);
  356. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  357. // CA5351: Do Not Use Broken Cryptographic Algorithms
  358. #pragma warning disable CA5351
  359. using var md5 = MD5.Create();
  360. cancellationToken.ThrowIfCancellationRequested();
  361. var hash = Convert.ToHexString(md5.ComputeHash(stream));
  362. if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
  363. {
  364. _logger.LogError(
  365. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  366. package.Name,
  367. package.Checksum,
  368. hash);
  369. throw new InvalidDataException("The checksum of the received data doesn't match.");
  370. }
  371. // Version folder as they cannot be overwritten in Windows.
  372. targetDir += "_" + package.Version;
  373. if (Directory.Exists(targetDir))
  374. {
  375. try
  376. {
  377. Directory.Delete(targetDir, true);
  378. }
  379. catch
  380. {
  381. // Ignore any exceptions.
  382. }
  383. }
  384. stream.Position = 0;
  385. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  386. #pragma warning restore CA5351
  387. }
  388. /// <summary>
  389. /// Uninstalls a plugin.
  390. /// </summary>
  391. /// <param name="plugin">The plugin.</param>
  392. public void UninstallPlugin(IPlugin plugin)
  393. {
  394. if (!plugin.CanUninstall)
  395. {
  396. _logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name);
  397. return;
  398. }
  399. plugin.OnUninstalling();
  400. // Remove it the quick way for now
  401. _applicationHost.RemovePlugin(plugin);
  402. var path = plugin.AssemblyFilePath;
  403. bool isDirectory = false;
  404. // Check if we have a plugin directory we should remove too
  405. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  406. {
  407. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  408. isDirectory = true;
  409. }
  410. // Make this case-insensitive to account for possible incorrect assembly naming
  411. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  412. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  413. if (!string.IsNullOrWhiteSpace(file))
  414. {
  415. path = file;
  416. }
  417. try
  418. {
  419. if (isDirectory)
  420. {
  421. _logger.LogInformation("Deleting plugin directory {0}", path);
  422. Directory.Delete(path, true);
  423. }
  424. else
  425. {
  426. _logger.LogInformation("Deleting plugin file {0}", path);
  427. _fileSystem.DeleteFile(path);
  428. }
  429. }
  430. catch
  431. {
  432. // Ignore file errors.
  433. }
  434. var list = _config.Configuration.UninstalledPlugins.ToList();
  435. var filename = Path.GetFileName(path);
  436. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  437. {
  438. list.Add(filename);
  439. _config.Configuration.UninstalledPlugins = list.ToArray();
  440. _config.SaveConfiguration();
  441. }
  442. _eventManager.Publish(new PluginUninstalledEventArgs(plugin));
  443. _applicationHost.NotifyPendingRestart();
  444. }
  445. /// <inheritdoc/>
  446. public bool CancelInstallation(Guid id)
  447. {
  448. lock (_currentInstallationsLock)
  449. {
  450. var install = _currentInstallations.Find(x => x.info.Guid == id);
  451. if (install == default((InstallationInfo, CancellationTokenSource)))
  452. {
  453. return false;
  454. }
  455. install.token.Cancel();
  456. _currentInstallations.Remove(install);
  457. return true;
  458. }
  459. }
  460. /// <inheritdoc />
  461. public void Dispose()
  462. {
  463. Dispose(true);
  464. GC.SuppressFinalize(this);
  465. }
  466. /// <summary>
  467. /// Releases unmanaged and optionally managed resources.
  468. /// </summary>
  469. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  470. protected virtual void Dispose(bool dispose)
  471. {
  472. if (dispose)
  473. {
  474. lock (_currentInstallationsLock)
  475. {
  476. foreach (var tuple in _currentInstallations)
  477. {
  478. tuple.token.Dispose();
  479. }
  480. _currentInstallations.Clear();
  481. }
  482. }
  483. }
  484. }
  485. }