InstallationManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  165. {
  166. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  167. return GetAvailablePluginUpdates(catalog);
  168. }
  169. private IEnumerable<PackageVersionInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  170. {
  171. foreach (var plugin in _applicationHost.Plugins)
  172. {
  173. var compatibleversions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, plugin.Version, _applicationHost.SystemUpdateLevel);
  174. var version = compatibleversions.FirstOrDefault(y => y.Version > plugin.Version);
  175. if (version != null
  176. && !CompletedInstallations.Any(x => string.Equals(x.AssemblyGuid, version.guid, StringComparison.OrdinalIgnoreCase)))
  177. {
  178. yield return version;
  179. }
  180. }
  181. }
  182. /// <inheritdoc />
  183. public async Task InstallPackage(PackageVersionInfo package, CancellationToken cancellationToken)
  184. {
  185. if (package == null)
  186. {
  187. throw new ArgumentNullException(nameof(package));
  188. }
  189. var installationInfo = new InstallationInfo
  190. {
  191. Id = Guid.NewGuid(),
  192. Name = package.name,
  193. AssemblyGuid = package.guid,
  194. UpdateClass = package.classification,
  195. Version = package.versionStr
  196. };
  197. var innerCancellationTokenSource = new CancellationTokenSource();
  198. var tuple = (installationInfo, innerCancellationTokenSource);
  199. // Add it to the in-progress list
  200. lock (_currentInstallationsLock)
  201. {
  202. _currentInstallations.Add(tuple);
  203. }
  204. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  205. var installationEventArgs = new InstallationEventArgs
  206. {
  207. InstallationInfo = installationInfo,
  208. PackageVersionInfo = package
  209. };
  210. PackageInstalling?.Invoke(this, installationEventArgs);
  211. try
  212. {
  213. await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  214. lock (_currentInstallationsLock)
  215. {
  216. _currentInstallations.Remove(tuple);
  217. }
  218. _completedInstallationsInternal.Add(installationInfo);
  219. PackageInstallationCompleted?.Invoke(this, installationEventArgs);
  220. }
  221. catch (OperationCanceledException)
  222. {
  223. lock (_currentInstallationsLock)
  224. {
  225. _currentInstallations.Remove(tuple);
  226. }
  227. _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  228. PackageInstallationCancelled?.Invoke(this, installationEventArgs);
  229. throw;
  230. }
  231. catch (Exception ex)
  232. {
  233. _logger.LogError(ex, "Package installation failed");
  234. lock (_currentInstallationsLock)
  235. {
  236. _currentInstallations.Remove(tuple);
  237. }
  238. PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
  239. {
  240. InstallationInfo = installationInfo,
  241. Exception = ex
  242. });
  243. throw;
  244. }
  245. finally
  246. {
  247. // Dispose the progress object and remove the installation from the in-progress list
  248. tuple.innerCancellationTokenSource.Dispose();
  249. }
  250. }
  251. /// <summary>
  252. /// Installs the package internal.
  253. /// </summary>
  254. /// <param name="package">The package.</param>
  255. /// <param name="cancellationToken">The cancellation token.</param>
  256. /// <returns><see cref="Task" />.</returns>
  257. private async Task InstallPackageInternal(PackageVersionInfo package, CancellationToken cancellationToken)
  258. {
  259. // Set last update time if we were installed before
  260. IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase))
  261. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  262. // Do the install
  263. await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false);
  264. // Do plugin-specific processing
  265. if (plugin == null)
  266. {
  267. _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  268. PluginInstalled?.Invoke(this, new GenericEventArgs<PackageVersionInfo>(package));
  269. }
  270. else
  271. {
  272. _logger.LogInformation("Plugin updated: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
  273. PluginUpdated?.Invoke(this, new GenericEventArgs<(IPlugin, PackageVersionInfo)>((plugin, package)));
  274. }
  275. _applicationHost.NotifyPendingRestart();
  276. }
  277. private async Task PerformPackageInstallation(PackageVersionInfo package, CancellationToken cancellationToken)
  278. {
  279. var extension = Path.GetExtension(package.targetFilename);
  280. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  281. {
  282. _logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename);
  283. return;
  284. }
  285. // Always override the passed-in target (which is a file) and figure it out again
  286. string targetDir = Path.Combine(_appPaths.PluginsPath, package.name);
  287. // CA5351: Do Not Use Broken Cryptographic Algorithms
  288. #pragma warning disable CA5351
  289. using (var res = await _httpClient.SendAsync(
  290. new HttpRequestOptions
  291. {
  292. Url = package.sourceUrl,
  293. CancellationToken = cancellationToken,
  294. // We need it to be buffered for setting the position
  295. BufferContent = true
  296. },
  297. HttpMethod.Get).ConfigureAwait(false))
  298. using (var stream = res.Content)
  299. using (var md5 = MD5.Create())
  300. {
  301. cancellationToken.ThrowIfCancellationRequested();
  302. var hash = Hex.Encode(md5.ComputeHash(stream));
  303. if (!string.Equals(package.checksum, hash, StringComparison.OrdinalIgnoreCase))
  304. {
  305. _logger.LogError(
  306. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  307. package.name,
  308. package.checksum,
  309. hash);
  310. throw new InvalidDataException("The checksum of the received data doesn't match.");
  311. }
  312. if (Directory.Exists(targetDir))
  313. {
  314. Directory.Delete(targetDir, true);
  315. }
  316. stream.Position = 0;
  317. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  318. }
  319. #pragma warning restore CA5351
  320. }
  321. /// <summary>
  322. /// Uninstalls a plugin
  323. /// </summary>
  324. /// <param name="plugin">The plugin.</param>
  325. public void UninstallPlugin(IPlugin plugin)
  326. {
  327. plugin.OnUninstalling();
  328. // Remove it the quick way for now
  329. _applicationHost.RemovePlugin(plugin);
  330. var path = plugin.AssemblyFilePath;
  331. bool isDirectory = false;
  332. // Check if we have a plugin directory we should remove too
  333. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  334. {
  335. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  336. isDirectory = true;
  337. }
  338. // Make this case-insensitive to account for possible incorrect assembly naming
  339. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  340. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  341. if (!string.IsNullOrWhiteSpace(file))
  342. {
  343. path = file;
  344. }
  345. if (isDirectory)
  346. {
  347. _logger.LogInformation("Deleting plugin directory {0}", path);
  348. Directory.Delete(path, true);
  349. }
  350. else
  351. {
  352. _logger.LogInformation("Deleting plugin file {0}", path);
  353. _fileSystem.DeleteFile(path);
  354. }
  355. var list = _config.Configuration.UninstalledPlugins.ToList();
  356. var filename = Path.GetFileName(path);
  357. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  358. {
  359. list.Add(filename);
  360. _config.Configuration.UninstalledPlugins = list.ToArray();
  361. _config.SaveConfiguration();
  362. }
  363. PluginUninstalled?.Invoke(this, new GenericEventArgs<IPlugin> { Argument = plugin });
  364. _applicationHost.NotifyPendingRestart();
  365. }
  366. /// <inheritdoc/>
  367. public bool CancelInstallation(Guid id)
  368. {
  369. lock (_currentInstallationsLock)
  370. {
  371. var install = _currentInstallations.Find(x => x.info.Id == id);
  372. if (install == default((InstallationInfo, CancellationTokenSource)))
  373. {
  374. return false;
  375. }
  376. install.token.Cancel();
  377. _currentInstallations.Remove(install);
  378. return true;
  379. }
  380. }
  381. /// <inheritdoc />
  382. public void Dispose()
  383. {
  384. Dispose(true);
  385. GC.SuppressFinalize(this);
  386. }
  387. /// <summary>
  388. /// Releases unmanaged and - optionally - managed resources.
  389. /// </summary>
  390. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  391. protected virtual void Dispose(bool dispose)
  392. {
  393. if (dispose)
  394. {
  395. lock (_currentInstallationsLock)
  396. {
  397. foreach (var tuple in _currentInstallations)
  398. {
  399. tuple.token.Dispose();
  400. }
  401. _currentInstallations.Clear();
  402. }
  403. }
  404. }
  405. }
  406. }