InstallationManager.cs 23 KB

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