InstallationManager.cs 21 KB

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