PluginSecurityManager.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Net;
  10. using MediaBrowser.Common.Security;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Model.Cryptography;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using Microsoft.Extensions.Logging;
  16. using MediaBrowser.Model.Net;
  17. using MediaBrowser.Model.Serialization;
  18. namespace Emby.Server.Implementations.Security
  19. {
  20. /// <summary>
  21. /// Class PluginSecurityManager
  22. /// </summary>
  23. public class PluginSecurityManager : ISecurityManager
  24. {
  25. private const string MBValidateUrl = "https://mb3admin.local/admin/service/registration/validate";
  26. private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "https://mb3admin.local/admin/service/appstore/register";
  27. public async Task<bool> IsSupporter()
  28. {
  29. var result = await GetRegistrationStatusInternal("MBSupporter", false, _appHost.ApplicationVersion.ToString(), CancellationToken.None).ConfigureAwait(false);
  30. return result.IsRegistered;
  31. }
  32. private MBLicenseFile _licenseFile;
  33. private MBLicenseFile LicenseFile
  34. {
  35. get { return _licenseFile ?? (_licenseFile = new MBLicenseFile(_appPaths, _fileSystem, _cryptographyProvider)); }
  36. }
  37. private readonly IHttpClient _httpClient;
  38. private readonly IJsonSerializer _jsonSerializer;
  39. private readonly IServerApplicationHost _appHost;
  40. private readonly ILogger _logger;
  41. private readonly IApplicationPaths _appPaths;
  42. private readonly IFileSystem _fileSystem;
  43. private readonly ICryptoProvider _cryptographyProvider;
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
  46. /// </summary>
  47. public PluginSecurityManager(IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer,
  48. IApplicationPaths appPaths, ILoggerFactory loggerFactory, IFileSystem fileSystem, ICryptoProvider cryptographyProvider)
  49. {
  50. if (httpClient == null)
  51. {
  52. throw new ArgumentNullException("httpClient");
  53. }
  54. _appHost = appHost;
  55. _httpClient = httpClient;
  56. _jsonSerializer = jsonSerializer;
  57. _appPaths = appPaths;
  58. _fileSystem = fileSystem;
  59. _cryptographyProvider = cryptographyProvider;
  60. _logger = loggerFactory.CreateLogger("SecurityManager");
  61. }
  62. /// <summary>
  63. /// Gets the registration status.
  64. /// This overload supports existing plug-ins.
  65. /// </summary>
  66. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature)
  67. {
  68. return GetRegistrationStatusInternal(feature, false, null, CancellationToken.None);
  69. }
  70. /// <summary>
  71. /// Gets or sets the supporter key.
  72. /// </summary>
  73. /// <value>The supporter key.</value>
  74. public string SupporterKey
  75. {
  76. get
  77. {
  78. return LicenseFile.RegKey;
  79. }
  80. set
  81. {
  82. throw new Exception("Please call UpdateSupporterKey");
  83. }
  84. }
  85. public async Task UpdateSupporterKey(string newValue)
  86. {
  87. if (newValue != null)
  88. {
  89. newValue = newValue.Trim();
  90. }
  91. if (!string.Equals(newValue, LicenseFile.RegKey, StringComparison.Ordinal))
  92. {
  93. LicenseFile.RegKey = newValue;
  94. LicenseFile.Save();
  95. // Reset this
  96. await GetRegistrationStatusInternal("MBSupporter", true, _appHost.ApplicationVersion.ToString(), CancellationToken.None).ConfigureAwait(false);
  97. }
  98. }
  99. /// <summary>
  100. /// Register an app store sale with our back-end. It will validate the transaction with the store
  101. /// and then register the proper feature and then fill in the supporter key on success.
  102. /// </summary>
  103. /// <param name="parameters">Json parameters to send to admin server</param>
  104. public async Task RegisterAppStoreSale(string parameters)
  105. {
  106. var options = new HttpRequestOptions()
  107. {
  108. Url = AppstoreRegUrl,
  109. CancellationToken = CancellationToken.None,
  110. BufferContent = false
  111. };
  112. options.RequestHeaders.Add("X-Emby-Token", _appHost.SystemId);
  113. options.RequestContent = parameters;
  114. options.RequestContentType = "application/json";
  115. try
  116. {
  117. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  118. {
  119. var reg = await _jsonSerializer.DeserializeFromStreamAsync<RegRecord>(response.Content).ConfigureAwait(false);
  120. if (reg == null)
  121. {
  122. var msg = "Result from appstore registration was null.";
  123. _logger.LogError(msg);
  124. throw new ArgumentException(msg);
  125. }
  126. if (!String.IsNullOrEmpty(reg.key))
  127. {
  128. await UpdateSupporterKey(reg.key).ConfigureAwait(false);
  129. }
  130. }
  131. }
  132. catch (ArgumentException)
  133. {
  134. SaveAppStoreInfo(parameters);
  135. throw;
  136. }
  137. catch (HttpException ex)
  138. {
  139. _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT");
  140. throw new Exception("Error registering store sale");
  141. }
  142. catch (Exception ex)
  143. {
  144. _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT");
  145. SaveAppStoreInfo(parameters);
  146. //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
  147. throw new Exception("Error registering store sale");
  148. }
  149. }
  150. private void SaveAppStoreInfo(string info)
  151. {
  152. // Save all transaction information to a file
  153. try
  154. {
  155. _fileSystem.WriteAllText(Path.Combine(_appPaths.ProgramDataPath, "apptrans-error.txt"), info);
  156. }
  157. catch (IOException)
  158. {
  159. }
  160. }
  161. private SemaphoreSlim _regCheckLock = new SemaphoreSlim(1, 1);
  162. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature, bool forceCallToServer, string version, CancellationToken cancellationToken)
  163. {
  164. await _regCheckLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  165. try
  166. {
  167. var record = new MBRegistrationRecord
  168. {
  169. IsRegistered = true,
  170. RegChecked = true,
  171. TrialVersion = false,
  172. IsValid = true,
  173. RegError = false
  174. };
  175. return record;
  176. }
  177. finally
  178. {
  179. _regCheckLock.Release();
  180. }
  181. }
  182. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  183. {
  184. //don't set this until we've successfully obtained exp date
  185. if (!regChecked)
  186. {
  187. return false;
  188. }
  189. var isInTrial = expirationDate > DateTime.UtcNow;
  190. return isInTrial && !isRegistered;
  191. }
  192. }
  193. }