InstallationManager.cs 19 KB

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