PluginSecurityManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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*/ "http://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. if (value != LicenseFile.RegKey)
  132. {
  133. LicenseFile.RegKey = value;
  134. LicenseFile.Save();
  135. // re-load registration info
  136. Task.Run(() => LoadAllRegistrationInfo());
  137. }
  138. }
  139. }
  140. public async Task<SupporterInfo> GetSupporterInfo()
  141. {
  142. var key = SupporterKey;
  143. if (string.IsNullOrWhiteSpace(key))
  144. {
  145. return new SupporterInfo();
  146. }
  147. var data = new Dictionary<string, string>
  148. {
  149. { "key", key },
  150. };
  151. var url = MbAdmin.HttpsUrl + "/service/supporter/retrieve";
  152. using (var stream = await _httpClient.Post(url, data, CancellationToken.None).ConfigureAwait(false))
  153. {
  154. var response = _jsonSerializer.DeserializeFromStream<SuppporterInfoResponse>(stream);
  155. var info = new SupporterInfo
  156. {
  157. Email = response.email,
  158. PlanType = response.planType,
  159. SupporterKey = response.supporterKey,
  160. IsActiveSupporter = IsMBSupporter
  161. };
  162. if (!string.IsNullOrWhiteSpace(response.expDate))
  163. {
  164. DateTime parsedDate;
  165. if (DateTime.TryParse(response.expDate, out parsedDate))
  166. {
  167. info.ExpirationDate = parsedDate;
  168. }
  169. else
  170. {
  171. _logger.Error("Failed to parse expDate: {0}", response.expDate);
  172. }
  173. }
  174. if (!string.IsNullOrWhiteSpace(response.regDate))
  175. {
  176. DateTime parsedDate;
  177. if (DateTime.TryParse(response.regDate, out parsedDate))
  178. {
  179. info.RegistrationDate = parsedDate;
  180. }
  181. else
  182. {
  183. _logger.Error("Failed to parse regDate: {0}", response.regDate);
  184. }
  185. }
  186. info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey);
  187. return info;
  188. }
  189. }
  190. /// <summary>
  191. /// Register an app store sale with our back-end. It will validate the transaction with the store
  192. /// and then register the proper feature and then fill in the supporter key on success.
  193. /// </summary>
  194. /// <param name="parameters">Json parameters to send to admin server</param>
  195. public async Task RegisterAppStoreSale(string parameters)
  196. {
  197. var options = new HttpRequestOptions()
  198. {
  199. Url = AppstoreRegUrl,
  200. CancellationToken = CancellationToken.None
  201. };
  202. options.RequestHeaders.Add("X-Emby-Token", _appHost.SystemId);
  203. options.RequestContent = parameters;
  204. options.RequestContentType = "application/json";
  205. try
  206. {
  207. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  208. {
  209. var reg = _jsonSerializer.DeserializeFromStream<RegRecord>(response.Content);
  210. if (reg == null)
  211. {
  212. var msg = "Result from appstore registration was null.";
  213. _logger.Error(msg);
  214. throw new ApplicationException(msg);
  215. }
  216. if (!String.IsNullOrEmpty(reg.key))
  217. {
  218. SupporterKey = reg.key;
  219. }
  220. }
  221. }
  222. catch (ApplicationException)
  223. {
  224. SaveAppStoreInfo(parameters);
  225. throw;
  226. }
  227. catch (HttpException e)
  228. {
  229. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  230. if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired)
  231. {
  232. throw new PaymentRequiredException();
  233. }
  234. throw new ApplicationException("Error registering store sale");
  235. }
  236. catch (Exception e)
  237. {
  238. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  239. SaveAppStoreInfo(parameters);
  240. //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
  241. throw new ApplicationException("Error registering store sale");
  242. }
  243. }
  244. private void SaveAppStoreInfo(string info)
  245. {
  246. // Save all transaction information to a file
  247. try
  248. {
  249. File.WriteAllText(Path.Combine(_appPaths.ProgramDataPath, "apptrans-error.txt"), info);
  250. }
  251. catch (IOException)
  252. {
  253. }
  254. }
  255. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  256. string mb2Equivalent = null,
  257. string version = null)
  258. {
  259. var lastChecked = LicenseFile.LastChecked(feature);
  260. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  261. var reg = new RegRecord
  262. {
  263. // Cache the result for up to a week
  264. registered = lastChecked > DateTime.UtcNow.AddDays(-7)
  265. };
  266. var success = reg.registered;
  267. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)))
  268. {
  269. var data = new Dictionary<string, string>
  270. {
  271. { "feature", feature },
  272. { "key", SupporterKey },
  273. { "mac", _appHost.SystemId },
  274. { "systemid", _appHost.SystemId },
  275. { "mb2equiv", mb2Equivalent },
  276. { "ver", version },
  277. { "platform", _appHost.OperatingSystemDisplayName },
  278. { "isservice", _appHost.IsRunningAsService.ToString().ToLower() }
  279. };
  280. try
  281. {
  282. using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
  283. {
  284. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  285. success = true;
  286. }
  287. if (reg.registered)
  288. {
  289. LicenseFile.AddRegCheck(feature);
  290. }
  291. else
  292. {
  293. LicenseFile.RemoveRegCheck(feature);
  294. }
  295. }
  296. catch (Exception e)
  297. {
  298. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  299. }
  300. }
  301. var record = new MBRegistrationRecord
  302. {
  303. IsRegistered = reg.registered,
  304. ExpirationDate = reg.expDate,
  305. RegChecked = true,
  306. RegError = !success
  307. };
  308. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  309. record.IsValid = !record.RegChecked || (record.IsRegistered || record.TrialVersion);
  310. return record;
  311. }
  312. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  313. {
  314. //don't set this until we've successfully obtained exp date
  315. if (!regChecked)
  316. {
  317. return false;
  318. }
  319. var isInTrial = expirationDate > DateTime.UtcNow;
  320. return (isInTrial && !isRegistered);
  321. }
  322. /// <summary>
  323. /// Resets the supporter info.
  324. /// </summary>
  325. private void ResetSupporterInfo()
  326. {
  327. _isMbSupporter = null;
  328. _isMbSupporterInitialized = false;
  329. }
  330. }
  331. }