InstallationManager.cs 18 KB

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