InstallationManager.cs 18 KB

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