LicenseSystem.cpp 17 KB

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