InstallationManager.cs 18 KB

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