PluginSecurityManager.cs 12 KB

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