InstallationManager.cs 18 KB

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