PluginSecurityManager.cs 13 KB

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