2
0

InstallationManager.cs 19 KB

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