InstallationManager.cs 19 KB

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