InstallationManager.cs 21 KB

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