InstallationManager.cs 19 KB

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