InstallationManager.cs 18 KB

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