InstallationManager.cs 17 KB

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