InstallationManager.cs 18 KB

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