InstallationManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net.Http;
  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 for the system and individual plugins.
  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<InstallationManager> _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<InstallationInfo> PackageInstalling;
  90. /// <inheritdoc />
  91. public event EventHandler<InstallationInfo> PackageInstallationCompleted;
  92. /// <inheritdoc />
  93. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  94. /// <inheritdoc />
  95. public event EventHandler<InstallationInfo> PackageInstallationCancelled;
  96. /// <inheritdoc />
  97. public event EventHandler<IPlugin> PluginUninstalled;
  98. /// <inheritdoc />
  99. public event EventHandler<InstallationInfo> PluginUpdated;
  100. /// <inheritdoc />
  101. public event EventHandler<InstallationInfo> 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<InstallationInfo> GetCompatibleVersions(
  163. IEnumerable<PackageInfo> availablePackages,
  164. string name = null,
  165. Guid guid = default,
  166. Version minVersion = null)
  167. {
  168. var package = FilterPackages(availablePackages, name, guid).FirstOrDefault();
  169. // Package not found in repository
  170. if (package == null)
  171. {
  172. yield break;
  173. }
  174. var appVer = _applicationHost.ApplicationVersion;
  175. var availableVersions = package.versions
  176. .Where(x => Version.Parse(x.targetAbi) <= appVer);
  177. if (minVersion != null)
  178. {
  179. availableVersions = availableVersions.Where(x => new Version(x.version) >= minVersion);
  180. }
  181. foreach (var v in availableVersions.OrderByDescending(x => x.version))
  182. {
  183. yield return new InstallationInfo
  184. {
  185. Changelog = v.changelog,
  186. Guid = new Guid(package.guid),
  187. Name = package.name,
  188. Version = new Version(v.version),
  189. SourceUrl = v.sourceUrl,
  190. Checksum = v.checksum
  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. }