LicenseSystem.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  2. // Please see LICENSE.md in repository root for license information
  3. // https://github.com/AtomicGameEngine/AtomicGameEngine
  4. // BEGIN LICENSE MANAGEMENT
  5. #ifdef ATOMIC_PLATFORM_WINDOWS
  6. #ifndef _MSC_VER
  7. #define _WIN32_IE 0x501
  8. #endif
  9. #include <windows.h>
  10. #include <shellapi.h>
  11. #include <direct.h>
  12. #include <shlobj.h>
  13. #include <sys/types.h>
  14. #include <sys/utime.h>
  15. #endif
  16. #include <Atomic/Core/CoreEvents.h>
  17. #include <Atomic/Core/Context.h>
  18. #include <Atomic/Core/Timer.h>
  19. #include <Atomic/IO/FileSystem.h>
  20. #include <Atomic/IO/File.h>
  21. #include <Atomic/IO/Log.h>
  22. #include "LicenseEvents.h"
  23. #include "LicenseSystem.h"
  24. #include <Poco/MD5Engine.h>
  25. #include <Poco/File.h>
  26. namespace ToolCore
  27. {
  28. LicenseSystem::LicenseSystem(Context* context) :
  29. Object(context)
  30. , eulaAgreementConfirmed_(false)
  31. {
  32. FileSystem* filesystem = GetSubsystem<FileSystem>();
  33. licenseFilePath_ = filesystem->GetAppPreferencesDir("AtomicEditor", "License");
  34. licenseFilePath_ = AddTrailingSlash(licenseFilePath_);
  35. if (!filesystem->DirExists(licenseFilePath_))
  36. {
  37. Poco::File dirs(licenseFilePath_.CString());
  38. dirs.createDirectories();
  39. }
  40. licenseCachePath_ = licenseFilePath_;
  41. licenseCachePath_ += "AtomicLicenseCache";
  42. licenseFilePath_ += "AtomicLicense";
  43. eulaAgreementPath_ = filesystem->GetAppPreferencesDir("AtomicEditor", "License");
  44. eulaAgreementPath_ = AddTrailingSlash(eulaAgreementPath_);
  45. eulaAgreementPath_ += "EulaConfirmed";
  46. ResetLicense();
  47. }
  48. LicenseSystem::~LicenseSystem()
  49. {
  50. }
  51. void LicenseSystem::Initialize()
  52. {
  53. FileSystem* filesystem = GetSubsystem<FileSystem>();
  54. eulaAgreementConfirmed_ = filesystem->FileExists(eulaAgreementPath_);
  55. if (!eulaAgreementConfirmed_)
  56. {
  57. SendEvent(E_LICENSE_EULAREQUIRED);
  58. return;
  59. }
  60. if (!LoadLicense() || !key_.Length())
  61. {
  62. ResetLicense();
  63. SendEvent(E_LICENSE_ACTIVATIONREQUIRED);
  64. return;
  65. }
  66. else
  67. {
  68. RequestServerVerification(key_);
  69. }
  70. }
  71. void LicenseSystem::LicenseAgreementConfirmed()
  72. {
  73. eulaAgreementConfirmed_ = true;
  74. SharedPtr<File> file(new File(context_, eulaAgreementPath_, FILE_WRITE));
  75. file->WriteInt(1);
  76. file->Close();
  77. /*
  78. UIModalOps* ops = GetSubsystem<UIModalOps>();
  79. ops->ShowActivation();
  80. */
  81. }
  82. String LicenseSystem::GenerateMachineID()
  83. {
  84. #if defined(ATOMIC_PLATFORM_OSX) || defined(ATOMIC_PLATFORM_LINUX)
  85. String path = getenv("HOME");
  86. #else
  87. wchar_t pathName[MAX_PATH];
  88. pathName[0] = 0;
  89. SHGetSpecialFolderPathW(0, pathName, CSIDL_PERSONAL, 0);
  90. String path(pathName);
  91. #endif
  92. Poco::MD5Engine md5;
  93. md5.update(path.CString(), path.Length());
  94. String id = Poco::MD5Engine::digestToHex(md5.digest()).c_str();
  95. return id;
  96. }
  97. void LicenseSystem::ResetLicense()
  98. {
  99. key_ = "";
  100. licenseWindows_ = false;
  101. licenseMac_ = false;
  102. licenseAndroid_ = false;
  103. licenseIOS_ = false;
  104. licenseHTML5_ = false;
  105. licenseModule3D_ = false;
  106. }
  107. bool LicenseSystem::LoadLicense()
  108. {
  109. ResetLicense();
  110. FileSystem* filesystem = GetSubsystem<FileSystem>();
  111. if (!filesystem->FileExists(licenseFilePath_))
  112. return false;
  113. SharedPtr<File> file(new File(context_, licenseFilePath_, FILE_READ));
  114. file->ReadInt(); // version
  115. String key = file->ReadString();
  116. if (!ValidateKey(key))
  117. return false;
  118. key_ = key;
  119. licenseWindows_ = file->ReadBool();
  120. licenseMac_ = file->ReadBool();
  121. licenseAndroid_ = file->ReadBool();
  122. licenseIOS_ = file->ReadBool();
  123. licenseHTML5_ = file->ReadBool();
  124. licenseModule3D_ = file->ReadBool();
  125. return true;
  126. }
  127. bool LicenseSystem::ValidateKey(const String& key)
  128. {
  129. if (!key.StartsWith("ATOMIC-"))
  130. return false;
  131. Vector<String> elements = key.Split('-');
  132. if (elements.Size() != 5)
  133. return false;
  134. for (unsigned i = 1; i < elements.Size(); i++)
  135. {
  136. String element = elements[i];
  137. if (element.Length() != 4)
  138. return false;
  139. for (unsigned j = 0; j < 4; j++)
  140. {
  141. char c = element[j];
  142. if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
  143. continue;
  144. return false;
  145. }
  146. }
  147. return true;
  148. }
  149. void LicenseSystem::SaveLicense()
  150. {
  151. SharedPtr<File> file(new File(context_, licenseFilePath_, FILE_WRITE));
  152. file->WriteInt(1); // version
  153. file->WriteString(key_);
  154. file->WriteBool(licenseWindows_);
  155. file->WriteBool(licenseMac_);
  156. file->WriteBool(licenseAndroid_);
  157. file->WriteBool(licenseIOS_);
  158. file->WriteBool(licenseHTML5_);
  159. file->WriteBool(licenseModule3D_);
  160. file->Close();
  161. }
  162. void LicenseSystem::RemoveLicense()
  163. {
  164. FileSystem* filesystem = GetSubsystem<FileSystem>();
  165. if (filesystem->FileExists(licenseFilePath_))
  166. {
  167. filesystem->Delete(licenseFilePath_);
  168. }
  169. if (filesystem->FileExists(licenseCachePath_))
  170. {
  171. filesystem->Delete(licenseCachePath_);
  172. }
  173. }
  174. bool LicenseSystem::IsStandardLicense()
  175. {
  176. return !licenseAndroid_;
  177. }
  178. void LicenseSystem::RequestServerVerification(const String& key)
  179. {
  180. if (serverVerification_.NotNull())
  181. {
  182. LOGERROR("LicenseSystem::RequestServerLicense - request already exists");
  183. return;
  184. }
  185. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  186. if (fileSystem->FileExists(licenseCachePath_))
  187. {
  188. Time* time = GetSubsystem<Time>();
  189. unsigned currentTime = time->GetTimeSinceEpoch();
  190. unsigned fileTime = fileSystem->GetLastModifiedTime(licenseCachePath_);
  191. unsigned deltaMinutes = (currentTime - fileTime)/60;
  192. if (deltaMinutes < 1)
  193. {
  194. LOGINFOF("%u minutes, using cached license", deltaMinutes);
  195. SendEvent(E_LICENSE_SUCCESS);
  196. return;
  197. }
  198. }
  199. LOGINFO("LicenseSystem::RequestServerLicense - requesting verification");
  200. key_ = key;
  201. CurlManager* cm = GetSubsystem<CurlManager>();
  202. String post;
  203. String id = GenerateMachineID();
  204. post.AppendWithFormat("key=%s&id=%s", key.CString(), id.CString());
  205. serverVerification_ = cm->MakeRequest("https://store.atomicgameengine.com/licenses/license_verify.php", post);
  206. SubscribeToEvent(serverVerification_, E_CURLCOMPLETE, HANDLER(LicenseSystem, HandleVerification));
  207. }
  208. int LicenseSystem::ParseResponse(const String& response, LicenseParse& parse)
  209. {
  210. LOGINFOF("%s", response.CString());
  211. if (response.StartsWith("AC_ACTIVATIONSEXCEEDED"))
  212. {
  213. return 1;
  214. }
  215. if (response.StartsWith("AC_IDNOTACTIVATED"))
  216. {
  217. return 4;
  218. }
  219. if (response.StartsWith("AC_FAILED"))
  220. {
  221. return 2;
  222. }
  223. if (!response.StartsWith("WINDOWS"))
  224. {
  225. LOGERRORF("Error Parsing Server Response %s", response.CString());
  226. return 3;
  227. }
  228. String codes = response;
  229. codes.Replace("\n", "");
  230. codes.Replace("\r", "");
  231. Vector<String> cvector = codes.Split(' ');
  232. for (unsigned i = 0; i < cvector.Size(); i++)
  233. {
  234. Vector<String> feature = cvector[i].Split('=');
  235. if (feature.Size() != 2)
  236. continue;
  237. if (feature[0] == "WINDOWS")
  238. parse.licenseWindows_ = !feature[1].StartsWith("0");
  239. else if (feature[0] == "MAC")
  240. parse.licenseMac_ = !feature[1].StartsWith("0");
  241. else if (feature[0] == "ANDROID")
  242. parse.licenseAndroid_ = !feature[1].StartsWith("0");
  243. else if (feature[0] == "IOS")
  244. parse.licenseIOS_ = !feature[1].StartsWith("0");
  245. else if (feature[0] == "HTML5")
  246. parse.licenseHTML5_ = !feature[1].StartsWith("0");
  247. else if (feature[0] == "THREED")
  248. parse.licenseModule3D_ = !feature[1].StartsWith("0");
  249. }
  250. return 0;
  251. }
  252. void LicenseSystem::Activate(const String& key, const LicenseParse& parse)
  253. {
  254. key_ = key;
  255. licenseWindows_ = parse.licenseWindows_;
  256. licenseMac_ = parse.licenseMac_;
  257. licenseAndroid_ = parse.licenseAndroid_;
  258. licenseIOS_= parse.licenseIOS_;
  259. licenseHTML5_= parse.licenseHTML5_;
  260. licenseModule3D_= parse.licenseModule3D_;
  261. SaveLicense();
  262. }
  263. SharedPtr<CurlRequest>& LicenseSystem::Deactivate()
  264. {
  265. if (deactivate_.NotNull())
  266. {
  267. LOGERROR("LicenseSystem::Deactivate - request already exists");
  268. return deactivate_;
  269. }
  270. if (!key_.Length())
  271. {
  272. LOGERROR("LicenseSystem::Deactivate - zero length key");
  273. return deactivate_;
  274. }
  275. CurlManager* cm = GetSubsystem<CurlManager>();
  276. String post;
  277. String id = GenerateMachineID();
  278. post.AppendWithFormat("key=%s&id=%s", key_.CString(), id.CString());
  279. deactivate_ = cm->MakeRequest("https://store.atomicgameengine.com/licenses/license_deactivate.php", post);
  280. SubscribeToEvent(deactivate_, E_CURLCOMPLETE, HANDLER(LicenseSystem, HandleDeactivate));
  281. return deactivate_;
  282. }
  283. void LicenseSystem::CreateOrUpdateLicenseCache()
  284. {
  285. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  286. Time* time = GetSubsystem<Time>();
  287. if (!fileSystem->FileExists(licenseCachePath_))
  288. {
  289. SharedPtr<File> file(new File(context_, licenseCachePath_, FILE_WRITE));
  290. file->WriteInt(1);
  291. file->Close();
  292. }
  293. fileSystem->SetLastModifiedTime(licenseCachePath_, time->GetTimeSinceEpoch());
  294. }
  295. void LicenseSystem::HandleVerification(StringHash eventType, VariantMap& eventData)
  296. {
  297. CurlRequest* request = (CurlRequest*) (eventData[CurlComplete::P_CURLREQUEST].GetPtr());
  298. bool licenseError = false;
  299. bool resetLicense = false;
  300. if (serverVerification_.NotNull())
  301. {
  302. assert(request == serverVerification_);
  303. if (serverVerification_->GetError().Length())
  304. {
  305. LOGERRORF("Unable to verify with server: %s", serverVerification_->GetError().CString());
  306. }
  307. else
  308. {
  309. LicenseParse parse;
  310. int code = ParseResponse(serverVerification_->GetResponse(), parse);
  311. if (code == 4)
  312. {
  313. // not activated
  314. resetLicense = true;
  315. licenseError = true;
  316. }
  317. else if (code == 2)
  318. {
  319. // something is wrong with the key
  320. resetLicense = true;
  321. licenseError = true;
  322. }
  323. else if (code == 3)
  324. {
  325. // something is wrong on the activation server
  326. licenseError = true;
  327. }
  328. else if (code == 1)
  329. {
  330. // exceeded code, should not happen here as we aren't activating
  331. resetLicense = true;
  332. licenseError = true;
  333. }
  334. else if (code == 0)
  335. {
  336. // we should raise an error if there is a mismatch between local and server keys
  337. // when the local says there are more enabled than server?
  338. // otherwise, they could be being added
  339. bool mismatch = false;
  340. if (parse.licenseWindows_ != licenseWindows_)
  341. mismatch = true;
  342. if (parse.licenseMac_ != licenseMac_)
  343. mismatch = true;
  344. if (parse.licenseWindows_ != licenseWindows_)
  345. mismatch = true;
  346. if (parse.licenseAndroid_ != licenseAndroid_)
  347. mismatch = true;
  348. if (parse.licenseIOS_ != licenseIOS_)
  349. mismatch = true;
  350. if (parse.licenseHTML5_ != licenseHTML5_)
  351. mismatch = true;
  352. if (parse.licenseModule3D_ != licenseModule3D_)
  353. mismatch = true;
  354. if (mismatch)
  355. {
  356. LOGERROR("License Mismatch, reseting");
  357. licenseWindows_ = parse.licenseWindows_;
  358. licenseMac_ = parse.licenseMac_;
  359. licenseAndroid_ = parse.licenseAndroid_;
  360. licenseIOS_= parse.licenseIOS_;
  361. licenseHTML5_= parse.licenseHTML5_;
  362. licenseModule3D_= parse.licenseModule3D_;
  363. SaveLicense();
  364. }
  365. CreateOrUpdateLicenseCache();
  366. SendEvent(E_LICENSE_SUCCESS);
  367. }
  368. }
  369. UnsubscribeFromEvents(serverVerification_);
  370. serverVerification_ = 0;
  371. }
  372. if (resetLicense)
  373. {
  374. RemoveLicense();
  375. ResetLicense();
  376. }
  377. if (licenseError)
  378. {
  379. LOGINFO("There was an issue with the atomic-cli activation. Please reactivate or contact [email protected] if this problem persists");
  380. SendEvent(E_LICENSE_ERROR);
  381. }
  382. }
  383. void LicenseSystem::HandleDeactivate(StringHash eventType, VariantMap& eventData)
  384. {
  385. CurlRequest* request = (CurlRequest*) (eventData[CurlComplete::P_CURLREQUEST].GetPtr());
  386. VariantMap eventDataOut;
  387. if (deactivate_.NotNull())
  388. {
  389. assert(request == deactivate_);
  390. if (deactivate_->GetError().Length())
  391. {
  392. String msg = "Deactivation Error:\n";
  393. msg.AppendWithFormat("Unable to deactivate with server: %s", deactivate_->GetError().CString());
  394. eventDataOut[LicenseDeactivationError::P_MESSAGE] = msg;
  395. SendEvent(E_LICENSE_DEACTIVATIONERROR, eventDataOut);
  396. }
  397. else
  398. {
  399. String response = request->GetResponse();
  400. if (response.StartsWith("AC_FAILED"))
  401. {
  402. String msg = "Deactivation Error:\n";
  403. msg.AppendWithFormat("Unable to deactivate with server: %s", response.CString());
  404. eventDataOut[LicenseDeactivationError::P_MESSAGE] = msg;
  405. SendEvent(E_LICENSE_DEACTIVATIONERROR, eventDataOut);
  406. }
  407. else if (response.StartsWith("AC_NOTACTIVATED") || response.StartsWith("AC_SUCCESS"))
  408. {
  409. ResetLicense();
  410. RemoveLicense();
  411. SendEvent(E_LICENSE_DEACTIVATIONSUCCESS);
  412. }
  413. }
  414. UnsubscribeFromEvents(deactivate_);
  415. deactivate_ = 0;
  416. }
  417. }
  418. void LicenseSystem::HandleActivationResult(StringHash eventType, VariantMap& eventData)
  419. {
  420. VariantMap eventDataOut;
  421. if (serverActivation_->GetError().Length())
  422. {
  423. String errorMessage;
  424. errorMessage.AppendWithFormat("There was an error contacting the activation server\n\n%s", serverActivation_->GetError().CString());
  425. eventDataOut[LicenseActivationError::P_MESSAGE] = errorMessage;
  426. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  427. return;
  428. }
  429. else
  430. {
  431. LicenseParse parse;
  432. int code = ParseResponse(serverActivation_->GetResponse(), parse);
  433. if (code == 0)
  434. {
  435. Activate(key_, parse);
  436. SendEvent(E_LICENSE_ACTIVATIONSUCCESS);
  437. }
  438. else if (code == 1)
  439. {
  440. // TODO: check for CLI and prompt to use CLI command to return license
  441. String message = "Activations Exceeded:\nThis key has 2 activations in use.\n\nPlease return a license from Atomic Editor - Manage License menu on one of these active computers.\n\nIf you are unable to do so, please contact [email protected] providing the key to reset it";
  442. eventDataOut[LicenseActivationError::P_MESSAGE] = message;
  443. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  444. }
  445. else if (code == 2)
  446. {
  447. String message = "License Error:\nThere was a problem with the license key.\n\nPlease check the key and try again.\n\nIf the problem persists please contact [email protected]";
  448. eventDataOut[LicenseActivationError::P_MESSAGE] = message;
  449. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  450. }
  451. else if (code == 3)
  452. {
  453. String message ="Activation Server Error:\nThere was an error on the activation server\n\nIf the problem persists please contact [email protected]";
  454. eventDataOut[LicenseActivationError::P_MESSAGE] = message;
  455. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  456. }
  457. }
  458. UnsubscribeFromEvents(serverActivation_);
  459. serverActivation_ = 0;
  460. }
  461. void LicenseSystem::RequestServerActivation(const String& key)
  462. {
  463. if (serverActivation_.NotNull())
  464. {
  465. LOGERROR("UIActivation::RequestServerActivation - request already exists");
  466. return;
  467. }
  468. LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>();
  469. key_ = key;
  470. CurlManager* cm = GetSubsystem<CurlManager>();
  471. String post;
  472. String id = licenseSystem->GenerateMachineID();
  473. post.AppendWithFormat("key=%s&id=%s", key.CString(), id.CString());
  474. // todo, this should be a verify url (shouldn't auto add id)
  475. serverActivation_ = cm->MakeRequest("https://store.atomicgameengine.com/licenses/license_activate.php", post);
  476. SubscribeToEvent(serverActivation_, E_CURLCOMPLETE, HANDLER(LicenseSystem, HandleActivationResult));
  477. }
  478. }
  479. // END LICENSE MANAGEMENT