InstallationManager.cs 19 KB

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