InstallationManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Security.Cryptography;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Common.Plugins;
  14. using MediaBrowser.Common.Updates;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Model.Updates;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.Updates
  22. {
  23. /// <summary>
  24. /// Manages all install, uninstall and update operations (both plugins and system)
  25. /// </summary>
  26. public class InstallationManager : IInstallationManager
  27. {
  28. /// <summary>
  29. /// The _logger.
  30. /// </summary>
  31. private readonly ILogger _logger;
  32. private readonly IApplicationPaths _appPaths;
  33. private readonly IHttpClient _httpClient;
  34. private readonly IJsonSerializer _jsonSerializer;
  35. private readonly IServerConfigurationManager _config;
  36. private readonly IFileSystem _fileSystem;
  37. /// <summary>
  38. /// Gets the application host.
  39. /// </summary>
  40. /// <value>The application host.</value>
  41. private readonly IApplicationHost _applicationHost;
  42. private readonly IZipClient _zipClient;
  43. private readonly object _currentInstallationsLock = new object();
  44. /// <summary>
  45. /// The current installations.
  46. /// </summary>
  47. private List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations;
  48. /// <summary>
  49. /// The completed installations.
  50. /// </summary>
  51. private ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
  52. public InstallationManager(
  53. ILogger<InstallationManager> logger,
  54. IApplicationHost appHost,
  55. IApplicationPaths appPaths,
  56. IHttpClient httpClient,
  57. IJsonSerializer jsonSerializer,
  58. IServerConfigurationManager config,
  59. IFileSystem fileSystem,
  60. IZipClient zipClient)
  61. {
  62. if (logger == null)
  63. {
  64. throw new ArgumentNullException(nameof(logger));
  65. }
  66. _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
  67. _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  68. _logger = logger;
  69. _applicationHost = appHost;
  70. _appPaths = appPaths;
  71. _httpClient = httpClient;
  72. _jsonSerializer = jsonSerializer;
  73. _config = config;
  74. _fileSystem = fileSystem;
  75. _zipClient = zipClient;
  76. }
  77. public event EventHandler<InstallationEventArgs> PackageInstalling;
  78. public event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
  79. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  80. public event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
  81. /// <summary>
  82. /// Occurs when a plugin is uninstalled.
  83. /// </summary>
  84. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  85. /// <summary>
  86. /// Occurs when a plugin plugin is updated.
  87. /// </summary>
  88. public event EventHandler<GenericEventArgs<(IPlugin, PackageVersionInfo)>> PluginUpdated;
  89. /// <summary>
  90. /// Occurs when a plugin plugin is installed.
  91. /// </summary>
  92. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  93. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  94. /// <summary>
  95. /// Gets all available packages.
  96. /// </summary>
  97. /// <returns>Task{List{PackageInfo}}.</returns>
  98. public async Task<List<PackageInfo>> GetAvailablePackages(
  99. CancellationToken cancellationToken,
  100. bool withRegistration = true,
  101. string packageType = null,
  102. Version applicationVersion = null)
  103. {
  104. var packages = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  105. return FilterPackages(packages, packageType, applicationVersion);
  106. }
  107. /// <summary>
  108. /// Gets all available packages.
  109. /// </summary>
  110. /// <param name="cancellationToken">The cancellation token.</param>
  111. /// <returns>Task{List{PackageInfo}}.</returns>
  112. public async Task<List<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken)
  113. {
  114. using (var response = await _httpClient.SendAsync(
  115. new HttpRequestOptions
  116. {
  117. Url = "https://repo.jellyfin.org/releases/plugin/manifest.json",
  118. CancellationToken = cancellationToken,
  119. CacheMode = CacheMode.Unconditional,
  120. CacheLength = GetCacheLength()
  121. },
  122. HttpMethod.Get).ConfigureAwait(false))
  123. using (Stream stream = response.Content)
  124. {
  125. return FilterPackages(await _jsonSerializer.DeserializeFromStreamAsync<PackageInfo[]>(stream).ConfigureAwait(false));
  126. }
  127. }
  128. private static TimeSpan GetCacheLength()
  129. {
  130. return TimeSpan.FromMinutes(3);
  131. }
  132. protected List<PackageInfo> FilterPackages(IEnumerable<PackageInfo> packages)
  133. {
  134. var list = new List<PackageInfo>();
  135. foreach (var package in packages)
  136. {
  137. var versions = new List<PackageVersionInfo>();
  138. foreach (var version in package.versions)
  139. {
  140. if (string.IsNullOrEmpty(version.sourceUrl))
  141. {
  142. continue;
  143. }
  144. versions.Add(version);
  145. }
  146. package.versions = versions
  147. .OrderByDescending(x => x.Version)
  148. .ToArray();
  149. if (package.versions.Length == 0)
  150. {
  151. continue;
  152. }
  153. list.Add(package);
  154. }
  155. // Remove packages with no versions
  156. return list;
  157. }
  158. protected List<PackageInfo> FilterPackages(IEnumerable<PackageInfo> packages, string packageType, Version applicationVersion)
  159. {
  160. var packagesList = FilterPackages(packages);
  161. var returnList = new List<PackageInfo>();
  162. var filterOnPackageType = !string.IsNullOrEmpty(packageType);
  163. foreach (var p in packagesList)
  164. {
  165. if (filterOnPackageType && !string.Equals(p.type, packageType, StringComparison.OrdinalIgnoreCase))
  166. {
  167. continue;
  168. }
  169. // If an app version was supplied, filter the versions for each package to only include supported versions
  170. if (applicationVersion != null)
  171. {
  172. p.versions = p.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToArray();
  173. }
  174. if (p.versions.Length == 0)
  175. {
  176. continue;
  177. }
  178. returnList.Add(p);
  179. }
  180. return returnList;
  181. }
  182. /// <summary>
  183. /// Determines whether [is package version up to date] [the specified package version info].
  184. /// </summary>
  185. /// <param name="packageVersionInfo">The package version info.</param>
  186. /// <param name="currentServerVersion">The current server version.</param>
  187. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  188. private static bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
  189. {
  190. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  191. {
  192. return true;
  193. }
  194. return Version.TryParse(packageVersionInfo.requiredVersionStr, out var requiredVersion) && currentServerVersion >= requiredVersion;
  195. }
  196. /// <summary>
  197. /// Gets the package.
  198. /// </summary>
  199. /// <param name="name">The name.</param>
  200. /// <param name="guid">The assembly guid</param>
  201. /// <param name="classification">The classification.</param>
  202. /// <param name="version">The version.</param>
  203. /// <returns>Task{PackageVersionInfo}.</returns>
  204. public async Task<PackageVersionInfo> GetPackage(string name, string guid, PackageVersionClass classification, Version version)
  205. {
  206. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  207. var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  208. ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  209. if (package == null)
  210. {
  211. return null;
  212. }
  213. return package.versions.FirstOrDefault(v => v.Version == version && v.classification == classification);
  214. }
  215. /// <summary>
  216. /// Gets the latest compatible version.
  217. /// </summary>
  218. /// <param name="name">The name.</param>
  219. /// <param name="guid">The assembly guid if this is a plug-in</param>
  220. /// <param name="currentServerVersion">The current server version.</param>
  221. /// <param name="classification">The classification.</param>
  222. /// <returns>Task{PackageVersionInfo}.</returns>
  223. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  224. {
  225. var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false);
  226. return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification);
  227. }
  228. /// <summary>
  229. /// Gets the latest compatible version.
  230. /// </summary>
  231. /// <param name="availablePackages">The available packages.</param>
  232. /// <param name="name">The name.</param>
  233. /// <param name="currentServerVersion">The current server version.</param>
  234. /// <param name="classification">The classification.</param>
  235. /// <returns>PackageVersionInfo.</returns>
  236. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  237. {
  238. var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase))
  239. ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  240. return package?.versions
  241. .OrderByDescending(x => x.Version)
  242. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  243. }
  244. /// <summary>
  245. /// Gets the available plugin updates.
  246. /// </summary>
  247. /// <param name="applicationVersion">The current server version.</param>
  248. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  249. /// <param name="cancellationToken">The cancellation token.</param>
  250. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  251. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  252. {
  253. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  254. var systemUpdateLevel = _applicationHost.SystemUpdateLevel;
  255. // Figure out what needs to be installed
  256. return _applicationHost.Plugins.Select(p =>
  257. {
  258. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, systemUpdateLevel);
  259. return latestPluginInfo != null && latestPluginInfo.Version > p.Version ? latestPluginInfo : null;
  260. }).Where(i => i != null)
  261. .Where(p => !string.IsNullOrEmpty(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.AssemblyGuid, p.guid, StringComparison.OrdinalIgnoreCase)));
  262. }
  263. /// <inheritdoc />
  264. public async Task InstallPackage(PackageVersionInfo package, CancellationToken cancellationToken)
  265. {
  266. if (package == null)
  267. {
  268. throw new ArgumentNullException(nameof(package));
  269. }
  270. var installationInfo = new InstallationInfo
  271. {
  272. Id = Guid.NewGuid(),
  273. Name = package.name,
  274. AssemblyGuid = package.guid,
  275. UpdateClass = package.classification,
  276. Version = package.versionStr
  277. };
  278. var innerCancellationTokenSource = new CancellationTokenSource();
  279. var tuple = (installationInfo, innerCancellationTokenSource);
  280. // Add it to the in-progress list
  281. lock (_currentInstallationsLock)
  282. {
  283. _currentInstallations.Add(tuple);
  284. }
  285. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  286. var installationEventArgs = new InstallationEventArgs
  287. {
  288. InstallationInfo = installationInfo,
  289. PackageVersionInfo = package
  290. };
  291. PackageInstalling?.Invoke(this, installationEventArgs);
  292. try
  293. {
  294. await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  295. lock (_currentInstallationsLock)
  296. {
  297. _currentInstallations.Remove(tuple);
  298. }
  299. _completedInstallationsInternal.Add(installationInfo);
  300. PackageInstallationCompleted?.Invoke(this, installationEventArgs);
  301. }
  302. catch (OperationCanceledException)
  303. {
  304. lock (_currentInstallationsLock)
  305. {
  306. _currentInstallations.Remove(tuple);
  307. }
  308. _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  309. PackageInstallationCancelled?.Invoke(this, installationEventArgs);
  310. throw;
  311. }
  312. catch (Exception ex)
  313. {
  314. _logger.LogError(ex, "Package installation failed");
  315. lock (_currentInstallationsLock)
  316. {
  317. _currentInstallations.Remove(tuple);
  318. }
  319. PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
  320. {
  321. InstallationInfo = installationInfo,
  322. Exception = ex
  323. });
  324. throw;
  325. }
  326. finally
  327. {
  328. // Dispose the progress object and remove the installation from the in-progress list
  329. tuple.Item2.Dispose();
  330. }
  331. }
  332. /// <summary>
  333. /// Installs the package internal.
  334. /// </summary>
  335. /// <param name="package">The package.</param>
  336. /// <param name="cancellationToken">The cancellation token.</param>
  337. /// <returns><see cref="Task" />.</returns>
  338. private async Task InstallPackageInternal(PackageVersionInfo package, CancellationToken cancellationToken)
  339. {
  340. // Set last update time if we were installed before
  341. IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  342. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  343. // Do the install
  344. await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false);
  345. // Do plugin-specific processing
  346. if (plugin == null)
  347. {
  348. _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  349. PluginInstalled?.Invoke(this, new GenericEventArgs<PackageVersionInfo>(package));
  350. }
  351. else
  352. {
  353. _logger.LogInformation("Plugin updated: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  354. PluginUpdated?.Invoke(this, new GenericEventArgs<(IPlugin, PackageVersionInfo)>((plugin, package)));
  355. }
  356. _applicationHost.NotifyPendingRestart();
  357. }
  358. private async Task PerformPackageInstallation(PackageVersionInfo package, CancellationToken cancellationToken)
  359. {
  360. var extension = Path.GetExtension(package.targetFilename);
  361. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  362. {
  363. _logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename);
  364. return;
  365. }
  366. // Always override the passed-in target (which is a file) and figure it out again
  367. string targetDir = Path.Combine(_appPaths.PluginsPath, package.name);
  368. // CA5351: Do Not Use Broken Cryptographic Algorithms
  369. #pragma warning disable CA5351
  370. using (var res = await _httpClient.SendAsync(
  371. new HttpRequestOptions
  372. {
  373. Url = package.sourceUrl,
  374. CancellationToken = cancellationToken,
  375. // We need it to be buffered for setting the position
  376. BufferContent = true
  377. },
  378. HttpMethod.Get).ConfigureAwait(false))
  379. using (var stream = res.Content)
  380. using (var md5 = MD5.Create())
  381. {
  382. cancellationToken.ThrowIfCancellationRequested();
  383. var hash = Hex.Encode(md5.ComputeHash(stream));
  384. if (!string.Equals(package.checksum, hash, StringComparison.OrdinalIgnoreCase))
  385. {
  386. _logger.LogError(
  387. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  388. package.name,
  389. package.checksum,
  390. hash);
  391. throw new InvalidDataException("The checksum of the received data doesn't match.");
  392. }
  393. if (Directory.Exists(targetDir))
  394. {
  395. Directory.Delete(targetDir, true);
  396. }
  397. stream.Position = 0;
  398. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  399. }
  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. plugin.OnUninstalling();
  409. // Remove it the quick way for now
  410. _applicationHost.RemovePlugin(plugin);
  411. var path = plugin.AssemblyFilePath;
  412. bool isDirectory = false;
  413. // Check if we have a plugin directory we should remove too
  414. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  415. {
  416. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  417. isDirectory = true;
  418. }
  419. // Make this case-insensitive to account for possible incorrect assembly naming
  420. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  421. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  422. if (!string.IsNullOrWhiteSpace(file))
  423. {
  424. path = file;
  425. }
  426. if (isDirectory)
  427. {
  428. _logger.LogInformation("Deleting plugin directory {0}", path);
  429. Directory.Delete(path, true);
  430. }
  431. else
  432. {
  433. _logger.LogInformation("Deleting plugin file {0}", path);
  434. _fileSystem.DeleteFile(path);
  435. }
  436. var list = _config.Configuration.UninstalledPlugins.ToList();
  437. var filename = Path.GetFileName(path);
  438. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  439. {
  440. list.Add(filename);
  441. _config.Configuration.UninstalledPlugins = list.ToArray();
  442. _config.SaveConfiguration();
  443. }
  444. PluginUninstalled?.Invoke(this, new GenericEventArgs<IPlugin> { Argument = plugin });
  445. _applicationHost.NotifyPendingRestart();
  446. }
  447. /// <inheritdoc/>
  448. public bool CancelInstallation(Guid id)
  449. {
  450. lock (_currentInstallationsLock)
  451. {
  452. var install = _currentInstallations.Find(x => x.Item1.Id == id);
  453. if (install == default((InstallationInfo, CancellationTokenSource)))
  454. {
  455. return false;
  456. }
  457. install.Item2.Cancel();
  458. _currentInstallations.Remove(install);
  459. return true;
  460. }
  461. }
  462. public void Dispose()
  463. {
  464. Dispose(true);
  465. GC.SuppressFinalize(this);
  466. }
  467. /// <summary>
  468. /// Releases unmanaged and - optionally - managed resources.
  469. /// </summary>
  470. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  471. protected virtual void Dispose(bool dispose)
  472. {
  473. if (dispose)
  474. {
  475. lock (_currentInstallationsLock)
  476. {
  477. foreach (var tuple in _currentInstallations)
  478. {
  479. tuple.Item2.Dispose();
  480. }
  481. _currentInstallations.Clear();
  482. }
  483. }
  484. }
  485. }
  486. }