PluginSecurityManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. using System.IO;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Security;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using MediaBrowser.Model.Net;
  15. namespace MediaBrowser.Common.Implementations.Security
  16. {
  17. /// <summary>
  18. /// Class PluginSecurityManager
  19. /// </summary>
  20. public class PluginSecurityManager : ISecurityManager
  21. {
  22. private const string MBValidateUrl = MbAdmin.HttpsUrl + "service/registration/validate";
  23. private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "https://mb3admin.com/admin/service/appstore/register";
  24. /// <summary>
  25. /// The _is MB supporter
  26. /// </summary>
  27. private bool? _isMbSupporter;
  28. /// <summary>
  29. /// The _is MB supporter initialized
  30. /// </summary>
  31. private bool _isMbSupporterInitialized;
  32. /// <summary>
  33. /// The _is MB supporter sync lock
  34. /// </summary>
  35. private object _isMbSupporterSyncLock = new object();
  36. /// <summary>
  37. /// Gets a value indicating whether this instance is MB supporter.
  38. /// </summary>
  39. /// <value><c>true</c> if this instance is MB supporter; otherwise, <c>false</c>.</value>
  40. public bool IsMBSupporter
  41. {
  42. get
  43. {
  44. LazyInitializer.EnsureInitialized(ref _isMbSupporter, ref _isMbSupporterInitialized, ref _isMbSupporterSyncLock, () => GetSupporterRegistrationStatus().Result.IsRegistered);
  45. return _isMbSupporter.Value;
  46. }
  47. }
  48. private MBLicenseFile _licenseFile;
  49. private MBLicenseFile LicenseFile
  50. {
  51. get { return _licenseFile ?? (_licenseFile = new MBLicenseFile(_appPaths)); }
  52. }
  53. private readonly IHttpClient _httpClient;
  54. private readonly IJsonSerializer _jsonSerializer;
  55. private readonly IApplicationHost _appHost;
  56. private readonly ILogger _logger;
  57. private readonly IApplicationPaths _appPaths;
  58. private IEnumerable<IRequiresRegistration> _registeredEntities;
  59. protected IEnumerable<IRequiresRegistration> RegisteredEntities
  60. {
  61. get
  62. {
  63. return _registeredEntities ?? (_registeredEntities = _appHost.GetExports<IRequiresRegistration>());
  64. }
  65. }
  66. /// <summary>
  67. /// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
  68. /// </summary>
  69. public PluginSecurityManager(IApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer,
  70. IApplicationPaths appPaths, ILogManager logManager)
  71. {
  72. if (httpClient == null)
  73. {
  74. throw new ArgumentNullException("httpClient");
  75. }
  76. _appHost = appHost;
  77. _httpClient = httpClient;
  78. _jsonSerializer = jsonSerializer;
  79. _appPaths = appPaths;
  80. _logger = logManager.GetLogger("SecurityManager");
  81. }
  82. /// <summary>
  83. /// Load all registration info for all entities that require registration
  84. /// </summary>
  85. /// <returns></returns>
  86. public async Task LoadAllRegistrationInfo()
  87. {
  88. var tasks = new List<Task>();
  89. ResetSupporterInfo();
  90. tasks.AddRange(RegisteredEntities.Select(i => i.LoadRegistrationInfoAsync()));
  91. await Task.WhenAll(tasks);
  92. }
  93. /// <summary>
  94. /// Gets the registration status.
  95. /// This overload supports existing plug-ins.
  96. /// </summary>
  97. /// <param name="feature">The feature.</param>
  98. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  99. /// <returns>Task{MBRegistrationRecord}.</returns>
  100. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent = null)
  101. {
  102. return GetRegistrationStatusInternal(feature, mb2Equivalent);
  103. }
  104. /// <summary>
  105. /// Gets the registration status.
  106. /// </summary>
  107. /// <param name="feature">The feature.</param>
  108. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  109. /// <param name="version">The version of this feature</param>
  110. /// <returns>Task{MBRegistrationRecord}.</returns>
  111. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent, string version)
  112. {
  113. return GetRegistrationStatusInternal(feature, mb2Equivalent, version);
  114. }
  115. private Task<MBRegistrationRecord> GetSupporterRegistrationStatus()
  116. {
  117. return GetRegistrationStatusInternal("MBSupporter", null, _appHost.ApplicationVersion.ToString());
  118. }
  119. /// <summary>
  120. /// Gets or sets the supporter key.
  121. /// </summary>
  122. /// <value>The supporter key.</value>
  123. public string SupporterKey
  124. {
  125. get
  126. {
  127. return LicenseFile.RegKey;
  128. }
  129. set
  130. {
  131. var newValue = value;
  132. if (newValue != null)
  133. {
  134. newValue = newValue.Trim();
  135. }
  136. if (newValue != LicenseFile.RegKey)
  137. {
  138. LicenseFile.RegKey = newValue;
  139. LicenseFile.Save();
  140. // re-load registration info
  141. Task.Run(() => LoadAllRegistrationInfo());
  142. }
  143. }
  144. }
  145. /// <summary>
  146. /// Register an app store sale with our back-end. It will validate the transaction with the store
  147. /// and then register the proper feature and then fill in the supporter key on success.
  148. /// </summary>
  149. /// <param name="parameters">Json parameters to send to admin server</param>
  150. public async Task RegisterAppStoreSale(string parameters)
  151. {
  152. var options = new HttpRequestOptions()
  153. {
  154. Url = AppstoreRegUrl,
  155. CancellationToken = CancellationToken.None,
  156. BufferContent = false
  157. };
  158. options.RequestHeaders.Add("X-Emby-Token", _appHost.SystemId);
  159. options.RequestContent = parameters;
  160. options.RequestContentType = "application/json";
  161. try
  162. {
  163. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  164. {
  165. var reg = _jsonSerializer.DeserializeFromStream<RegRecord>(response.Content);
  166. if (reg == null)
  167. {
  168. var msg = "Result from appstore registration was null.";
  169. _logger.Error(msg);
  170. throw new ApplicationException(msg);
  171. }
  172. if (!String.IsNullOrEmpty(reg.key))
  173. {
  174. SupporterKey = reg.key;
  175. }
  176. }
  177. }
  178. catch (ApplicationException)
  179. {
  180. SaveAppStoreInfo(parameters);
  181. throw;
  182. }
  183. catch (HttpException e)
  184. {
  185. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  186. if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired)
  187. {
  188. throw new PaymentRequiredException();
  189. }
  190. throw new ApplicationException("Error registering store sale");
  191. }
  192. catch (Exception e)
  193. {
  194. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  195. SaveAppStoreInfo(parameters);
  196. //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
  197. throw new ApplicationException("Error registering store sale");
  198. }
  199. }
  200. private void SaveAppStoreInfo(string info)
  201. {
  202. // Save all transaction information to a file
  203. try
  204. {
  205. File.WriteAllText(Path.Combine(_appPaths.ProgramDataPath, "apptrans-error.txt"), info);
  206. }
  207. catch (IOException)
  208. {
  209. }
  210. }
  211. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  212. string mb2Equivalent = null,
  213. string version = null)
  214. {
  215. var lastChecked = LicenseFile.LastChecked(feature);
  216. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  217. var reg = new RegRecord
  218. {
  219. // Cache the result for up to a week
  220. registered = lastChecked > DateTime.UtcNow.AddDays(-7)
  221. };
  222. var success = reg.registered;
  223. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)))
  224. {
  225. var data = new Dictionary<string, string>
  226. {
  227. { "feature", feature },
  228. { "key", SupporterKey },
  229. { "mac", _appHost.SystemId },
  230. { "systemid", _appHost.SystemId },
  231. { "mb2equiv", mb2Equivalent },
  232. { "ver", version },
  233. { "platform", _appHost.OperatingSystemDisplayName },
  234. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  235. };
  236. try
  237. {
  238. var options = new HttpRequestOptions
  239. {
  240. Url = MBValidateUrl,
  241. // Seeing block length errors
  242. EnableHttpCompression = false,
  243. BufferContent = false
  244. };
  245. options.SetPostData(data);
  246. using (var json = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  247. {
  248. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  249. success = true;
  250. }
  251. if (reg.registered)
  252. {
  253. LicenseFile.AddRegCheck(feature);
  254. }
  255. else
  256. {
  257. LicenseFile.RemoveRegCheck(feature);
  258. }
  259. }
  260. catch (Exception e)
  261. {
  262. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  263. }
  264. }
  265. var record = new MBRegistrationRecord
  266. {
  267. IsRegistered = reg.registered,
  268. ExpirationDate = reg.expDate,
  269. RegChecked = true,
  270. RegError = !success
  271. };
  272. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  273. record.IsValid = !record.RegChecked || record.IsRegistered || record.TrialVersion;
  274. return record;
  275. }
  276. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  277. {
  278. //don't set this until we've successfully obtained exp date
  279. if (!regChecked)
  280. {
  281. return false;
  282. }
  283. var isInTrial = expirationDate > DateTime.UtcNow;
  284. return isInTrial && !isRegistered;
  285. }
  286. /// <summary>
  287. /// Resets the supporter info.
  288. /// </summary>
  289. private void ResetSupporterInfo()
  290. {
  291. _isMbSupporter = null;
  292. _isMbSupporterInitialized = false;
  293. }
  294. }
  295. }