InstallationManager.cs 18 KB

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