InstallationManager.cs 18 KB

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