LicenseSystem.cpp 18 KB

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