LicenseSystem.cpp 17 KB

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