LicenseSystem.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. SharedPtr<CurlRequest>& LicenseSystem::Deactivate()
  262. {
  263. if (deactivate_.NotNull())
  264. {
  265. LOGERROR("LicenseSystem::Deactivate - request already exists");
  266. return deactivate_;
  267. }
  268. if (!key_.Length())
  269. {
  270. LOGERROR("LicenseSystem::Deactivate - zero length key");
  271. return deactivate_;
  272. }
  273. CurlManager* cm = GetSubsystem<CurlManager>();
  274. String post;
  275. String id = GenerateMachineID();
  276. post.AppendWithFormat("key=%s&id=%s", key_.CString(), id.CString());
  277. deactivate_ = cm->MakeRequest("https://store.atomicgameengine.com/licenses/license_deactivate.php", post);
  278. SubscribeToEvent(deactivate_, E_CURLCOMPLETE, HANDLER(LicenseSystem, HandleDeactivate));
  279. return deactivate_;
  280. }
  281. void LicenseSystem::CreateOrUpdateLicenseCache()
  282. {
  283. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  284. Time* time = GetSubsystem<Time>();
  285. if (!fileSystem->FileExists(licenseCachePath_))
  286. {
  287. SharedPtr<File> file(new File(context_, licenseCachePath_, FILE_WRITE));
  288. file->WriteInt(1);
  289. file->Close();
  290. }
  291. fileSystem->SetLastModifiedTime(licenseCachePath_, time->GetTimeSinceEpoch());
  292. }
  293. void LicenseSystem::HandleVerification(StringHash eventType, VariantMap& eventData)
  294. {
  295. CurlRequest* request = (CurlRequest*) (eventData[CurlComplete::P_CURLREQUEST].GetPtr());
  296. bool licenseError = false;
  297. bool resetLicense = false;
  298. if (serverVerification_.NotNull())
  299. {
  300. assert(request == serverVerification_);
  301. if (serverVerification_->GetError().Length())
  302. {
  303. LOGERRORF("Unable to verify with server: %s", serverVerification_->GetError().CString());
  304. }
  305. else
  306. {
  307. LicenseParse parse;
  308. int code = ParseResponse(serverVerification_->GetResponse(), parse);
  309. if (code == 4)
  310. {
  311. // not activated
  312. resetLicense = true;
  313. licenseError = true;
  314. }
  315. else if (code == 2)
  316. {
  317. // something is wrong with the key
  318. resetLicense = true;
  319. licenseError = true;
  320. }
  321. else if (code == 3)
  322. {
  323. // something is wrong on the activation server
  324. licenseError = true;
  325. }
  326. else if (code == 1)
  327. {
  328. // exceeded code, should not happen here as we aren't activating
  329. resetLicense = true;
  330. licenseError = true;
  331. }
  332. else if (code == 0)
  333. {
  334. // we should raise an error if there is a mismatch between local and server keys
  335. // when the local says there are more enabled than server?
  336. // otherwise, they could be being added
  337. bool mismatch = false;
  338. if (parse.licenseWindows_ != licenseWindows_)
  339. mismatch = true;
  340. if (parse.licenseMac_ != licenseMac_)
  341. mismatch = true;
  342. if (parse.licenseWindows_ != licenseWindows_)
  343. mismatch = true;
  344. if (parse.licenseAndroid_ != licenseAndroid_)
  345. mismatch = true;
  346. if (parse.licenseIOS_ != licenseIOS_)
  347. mismatch = true;
  348. if (parse.licenseHTML5_ != licenseHTML5_)
  349. mismatch = true;
  350. if (parse.licenseModule3D_ != licenseModule3D_)
  351. mismatch = true;
  352. if (mismatch)
  353. {
  354. LOGERROR("License Mismatch, reseting");
  355. licenseWindows_ = parse.licenseWindows_;
  356. licenseMac_ = parse.licenseMac_;
  357. licenseAndroid_ = parse.licenseAndroid_;
  358. licenseIOS_= parse.licenseIOS_;
  359. licenseHTML5_= parse.licenseHTML5_;
  360. licenseModule3D_= parse.licenseModule3D_;
  361. SaveLicense();
  362. }
  363. CreateOrUpdateLicenseCache();
  364. SendEvent(E_LICENSE_SUCCESS);
  365. }
  366. }
  367. UnsubscribeFromEvents(serverVerification_);
  368. serverVerification_ = 0;
  369. }
  370. if (resetLicense)
  371. {
  372. RemoveLicense();
  373. ResetLicense();
  374. }
  375. if (licenseError)
  376. {
  377. LOGINFO("There was an issue with the atomic-cli activation. Please reactivate or contact [email protected] if this problem persists");
  378. SendEvent(E_LICENSE_ERROR);
  379. }
  380. }
  381. void LicenseSystem::HandleDeactivate(StringHash eventType, VariantMap& eventData)
  382. {
  383. CurlRequest* request = (CurlRequest*) (eventData[CurlComplete::P_CURLREQUEST].GetPtr());
  384. VariantMap eventDataOut;
  385. if (deactivate_.NotNull())
  386. {
  387. assert(request == deactivate_);
  388. if (deactivate_->GetError().Length())
  389. {
  390. String msg = "Deactivation Error:\n";
  391. msg.AppendWithFormat("Unable to deactivate with server: %s", deactivate_->GetError().CString());
  392. eventDataOut[LicenseDeactivationError::P_MESSAGE] = msg;
  393. SendEvent(E_LICENSE_DEACTIVATIONERROR, eventDataOut);
  394. }
  395. else
  396. {
  397. String response = request->GetResponse();
  398. if (response.StartsWith("AC_FAILED"))
  399. {
  400. String msg = "Deactivation Error:\n";
  401. msg.AppendWithFormat("Unable to deactivate with server: %s", response.CString());
  402. eventDataOut[LicenseDeactivationError::P_MESSAGE] = msg;
  403. SendEvent(E_LICENSE_DEACTIVATIONERROR, eventDataOut);
  404. }
  405. else if (response.StartsWith("AC_NOTACTIVATED") || response.StartsWith("AC_SUCCESS"))
  406. {
  407. ResetLicense();
  408. RemoveLicense();
  409. SendEvent(E_LICENSE_DEACTIVATIONSUCCESS);
  410. }
  411. }
  412. UnsubscribeFromEvents(deactivate_);
  413. deactivate_ = 0;
  414. }
  415. }
  416. void LicenseSystem::HandleActivationResult(StringHash eventType, VariantMap& eventData)
  417. {
  418. VariantMap eventDataOut;
  419. if (serverActivation_->GetError().Length())
  420. {
  421. String errorMessage;
  422. errorMessage.AppendWithFormat("There was an error contacting the activation server\n\n%s", serverActivation_->GetError().CString());
  423. eventDataOut[LicenseActivationError::P_MESSAGE] = errorMessage;
  424. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  425. return;
  426. }
  427. else
  428. {
  429. LicenseParse parse;
  430. int code = ParseResponse(serverActivation_->GetResponse(), parse);
  431. if (code == 0)
  432. {
  433. Activate(key_, parse);
  434. SendEvent(E_LICENSE_ACTIVATIONSUCCESS);
  435. }
  436. else if (code == 1)
  437. {
  438. // TODO: check for CLI and prompt to use CLI command to return license
  439. 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";
  440. eventDataOut[LicenseActivationError::P_MESSAGE] = message;
  441. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  442. }
  443. else if (code == 2)
  444. {
  445. 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]";
  446. eventDataOut[LicenseActivationError::P_MESSAGE] = message;
  447. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  448. }
  449. else if (code == 3)
  450. {
  451. String message ="Activation Server Error:\nThere was an error on the activation server\n\nIf the problem persists please contact [email protected]";
  452. eventDataOut[LicenseActivationError::P_MESSAGE] = message;
  453. SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
  454. }
  455. }
  456. UnsubscribeFromEvents(serverActivation_);
  457. serverActivation_ = 0;
  458. }
  459. void LicenseSystem::RequestServerActivation(const String& key)
  460. {
  461. if (serverActivation_.NotNull())
  462. {
  463. LOGERROR("UIActivation::RequestServerActivation - request already exists");
  464. return;
  465. }
  466. key_ = key;
  467. CurlManager* cm = GetSubsystem<CurlManager>();
  468. String post;
  469. String id = GenerateMachineID();
  470. post.AppendWithFormat("key=%s&id=%s", key.CString(), id.CString());
  471. // todo, this should be a verify url (shouldn't auto add id)
  472. serverActivation_ = cm->MakeRequest("https://store.atomicgameengine.com/licenses/license_activate.php", post);
  473. SubscribeToEvent(serverActivation_, E_CURLCOMPLETE, HANDLER(LicenseSystem, HandleActivationResult));
  474. }
  475. }
  476. // END LICENSE MANAGEMENT