2
0

InstallationManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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.Common.System;
  19. using MediaBrowser.Controller.Configuration;
  20. using MediaBrowser.Model.Events;
  21. using MediaBrowser.Model.IO;
  22. using MediaBrowser.Model.Serialization;
  23. using MediaBrowser.Model.Updates;
  24. using Microsoft.Extensions.Configuration;
  25. using Microsoft.Extensions.Logging;
  26. using MediaBrowser.Model.System;
  27. namespace Emby.Server.Implementations.Updates
  28. {
  29. /// <summary>
  30. /// Manages all install, uninstall, and update operations for the system and individual plugins.
  31. /// </summary>
  32. public class InstallationManager : IInstallationManager
  33. {
  34. /// <summary>
  35. /// The key for a setting that specifies a URL for the plugin repository JSON manifest.
  36. /// </summary>
  37. public const string PluginManifestUrlKey = "InstallationManager:PluginManifestUrl";
  38. /// <summary>
  39. /// The logger.
  40. /// </summary>
  41. private readonly ILogger<InstallationManager> _logger;
  42. private readonly IApplicationPaths _appPaths;
  43. private readonly IHttpClient _httpClient;
  44. private readonly IJsonSerializer _jsonSerializer;
  45. private readonly IServerConfigurationManager _config;
  46. private readonly IFileSystem _fileSystem;
  47. /// <summary>
  48. /// Gets the application host.
  49. /// </summary>
  50. /// <value>The application host.</value>
  51. private readonly IApplicationHost _applicationHost;
  52. private readonly IZipClient _zipClient;
  53. private readonly IConfiguration _appConfig;
  54. private readonly object _currentInstallationsLock = new object();
  55. /// <summary>
  56. /// The current installations.
  57. /// </summary>
  58. private readonly List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations;
  59. /// <summary>
  60. /// The completed installations.
  61. /// </summary>
  62. private readonly ConcurrentBag<InstallationInfo> _completedInstallationsInternal;
  63. public InstallationManager(
  64. ILogger<InstallationManager> logger,
  65. IApplicationHost appHost,
  66. IApplicationPaths appPaths,
  67. IHttpClient httpClient,
  68. IJsonSerializer jsonSerializer,
  69. IServerConfigurationManager config,
  70. IFileSystem fileSystem,
  71. IZipClient zipClient,
  72. IConfiguration appConfig)
  73. {
  74. if (logger == null)
  75. {
  76. throw new ArgumentNullException(nameof(logger));
  77. }
  78. _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>();
  79. _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>();
  80. _logger = logger;
  81. _applicationHost = appHost;
  82. _appPaths = appPaths;
  83. _httpClient = httpClient;
  84. _jsonSerializer = jsonSerializer;
  85. _config = config;
  86. _fileSystem = fileSystem;
  87. _zipClient = zipClient;
  88. _appConfig = appConfig;
  89. }
  90. /// <inheritdoc />
  91. public event EventHandler<InstallationInfo> PackageInstalling;
  92. /// <inheritdoc />
  93. public event EventHandler<InstallationInfo> PackageInstallationCompleted;
  94. /// <inheritdoc />
  95. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  96. /// <inheritdoc />
  97. public event EventHandler<InstallationInfo> PackageInstallationCancelled;
  98. /// <inheritdoc />
  99. public event EventHandler<IPlugin> PluginUninstalled;
  100. /// <inheritdoc />
  101. public event EventHandler<InstallationInfo> PluginUpdated;
  102. /// <inheritdoc />
  103. public event EventHandler<InstallationInfo> PluginInstalled;
  104. /// <inheritdoc />
  105. public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
  106. /// <inheritdoc />
  107. public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
  108. {
  109. var manifestUrl = _appConfig.GetValue<string>(PluginManifestUrlKey);
  110. try
  111. {
  112. using (var response = await _httpClient.SendAsync(
  113. new HttpRequestOptions
  114. {
  115. Url = manifestUrl,
  116. CancellationToken = cancellationToken,
  117. CacheMode = CacheMode.Unconditional,
  118. CacheLength = TimeSpan.FromMinutes(3)
  119. },
  120. HttpMethod.Get).ConfigureAwait(false))
  121. using (Stream stream = response.Content)
  122. {
  123. try
  124. {
  125. return await _jsonSerializer.DeserializeFromStreamAsync<IReadOnlyList<PackageInfo>>(stream).ConfigureAwait(false);
  126. }
  127. catch (SerializationException ex)
  128. {
  129. const string LogTemplate =
  130. "Failed to deserialize the plugin manifest retrieved from {PluginManifestUrl}. If you " +
  131. "have specified a custom plugin repository manifest URL with --plugin-manifest-url or " +
  132. PluginManifestUrlKey + ", please ensure that it is correct.";
  133. _logger.LogError(ex, LogTemplate, manifestUrl);
  134. throw;
  135. }
  136. }
  137. }
  138. catch (UriFormatException ex)
  139. {
  140. const string LogTemplate =
  141. "The URL configured for the plugin repository manifest URL is not valid: {PluginManifestUrl}. " +
  142. "Please check the URL configured by --plugin-manifest-url or " + PluginManifestUrlKey;
  143. _logger.LogError(ex, LogTemplate, manifestUrl);
  144. throw;
  145. }
  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. // Version folder as they cannot be overwritten in Windows.
  332. targetDir += package.Version.ToString();
  333. if (Directory.Exists(targetDir))
  334. {
  335. try
  336. {
  337. Directory.Delete(targetDir, true);
  338. }
  339. catch
  340. {
  341. // Ignore any exceptions.
  342. }
  343. }
  344. stream.Position = 0;
  345. _zipClient.ExtractAllFromZip(stream, targetDir, true);
  346. }
  347. #pragma warning restore CA5351
  348. }
  349. /// <summary>
  350. /// Uninstalls a plugin.
  351. /// </summary>
  352. /// <param name="plugin">The plugin.</param>
  353. public void UninstallPlugin(IPlugin plugin)
  354. {
  355. plugin.OnUninstalling();
  356. // Remove it the quick way for now
  357. _applicationHost.RemovePlugin(plugin);
  358. var path = plugin.AssemblyFilePath;
  359. bool isDirectory = false;
  360. // Check if we have a plugin directory we should remove too
  361. if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath)
  362. {
  363. path = Path.GetDirectoryName(plugin.AssemblyFilePath);
  364. isDirectory = true;
  365. }
  366. // Make this case-insensitive to account for possible incorrect assembly naming
  367. var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
  368. .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
  369. if (!string.IsNullOrWhiteSpace(file))
  370. {
  371. path = file;
  372. }
  373. try
  374. {
  375. if (isDirectory)
  376. {
  377. _logger.LogInformation("Deleting plugin directory {0}", path);
  378. Directory.Delete(path, true);
  379. }
  380. else
  381. {
  382. _logger.LogInformation("Deleting plugin file {0}", path);
  383. _fileSystem.DeleteFile(path);
  384. }
  385. }
  386. catch
  387. {
  388. // Ignore file errors.
  389. }
  390. var list = _config.Configuration.UninstalledPlugins.ToList();
  391. var filename = Path.GetFileName(path);
  392. if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase))
  393. {
  394. list.Add(filename);
  395. _config.Configuration.UninstalledPlugins = list.ToArray();
  396. _config.SaveConfiguration();
  397. }
  398. PluginUninstalled?.Invoke(this, plugin);
  399. _applicationHost.NotifyPendingRestart();
  400. }
  401. /// <inheritdoc/>
  402. public bool CancelInstallation(Guid id)
  403. {
  404. lock (_currentInstallationsLock)
  405. {
  406. var install = _currentInstallations.Find(x => x.info.Guid == id);
  407. if (install == default((InstallationInfo, CancellationTokenSource)))
  408. {
  409. return false;
  410. }
  411. install.token.Cancel();
  412. _currentInstallations.Remove(install);
  413. return true;
  414. }
  415. }
  416. /// <inheritdoc />
  417. public void Dispose()
  418. {
  419. Dispose(true);
  420. GC.SuppressFinalize(this);
  421. }
  422. /// <summary>
  423. /// Releases unmanaged and optionally managed resources.
  424. /// </summary>
  425. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param>
  426. protected virtual void Dispose(bool dispose)
  427. {
  428. if (dispose)
  429. {
  430. lock (_currentInstallationsLock)
  431. {
  432. foreach (var tuple in _currentInstallations)
  433. {
  434. tuple.token.Dispose();
  435. }
  436. _currentInstallations.Clear();
  437. }
  438. }
  439. }
  440. }
  441. }