PluginSecurityManager.cs 12 KB

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