InstallationManager.cs 18 KB

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