PluginSecurityManager.cs 12 KB

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