LicenseSystem.cpp 16 KB

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