LicenseSystem.cpp 18 KB

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