InstallationManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Runtime.Serialization;
  9. using System.Security.Cryptography;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Net;
  15. using MediaBrowser.Common.Plugins;
  16. using MediaBrowser.Common.Updates;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Net;
  20. using MediaBrowser.Model.Serialization;
  21. using MediaBrowser.Model.Updates;
  22. using Microsoft.Extensions.Logging;
  23. namespace Emby.Server.Implementations.Updates
  24. {
  25. /// <summary>
  26. /// Manages all install, uninstall, and update operations for the system and individual plugins.
  27. /// </summary>
  28. public class InstallationManager : IInstallationManager
  29. {
  30. /// <summary>
  31. /// The logger.
  32. /// </summary>
  33. private readonly ILogger<InstallationManager> _logger;
  34. private readonly IApplicationPaths _appPaths;
  35. private readonly IHttpClientFactory _httpClientFactory;
  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 readonly List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations;
  50. /// <summary>
  51. /// The completed installations.
  52. /// </summary>
  53. private readonly ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
  54. public InstallationManager(
  55. ILogger<InstallationManager> logger,
  56. IApplicationHost appHost,
  57. IApplicationPaths appPaths,
  58. IHttpClientFactory httpClientFactory,
  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. _httpClientFactory = httpClientFactory;
  74. _jsonSerializer = jsonSerializer;
  75. _config = config;
  76. _fileSystem = fileSystem;
  77. _zipClient = zipClient;
  78. }
  79. /// <inheritdoc />
  80. public event EventHandler<InstallationInfo> PackageInstalling;
  81. /// <inheritdoc />
  82. public event EventHandler<InstallationInfo> PackageInstallationCompleted;
  83. /// <inheritdoc />
  84. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  85. /// <inheritdoc />
  86. public event EventHandler<InstallationInfo> PackageInstallationCancelled;
  87. /// <inheritdoc />
  88. public event EventHandler<IPlugin> PluginUninstalled;
  89. /// <inheritdoc />
  90. public event EventHandler<InstallationInfo> PluginUpdated;
  91. /// <inheritdoc />
  92. public event EventHandler<InstallationInfo> PluginInstalled;
  93. /// <inheritdoc />
  94. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  95. /// <inheritdoc />
  96. public async Task<IReadOnlyList<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default)
  97. {
  98. try
  99. {
  100. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  101. .GetAsync(manifest, cancellationToken).ConfigureAwait(false);
  102. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  103. try
  104. {
  105. return await _jsonSerializer.DeserializeFromStreamAsync<IReadOnlyList<PackageInfo>>(stream).ConfigureAwait(false);
  106. }
  107. catch (SerializationException ex)
  108. {
  109. _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
  110. return Array.Empty<PackageInfo>();
  111. }
  112. }
  113. catch (UriFormatException ex)
  114. {
  115. _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
  116. return Array.Empty<PackageInfo>();
  117. }
  118. catch (HttpException ex)
  119. {
  120. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  121. return Array.Empty<PackageInfo>();
  122. }
  123. catch (HttpRequestException ex)
  124. {
  125. _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
  126. return Array.Empty<PackageInfo>();
  127. }
  128. }
  129. /// <inheritdoc />
  130. public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
  131. {
  132. var result = new List<PackageInfo>();
  133. foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
  134. {
  135. result.AddRange(await GetPackages(repository.Url, cancellationToken).ConfigureAwait(true));
  136. }
  137. return result;
  138. }
  139. /// <inheritdoc />
  140. public IEnumerable<PackageInfo> FilterPackages(
  141. IEnumerable<PackageInfo> availablePackages,
  142. string name = null,
  143. Guid guid = default)
  144. {
  145. if (name != null)
  146. {
  147. availablePackages = availablePackages.Where(x => x.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  148. }
  149. if (guid != Guid.Empty)
  150. {
  151. availablePackages = availablePackages.Where(x => Guid.Parse(x.guid) == guid);
  152. }
  153. return availablePackages;
  154. }
  155. /// <inheritdoc />
  156. public IEnumerable<InstallationInfo> GetCompatibleVersions(
  157. IEnumerable<PackageInfo> availablePackages,
  158. string name = null,
  159. Guid guid = default,
  160. Version minVersion = null,
  161. Version specificVersion = null)
  162. {
  163. var package = FilterPackages(availablePackages, name, guid).FirstOrDefault();
  164. // Package not found in repository
  165. if (package == null)
  166. {
  167. yield break;
  168. }
  169. var appVer = _applicationHost.ApplicationVersion;
  170. var availableVersions = package.versions
  171. .Where(x => Version.Parse(x.targetAbi) <= appVer);
  172. if (specificVersion != null)
  173. {
  174. availableVersions = availableVersions.Where(x => new Version(x.version) == specificVersion);
  175. }
  176. else if (minVersion != null)
  177. {
  178. availableVersions = availableVersions.Where(x => new Version(x.version) >= minVersion);
  179. }
  180. foreach (var v in availableVersions.OrderByDescending(x => x.version))
  181. {
  182. yield return new InstallationInfo
  183. {
  184. Changelog = v.changelog,
  185. Guid = new Guid(package.guid),
  186. Name = package.name,
  187. Version = new Version(v.version),
  188. SourceUrl = v.sourceUrl,
  189. Checksum = v.checksum
  190. };
  191. }
  192. }
  193. /// <inheritdoc />
  194. public async Task<IEnumerable<InstallationInfo>> GetAvailablePluginUpdates(CancellationToken cancellationToken = default)
  195. {
  196. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  197. return GetAvailablePluginUpdates(catalog);
  198. }
  199. private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog)
  200. {
  201. foreach (var plugin in _applicationHost.Plugins)
  202. {
  203. var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version);
  204. var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version);
  205. if (version != null && CompletedInstallations.All(x => x.Guid != version.Guid))
  206. {
  207. yield return version;
  208. }
  209. }
  210. }
  211. /// <inheritdoc />
  212. public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken)
  213. {
  214. if (package == null)
  215. {
  216. throw new ArgumentNullException(nameof(package));
  217. }
  218. var innerCancellationTokenSource = new CancellationTokenSource();
  219. var tuple = (package, innerCancellationTokenSource);
  220. // Add it to the in-progress list
  221. lock (_currentInstallationsLock)
  222. {
  223. _currentInstallations.Add(tuple);
  224. }
  225. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  226. PackageInstalling?.Invoke(this, package);
  227. try
  228. {
  229. await InstallPackageInternal(package, linkedToken).ConfigureAwait(false);
  230. lock (_currentInstallationsLock)
  231. {
  232. _currentInstallations.Remove(tuple);
  233. }
  234. _completedInstallationsInternal.Add(package);
  235. PackageInstallationCompleted?.Invoke(this, package);
  236. }
  237. catch (OperationCanceledException)
  238. {
  239. lock (_currentInstallationsLock)
  240. {
  241. _currentInstallations.Remove(tuple);
  242. }
  243. _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version);
  244. PackageInstallationCancelled?.Invoke(this, package);
  245. throw;
  246. }
  247. catch (Exception ex)
  248. {
  249. _logger.LogError(ex, "Package installation failed");
  250. lock (_currentInstallationsLock)
  251. {
  252. _currentInstallations.Remove(tuple);
  253. }
  254. PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
  255. {
  256. InstallationInfo = package,
  257. Exception = ex
  258. });
  259. throw;
  260. }
  261. finally
  262. {
  263. // Dispose the progress object and remove the installation from the in-progress list
  264. tuple.innerCancellationTokenSource.Dispose();
  265. }
  266. }
  267. /// <summary>
  268. /// Installs the package internal.
  269. /// </summary>
  270. /// <param name="package">The package.</param>
  271. /// <param name="cancellationToken">The cancellation token.</param>
  272. /// <returns><see cref="Task" />.</returns>
  273. private async Task InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken)
  274. {
  275. // Set last update time if we were installed before
  276. IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Id == package.Guid)
  277. ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase));
  278. // Do the install
  279. await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false);
  280. // Do plugin-specific processing
  281. if (plugin == null)
  282. {
  283. _logger.LogInformation("New plugin installed: {0} {1}", package.Name, package.Version);
  284. PluginInstalled?.Invoke(this, package);
  285. }
  286. else
  287. {
  288. _logger.LogInformation("Plugin updated: {0} {1}", package.Name, package.Version);
  289. PluginUpdated?.Invoke(this, package);
  290. }
  291. _applicationHost.NotifyPendingRestart();
  292. }
  293. private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken)
  294. {
  295. var extension = Path.GetExtension(package.SourceUrl);
  296. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
  297. {
  298. _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl);
  299. return;
  300. }
  301. // Always override the passed-in target (which is a file) and figure it out again
  302. string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name);
  303. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  304. .GetAsync(package.SourceUrl, cancellationToken).ConfigureAwait(false);
  305. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  306. // CA5351: Do Not Use Broken Cryptographic Algorithms
  307. #pragma warning disable CA5351
  308. using var md5 = MD5.Create();
  309. cancellationToken.ThrowIfCancellationRequested();
  310. var hash = Hex.Encode(md5.ComputeHash(stream));
  311. if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase))
  312. {
  313. _logger.LogError(
  314. "The checksums didn't match while installing {Package}, expected: {Expected}, got: {Received}",
  315. package.Name,
  316. package.Checksum,
  317. hash);
  318. throw new InvalidDataException("The checksum of the received data doesn't match.");
  319. }
  320. if (Directory.Exists(targetDir))
  321. {
  322. Directory.Delete(targetDir, true);
  323. }
  324. stream.Position = 0;
  325. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  326. #pragma warning restore CA5351
  327. }
  328. /// <summary>
  329. /// Uninstalls a plugin.
  330. /// </summary>
  331. /// <param name="plugin">The plugin.</param>
  332. public void UninstallPlugin(IPlugin plugin)
  333. {
  334. if (!plugin.CanUninstall)
  335. {
  336. _logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name);
  337. return;
  338. }
  339. plugin.OnUninstalling();
  340. // Remove it the quick way for now
  341. _applicationHost.RemovePlugin(plugin);
  342. var path = plugin.AssemblyFilePath;
  343. bool isDirectory = false;
  344. // Check if we have a plugin directory we should remove too
  345. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  346. {
  347. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  348. isDirectory = true;
  349. }
  350. // Make this case-insensitive to account for possible incorrect assembly naming
  351. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  352. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  353. if (!string.IsNullOrWhiteSpace(file))
  354. {
  355. path = file;
  356. }
  357. if (isDirectory)
  358. {
  359. _logger.LogInformation("Deleting plugin directory {0}", path);
  360. Directory.Delete(path, true);
  361. }
  362. else
  363. {
  364. _logger.LogInformation("Deleting plugin file {0}", path);
  365. _fileSystem.DeleteFile(path);
  366. }
  367. var list = _config.Configuration.UninstalledPlugins.ToList();
  368. var filename = Path.GetFileName(path);
  369. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  370. {
  371. list.Add(filename);
  372. _config.Configuration.UninstalledPlugins = list.ToArray();
  373. _config.SaveConfiguration();
  374. }
  375. PluginUninstalled?.Invoke(this, plugin);
  376. _applicationHost.NotifyPendingRestart();
  377. }
  378. /// <inheritdoc/>
  379. public bool CancelInstallation(Guid id)
  380. {
  381. lock (_currentInstallationsLock)
  382. {
  383. var install = _currentInstallations.Find(x => x.info.Guid == id);
  384. if (install == default((InstallationInfo, CancellationTokenSource)))
  385. {
  386. return false;
  387. }
  388. install.token.Cancel();
  389. _currentInstallations.Remove(install);
  390. return true;
  391. }
  392. }
  393. /// <inheritdoc />
  394. public void Dispose()
  395. {
  396. Dispose(true);
  397. GC.SuppressFinalize(this);
  398. }
  399. /// <summary>
  400. /// Releases unmanaged and optionally managed resources.
  401. /// </summary>
  402. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  403. protected virtual void Dispose(bool dispose)
  404. {
  405. if (dispose)
  406. {
  407. lock (_currentInstallationsLock)
  408. {
  409. foreach (var tuple in _currentInstallations)
  410. {
  411. tuple.token.Dispose();
  412. }
  413. _currentInstallations.Clear();
  414. }
  415. }
  416. }
  417. }
  418. }