InstallationManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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.Common.System;
  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. using MediaBrowser.Model.System;
  28. namespace Emby.Server.Implementations.Updates
  29. {
  30. /// <summary>
  31. /// Manages all install, uninstall, and update operations for the system and individual plugins.
  32. /// </summary>
  33. public class InstallationManager : IInstallationManager
  34. {
  35. /// <summary>
  36. /// The logger.
  37. /// </summary>
  38. private readonly ILogger<InstallationManager> _logger;
  39. private readonly IApplicationPaths _appPaths;
  40. private readonly IEventManager _eventManager;
  41. private readonly IHttpClientFactory _httpClientFactory;
  42. private readonly IJsonSerializer _jsonSerializer;
  43. private readonly IServerConfigurationManager _config;
  44. private readonly IFileSystem _fileSystem;
  45. /// <summary>
  46. /// Gets the application host.
  47. /// </summary>
  48. /// <value>The application host.</value>
  49. private readonly IApplicationHost _applicationHost;
  50. private readonly IZipClient _zipClient;
  51. private readonly object _currentInstallationsLock = new object();
  52. /// <summary>
  53. /// The current installations.
  54. /// </summary>
  55. private readonly List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations;
  56. /// <summary>
  57. /// The completed installations.
  58. /// </summary>
  59. private readonly ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
  60. public InstallationManager(
  61. ILogger<InstallationManager> logger,
  62. IApplicationHost appHost,
  63. IApplicationPaths appPaths,
  64. IEventManager eventManager,
  65. IHttpClientFactory httpClientFactory,
  66. IJsonSerializer jsonSerializer,
  67. IServerConfigurationManager config,
  68. IFileSystem fileSystem,
  69. IZipClient zipClient)
  70. {
  71. _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
  72. _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  73. _logger = logger;
  74. _applicationHost = appHost;
  75. _appPaths = appPaths;
  76. _eventManager = eventManager;
  77. _httpClientFactory = httpClientFactory;
  78. _jsonSerializer = jsonSerializer;
  79. _config = config;
  80. _fileSystem = fileSystem;
  81. _zipClient = zipClient;
  82. }
  83. /// <inheritdoc />
  84. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  85. /// <inheritdoc />
  86. public async Task<IReadOnlyList<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default)
  87. {
  88. try
  89. {
  90. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  91. .GetAsync(manifest, cancellationToken).ConfigureAwait(false);
  92. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  93. try
  94. {
  95. return await _jsonSerializer.DeserializeFromStreamAsync<IReadOnlyList<PackageInfo>>(stream).ConfigureAwait(false);
  96. }
  97. catch (SerializationException ex)
  98. {
  99. _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
  100. return Array.Empty<PackageInfo>();
  101. }
  102. }
  103. catch (UriFormatException ex)
  104. {
  105. _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
  106. return Array.Empty<PackageInfo>();
  107. }
  108. catch (HttpException ex)
  109. {
  110. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  111. return Array.Empty<PackageInfo>();
  112. }
  113. catch (HttpRequestException ex)
  114. {
  115. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  116. return Array.Empty<PackageInfo>();
  117. }
  118. }
  119. /// <inheritdoc />
  120. public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
  121. {
  122. var result = new List<PackageInfo>();
  123. foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
  124. {
  125. foreach (var package in await GetPackages(repository.Url, cancellationToken).ConfigureAwait(true))
  126. {
  127. package.repositoryName = repository.Name;
  128. package.repositoryUrl = repository.Url;
  129. result.Add(package);
  130. }
  131. }
  132. return result;
  133. }
  134. /// <inheritdoc />
  135. public IEnumerable<PackageInfo> FilterPackages(
  136. IEnumerable<PackageInfo> availablePackages,
  137. string name = null,
  138. Guid guid = default)
  139. {
  140. if (name != null)
  141. {
  142. availablePackages = availablePackages.Where(x => x.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  143. }
  144. if (guid != Guid.Empty)
  145. {
  146. availablePackages = availablePackages.Where(x => Guid.Parse(x.guid) == guid);
  147. }
  148. return availablePackages;
  149. }
  150. /// <inheritdoc />
  151. public IEnumerable<InstallationInfo> GetCompatibleVersions(
  152. IEnumerable<PackageInfo> availablePackages,
  153. string name = null,
  154. Guid guid = default,
  155. Version minVersion = null,
  156. Version specificVersion = null)
  157. {
  158. var package = FilterPackages(availablePackages, name, guid).FirstOrDefault();
  159. // Package not found in repository
  160. if (package == null)
  161. {
  162. yield break;
  163. }
  164. var appVer = _applicationHost.ApplicationVersion;
  165. var availableVersions = package.versions
  166. .Where(x => Version.Parse(x.targetAbi) <= appVer);
  167. if (specificVersion != null)
  168. {
  169. availableVersions = availableVersions.Where(x => new Version(x.version) == specificVersion);
  170. }
  171. else if (minVersion != null)
  172. {
  173. availableVersions = availableVersions.Where(x => new Version(x.version) >= minVersion);
  174. }
  175. foreach (var v in availableVersions.OrderByDescending(x => x.version))
  176. {
  177. yield return new InstallationInfo
  178. {
  179. Changelog = v.changelog,
  180. Guid = new Guid(package.guid),
  181. Name = package.name,
  182. Version = new Version(v.version),
  183. SourceUrl = v.sourceUrl,
  184. Checksum = v.checksum
  185. };
  186. }
  187. }
  188. /// <inheritdoc />
  189. public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  190. {
  191. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  192. return GetAvailablePluginUpdates(catalog);
  193. }
  194. private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  195. {
  196. foreach (var plugin in _applicationHost.Plugins)
  197. {
  198. var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
  199. var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
  200. if (version != null && CompletedInstallations.All(x => x.Guid != version.Guid))
  201. {
  202. yield return version;
  203. }
  204. }
  205. }
  206. /// <inheritdoc />
  207. public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
  208. {
  209. if (package == null)
  210. {
  211. throw new ArgumentNullException(nameof(package));
  212. }
  213. var innerCancellationTokenSource = new CancellationTokenSource();
  214. var tuple = (package, innerCancellationTokenSource);
  215. // Add it to the in-progress list
  216. lock (_currentInstallationsLock)
  217. {
  218. _currentInstallations.Add(tuple);
  219. }
  220. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  221. await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false);
  222. try
  223. {
  224. var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  225. lock (_currentInstallationsLock)
  226. {
  227. _currentInstallations.Remove(tuple);
  228. }
  229. _completedInstallationsInternal.Add(package);
  230. await _eventManager.PublishAsync(isUpdate
  231. ? (GenericEventArgs<InstallationInfo>)new PluginUpdatedEventArgs(package)
  232. : new PluginInstalledEventArgs(package)).ConfigureAwait(false);
  233. _applicationHost.NotifyPendingRestart();
  234. }
  235. catch (OperationCanceledException)
  236. {
  237. lock (_currentInstallationsLock)
  238. {
  239. _currentInstallations.Remove(tuple);
  240. }
  241. _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
  242. await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false);
  243. throw;
  244. }
  245. catch (Exception ex)
  246. {
  247. _logger.LogError(ex, "Package installation failed");
  248. lock (_currentInstallationsLock)
  249. {
  250. _currentInstallations.Remove(tuple);
  251. }
  252. await _eventManager.PublishAsync(new InstallationFailedEventArgs
  253. {
  254. InstallationInfo = package,
  255. Exception = ex
  256. }).ConfigureAwait(false);
  257. throw;
  258. }
  259. finally
  260. {
  261. // Dispose the progress object and remove the installation from the in-progress list
  262. tuple.innerCancellationTokenSource.Dispose();
  263. }
  264. }
  265. /// <summary>
  266. /// Installs the package internal.
  267. /// </summary>
  268. /// <param name="package">The package.</param>
  269. /// <param name="cancellationToken">The cancellation token.</param>
  270. /// <returns><see cref="Task" />.</returns>
  271. private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
  272. {
  273. // Set last update time if we were installed before
  274. IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Id == package.Guid)
  275. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase));
  276. // Do the install
  277. await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false);
  278. // Do plugin-specific processing
  279. _logger.LogInformation(plugin == null ? "New plugin installed: {0} {1}" : "Plugin updated: {0} {1}", package.Name, package.Version);
  280. return plugin != null;
  281. }
  282. private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken)
  283. {
  284. var extension = Path.GetExtension(package.SourceUrl);
  285. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  286. {
  287. _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
  288. return;
  289. }
  290. // Always override the passed-in target (which is a file) and figure it out again
  291. string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
  292. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  293. .GetAsync(package.SourceUrl, cancellationToken).ConfigureAwait(false);
  294. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  295. // CA5351: Do Not Use Broken Cryptographic Algorithms
  296. #pragma warning disable CA5351
  297. using var md5 = MD5.Create();
  298. cancellationToken.ThrowIfCancellationRequested();
  299. var hash = Hex.Encode(md5.ComputeHash(stream));
  300. if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
  301. {
  302. _logger.LogError(
  303. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  304. package.Name,
  305. package.Checksum,
  306. hash);
  307. throw new InvalidDataException("The checksum of the received data doesn't match.");
  308. }
  309. // Version folder as they cannot be overwritten in Windows.
  310. targetDir += "_" + package.Version;
  311. if (Directory.Exists(targetDir))
  312. {
  313. try
  314. {
  315. Directory.Delete(targetDir, true);
  316. }
  317. catch
  318. {
  319. // Ignore any exceptions.
  320. }
  321. }
  322. stream.Position = 0;
  323. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  324. #pragma warning restore CA5351
  325. }
  326. /// <summary>
  327. /// Uninstalls a plugin.
  328. /// </summary>
  329. /// <param name="plugin">The plugin.</param>
  330. public void UninstallPlugin(IPlugin plugin)
  331. {
  332. if (!plugin.CanUninstall)
  333. {
  334. _logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name);
  335. return;
  336. }
  337. plugin.OnUninstalling();
  338. // Remove it the quick way for now
  339. _applicationHost.RemovePlugin(plugin);
  340. var path = plugin.AssemblyFilePath;
  341. bool isDirectory = false;
  342. // Check if we have a plugin directory we should remove too
  343. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  344. {
  345. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  346. isDirectory = true;
  347. }
  348. // Make this case-insensitive to account for possible incorrect assembly naming
  349. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  350. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  351. if (!string.IsNullOrWhiteSpace(file))
  352. {
  353. path = file;
  354. }
  355. try
  356. {
  357. if (isDirectory)
  358. {
  359. _logger.LogInformation("Deleting plugin directory {0}", path);
  360. Directory.Delete(path, true);
  361. }
  362. else
  363. {
  364. _logger.LogInformation("Deleting plugin file {0}", path);
  365. _fileSystem.DeleteFile(path);
  366. }
  367. }
  368. catch
  369. {
  370. // Ignore file errors.
  371. }
  372. var list = _config.Configuration.UninstalledPlugins.ToList();
  373. var filename = Path.GetFileName(path);
  374. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  375. {
  376. list.Add(filename);
  377. _config.Configuration.UninstalledPlugins = list.ToArray();
  378. _config.SaveConfiguration();
  379. }
  380. _eventManager.Publish(new PluginUninstalledEventArgs(plugin));
  381. _applicationHost.NotifyPendingRestart();
  382. }
  383. /// <inheritdoc/>
  384. public bool CancelInstallation(Guid id)
  385. {
  386. lock (_currentInstallationsLock)
  387. {
  388. var install = _currentInstallations.Find(x => x.info.Guid == id);
  389. if (install == default((InstallationInfo, CancellationTokenSource)))
  390. {
  391. return false;
  392. }
  393. install.token.Cancel();
  394. _currentInstallations.Remove(install);
  395. return true;
  396. }
  397. }
  398. /// <inheritdoc />
  399. public void Dispose()
  400. {
  401. Dispose(true);
  402. GC.SuppressFinalize(this);
  403. }
  404. /// <summary>
  405. /// Releases unmanaged and optionally managed resources.
  406. /// </summary>
  407. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  408. protected virtual void Dispose(bool dispose)
  409. {
  410. if (dispose)
  411. {
  412. lock (_currentInstallationsLock)
  413. {
  414. foreach (var tuple in _currentInstallations)
  415. {
  416. tuple.token.Dispose();
  417. }
  418. _currentInstallations.Clear();
  419. }
  420. }
  421. }
  422. }
  423. }