InstallationManager.cs 19 KB

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