LobbyServer.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. /*
  2. * LobbyServer.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "LobbyServer.h"
  12. #include "LobbyDatabase.h"
  13. #include "../lib/Languages.h"
  14. #include "../lib/TextOperations.h"
  15. #include "../lib/json/JsonFormatException.h"
  16. #include "../lib/json/JsonNode.h"
  17. #include "../lib/json/JsonUtils.h"
  18. #include <boost/uuid/uuid_generators.hpp>
  19. #include <boost/uuid/uuid_io.hpp>
  20. bool LobbyServer::isAccountNameValid(const std::string & accountName) const
  21. {
  22. // Arbitrary limit on account name length.
  23. // Can be extended if there are no issues with UI space
  24. if(accountName.size() < 4)
  25. return false;
  26. if(accountName.size() > 20)
  27. return false;
  28. // For now permit only latin alphabet and numbers
  29. // Can be extended, but makes sure that such symbols will be present in all H3 fonts
  30. for(const auto & c : accountName)
  31. if(!std::isalnum(c))
  32. return false;
  33. return true;
  34. }
  35. std::string LobbyServer::sanitizeChatMessage(const std::string & inputString) const
  36. {
  37. static const std::string blacklist = "{}";
  38. std::string sanitized;
  39. for(const auto & ch : inputString)
  40. {
  41. // Remove all control characters
  42. if (ch >= '\0' && ch < ' ')
  43. continue;
  44. // Remove blacklisted characters such as brackets that are used for text formatting
  45. if (blacklist.find(ch) != std::string::npos)
  46. continue;
  47. sanitized += ch;
  48. }
  49. return boost::trim_copy(sanitized);
  50. }
  51. NetworkConnectionPtr LobbyServer::findAccount(const std::string & accountID) const
  52. {
  53. for(const auto & account : activeAccounts)
  54. if(account.second == accountID)
  55. return account.first;
  56. return nullptr;
  57. }
  58. NetworkConnectionPtr LobbyServer::findGameRoom(const std::string & gameRoomID) const
  59. {
  60. for(const auto & account : activeGameRooms)
  61. if(account.second == gameRoomID)
  62. return account.first;
  63. return nullptr;
  64. }
  65. void LobbyServer::sendMessage(const NetworkConnectionPtr & target, const JsonNode & json)
  66. {
  67. logGlobal->info("Sending message of type %s", json["type"].String());
  68. assert(JsonUtils::validate(json, "vcmi:lobbyProtocol/" + json["type"].String(), json["type"].String() + " pack"));
  69. target->sendPacket(json.toBytes());
  70. }
  71. void LobbyServer::sendAccountCreated(const NetworkConnectionPtr & target, const std::string & accountID, const std::string & accountCookie)
  72. {
  73. JsonNode reply;
  74. reply["type"].String() = "accountCreated";
  75. reply["accountID"].String() = accountID;
  76. reply["accountCookie"].String() = accountCookie;
  77. sendMessage(target, reply);
  78. }
  79. void LobbyServer::sendInviteReceived(const NetworkConnectionPtr & target, const std::string & accountID, const std::string & gameRoomID)
  80. {
  81. JsonNode reply;
  82. reply["type"].String() = "inviteReceived";
  83. reply["accountID"].String() = accountID;
  84. reply["gameRoomID"].String() = gameRoomID;
  85. sendMessage(target, reply);
  86. }
  87. void LobbyServer::sendOperationFailed(const NetworkConnectionPtr & target, const std::string & reason)
  88. {
  89. JsonNode reply;
  90. reply["type"].String() = "operationFailed";
  91. reply["reason"].String() = reason;
  92. sendMessage(target, reply);
  93. }
  94. void LobbyServer::sendClientLoginSuccess(const NetworkConnectionPtr & target, const std::string & accountCookie, const std::string & displayName)
  95. {
  96. JsonNode reply;
  97. reply["type"].String() = "clientLoginSuccess";
  98. reply["accountCookie"].String() = accountCookie;
  99. reply["displayName"].String() = displayName;
  100. sendMessage(target, reply);
  101. }
  102. void LobbyServer::sendServerLoginSuccess(const NetworkConnectionPtr & target, const std::string & accountCookie)
  103. {
  104. JsonNode reply;
  105. reply["type"].String() = "serverLoginSuccess";
  106. reply["accountCookie"].String() = accountCookie;
  107. sendMessage(target, reply);
  108. }
  109. void LobbyServer::sendFullChatHistory(const NetworkConnectionPtr & target, const std::string & channelType, const std::string & channelName, const std::string & channelNameForClient)
  110. {
  111. sendChatHistory(target, channelType, channelNameForClient, database->getFullMessageHistory(channelType, channelName));
  112. }
  113. void LobbyServer::sendRecentChatHistory(const NetworkConnectionPtr & target, const std::string & channelType, const std::string & channelName)
  114. {
  115. sendChatHistory(target, channelType, channelName, database->getRecentMessageHistory(channelType, channelName));
  116. }
  117. void LobbyServer::sendChatHistory(const NetworkConnectionPtr & target, const std::string & channelType, const std::string & channelName, const std::vector<LobbyChatMessage> & history)
  118. {
  119. JsonNode reply;
  120. reply["type"].String() = "chatHistory";
  121. reply["channelType"].String() = channelType;
  122. reply["channelName"].String() = channelName;
  123. reply["messages"].Vector(); // force creation of empty vector
  124. for(const auto & message : boost::adaptors::reverse(history))
  125. {
  126. JsonNode jsonEntry;
  127. jsonEntry["accountID"].String() = message.accountID;
  128. jsonEntry["displayName"].String() = message.displayName;
  129. jsonEntry["messageText"].String() = message.messageText;
  130. jsonEntry["ageSeconds"].Integer() = message.age.count();
  131. reply["messages"].Vector().push_back(jsonEntry);
  132. }
  133. sendMessage(target, reply);
  134. }
  135. void LobbyServer::broadcastActiveAccounts()
  136. {
  137. auto activeAccountsStats = database->getActiveAccounts();
  138. JsonNode reply;
  139. reply["type"].String() = "activeAccounts";
  140. reply["accounts"].Vector(); // force creation of empty vector
  141. for(const auto & account : activeAccountsStats)
  142. {
  143. JsonNode jsonEntry;
  144. jsonEntry["accountID"].String() = account.accountID;
  145. jsonEntry["displayName"].String() = account.displayName;
  146. jsonEntry["status"].String() = "In Lobby"; // TODO: in room status, in match status, offline status(?)
  147. reply["accounts"].Vector().push_back(jsonEntry);
  148. }
  149. for(const auto & connection : activeAccounts)
  150. sendMessage(connection.first, reply);
  151. }
  152. static JsonNode loadLobbyAccountToJson(const LobbyAccount & account)
  153. {
  154. JsonNode jsonEntry;
  155. jsonEntry["accountID"].String() = account.accountID;
  156. jsonEntry["displayName"].String() = account.displayName;
  157. return jsonEntry;
  158. }
  159. static JsonNode loadLobbyGameRoomToJson(const LobbyGameRoom & gameRoom)
  160. {
  161. static constexpr std::array LOBBY_ROOM_STATE_NAMES = {
  162. "idle",
  163. "public",
  164. "private",
  165. "busy",
  166. "cancelled",
  167. "closed"
  168. };
  169. JsonNode jsonEntry;
  170. jsonEntry["gameRoomID"].String() = gameRoom.roomID;
  171. jsonEntry["hostAccountID"].String() = gameRoom.hostAccountID;
  172. jsonEntry["hostAccountDisplayName"].String() = gameRoom.hostAccountDisplayName;
  173. jsonEntry["description"].String() = gameRoom.description;
  174. jsonEntry["status"].String() = LOBBY_ROOM_STATE_NAMES[vstd::to_underlying(gameRoom.roomState)];
  175. jsonEntry["playerLimit"].Integer() = gameRoom.playerLimit;
  176. jsonEntry["ageSeconds"].Integer() = gameRoom.age.count();
  177. for(const auto & account : gameRoom.participants)
  178. jsonEntry["participants"].Vector().push_back(loadLobbyAccountToJson(account));
  179. return jsonEntry;
  180. }
  181. void LobbyServer::sendMatchesHistory(const NetworkConnectionPtr & target)
  182. {
  183. std::string accountID = activeAccounts.at(target);
  184. auto matchesHistory = database->getAccountGameHistory(accountID);
  185. JsonNode reply;
  186. reply["type"].String() = "matchesHistory";
  187. reply["matchesHistory"].Vector(); // force creation of empty vector
  188. for(const auto & gameRoom : matchesHistory)
  189. reply["matchesHistory"].Vector().push_back(loadLobbyGameRoomToJson(gameRoom));
  190. sendMessage(target, reply);
  191. }
  192. JsonNode LobbyServer::prepareActiveGameRooms()
  193. {
  194. auto activeGameRoomStats = database->getActiveGameRooms();
  195. JsonNode reply;
  196. reply["type"].String() = "activeGameRooms";
  197. reply["gameRooms"].Vector(); // force creation of empty vector
  198. for(const auto & gameRoom : activeGameRoomStats)
  199. reply["gameRooms"].Vector().push_back(loadLobbyGameRoomToJson(gameRoom));
  200. return reply;
  201. }
  202. void LobbyServer::broadcastActiveGameRooms()
  203. {
  204. auto reply = prepareActiveGameRooms();
  205. for(const auto & connection : activeAccounts)
  206. sendMessage(connection.first, reply);
  207. }
  208. void LobbyServer::sendAccountJoinsRoom(const NetworkConnectionPtr & target, const std::string & accountID)
  209. {
  210. JsonNode reply;
  211. reply["type"].String() = "accountJoinsRoom";
  212. reply["accountID"].String() = accountID;
  213. sendMessage(target, reply);
  214. }
  215. void LobbyServer::sendJoinRoomSuccess(const NetworkConnectionPtr & target, const std::string & gameRoomID, bool proxyMode)
  216. {
  217. JsonNode reply;
  218. reply["type"].String() = "joinRoomSuccess";
  219. reply["gameRoomID"].String() = gameRoomID;
  220. reply["proxyMode"].Bool() = proxyMode;
  221. sendMessage(target, reply);
  222. }
  223. void LobbyServer::sendChatMessage(const NetworkConnectionPtr & target, const std::string & channelType, const std::string & channelName, const std::string & accountID, const std::string & displayName, const std::string & messageText)
  224. {
  225. JsonNode reply;
  226. reply["type"].String() = "chatMessage";
  227. reply["messageText"].String() = messageText;
  228. reply["accountID"].String() = accountID;
  229. reply["displayName"].String() = displayName;
  230. reply["channelType"].String() = channelType;
  231. reply["channelName"].String() = channelName;
  232. sendMessage(target, reply);
  233. }
  234. void LobbyServer::onNewConnection(const NetworkConnectionPtr & connection)
  235. {
  236. // no-op - waiting for incoming data
  237. }
  238. void LobbyServer::onDisconnected(const NetworkConnectionPtr & connection, const std::string & errorMessage)
  239. {
  240. if(activeAccounts.count(connection))
  241. {
  242. database->setAccountOnline(activeAccounts.at(connection), false);
  243. activeAccounts.erase(connection);
  244. }
  245. if(activeGameRooms.count(connection))
  246. {
  247. std::string gameRoomID = activeGameRooms.at(connection);
  248. if (database->getGameRoomStatus(gameRoomID) == LobbyRoomState::BUSY)
  249. {
  250. database->setGameRoomStatus(gameRoomID, LobbyRoomState::CLOSED);
  251. for(const auto & accountConnection : activeAccounts)
  252. if (database->isPlayerInGameRoom(accountConnection.second, gameRoomID))
  253. sendMatchesHistory(accountConnection.first);
  254. }
  255. else
  256. database->setGameRoomStatus(gameRoomID, LobbyRoomState::CANCELLED);
  257. activeGameRooms.erase(connection);
  258. }
  259. if(activeProxies.count(connection))
  260. {
  261. const auto & otherConnection = activeProxies.at(connection);
  262. if (otherConnection)
  263. otherConnection->close();
  264. activeProxies.erase(connection);
  265. activeProxies.erase(otherConnection);
  266. }
  267. broadcastActiveAccounts();
  268. broadcastActiveGameRooms();
  269. }
  270. JsonNode LobbyServer::parseAndValidateMessage(const std::vector<std::byte> & message) const
  271. {
  272. JsonParsingSettings parserSettings;
  273. parserSettings.mode = JsonParsingSettings::JsonFormatMode::JSON;
  274. parserSettings.maxDepth = 2;
  275. parserSettings.strict = true;
  276. JsonNode json;
  277. try
  278. {
  279. JsonNode jsonTemp(message.data(), message.size());
  280. json = std::move(jsonTemp);
  281. }
  282. catch (const JsonFormatException & e)
  283. {
  284. logGlobal->info(std::string("Json parsing error encountered: ") + e.what());
  285. return JsonNode();
  286. }
  287. std::string messageType = json["type"].String();
  288. if (messageType.empty())
  289. {
  290. logGlobal->info("Json parsing error encountered: Message type not set!");
  291. return JsonNode();
  292. }
  293. std::string schemaName = "vcmi:lobbyProtocol/" + messageType;
  294. if (!JsonUtils::validate(json, schemaName, messageType + " pack"))
  295. {
  296. logGlobal->info("Json validation error encountered!");
  297. assert(0);
  298. return JsonNode();
  299. }
  300. return json;
  301. }
  302. void LobbyServer::onPacketReceived(const NetworkConnectionPtr & connection, const std::vector<std::byte> & message)
  303. {
  304. // proxy connection - no processing, only redirect
  305. if(activeProxies.count(connection))
  306. {
  307. auto lockedPtr = activeProxies.at(connection);
  308. if(lockedPtr)
  309. return lockedPtr->sendPacket(message);
  310. logGlobal->info("Received unexpected message for inactive proxy!");
  311. }
  312. JsonNode json = parseAndValidateMessage(message);
  313. std::string messageType = json["type"].String();
  314. // communication messages from vcmiclient
  315. if(activeAccounts.count(connection))
  316. {
  317. std::string accountName = activeAccounts.at(connection);
  318. logGlobal->info("%s: Received message of type %s", accountName, messageType);
  319. if(messageType == "sendChatMessage")
  320. return receiveSendChatMessage(connection, json);
  321. if(messageType == "requestChatHistory")
  322. return receiveRequestChatHistory(connection, json);
  323. if(messageType == "activateGameRoom")
  324. return receiveActivateGameRoom(connection, json);
  325. if(messageType == "joinGameRoom")
  326. return receiveJoinGameRoom(connection, json);
  327. if(messageType == "sendInvite")
  328. return receiveSendInvite(connection, json);
  329. logGlobal->warn("%s: Unknown message type: %s", accountName, messageType);
  330. return;
  331. }
  332. // communication messages from vcmiserver
  333. if(activeGameRooms.count(connection))
  334. {
  335. std::string roomName = activeGameRooms.at(connection);
  336. logGlobal->info("%s: Received message of type %s", roomName, messageType);
  337. if(messageType == "changeRoomDescription")
  338. return receiveChangeRoomDescription(connection, json);
  339. if(messageType == "gameStarted")
  340. return receiveGameStarted(connection, json);
  341. if(messageType == "leaveGameRoom")
  342. return receiveLeaveGameRoom(connection, json);
  343. logGlobal->warn("%s: Unknown message type: %s", roomName, messageType);
  344. return;
  345. }
  346. logGlobal->info("(unauthorised): Received message of type %s", messageType);
  347. // unauthorized connections - permit only login or register attempts
  348. if(messageType == "clientLogin")
  349. return receiveClientLogin(connection, json);
  350. if(messageType == "clientRegister")
  351. return receiveClientRegister(connection, json);
  352. if(messageType == "serverLogin")
  353. return receiveServerLogin(connection, json);
  354. if(messageType == "clientProxyLogin")
  355. return receiveClientProxyLogin(connection, json);
  356. if(messageType == "serverProxyLogin")
  357. return receiveServerProxyLogin(connection, json);
  358. connection->close();
  359. logGlobal->info("(unauthorised): Unknown message type %s", messageType);
  360. }
  361. void LobbyServer::receiveRequestChatHistory(const NetworkConnectionPtr & connection, const JsonNode & json)
  362. {
  363. std::string accountID = activeAccounts[connection];
  364. std::string channelType = json["channelType"].String();
  365. std::string channelName = json["channelName"].String();
  366. if (channelType == "global")
  367. {
  368. // can only be sent on connection, initiated by server
  369. sendOperationFailed(connection, "Operation not supported!");
  370. }
  371. if (channelType == "match")
  372. {
  373. if (!database->isPlayerInGameRoom(accountID, channelName))
  374. return sendOperationFailed(connection, "Can not access room you are not part of!");
  375. sendFullChatHistory(connection, channelType, channelName, channelName);
  376. }
  377. if (channelType == "player")
  378. {
  379. if (!database->isAccountIDExists(channelName))
  380. return sendOperationFailed(connection, "Such player does not exists!");
  381. // room ID for private messages is actually <player 1 ID>_<player 2 ID>, with player ID's sorted alphabetically (to generate unique room ID)
  382. std::string roomID = std::min(accountID, channelName) + "_" + std::max(accountID, channelName);
  383. sendFullChatHistory(connection, channelType, roomID, channelName);
  384. }
  385. }
  386. void LobbyServer::receiveSendChatMessage(const NetworkConnectionPtr & connection, const JsonNode & json)
  387. {
  388. std::string senderAccountID = activeAccounts[connection];
  389. std::string messageText = json["messageText"].String();
  390. std::string channelType = json["channelType"].String();
  391. std::string channelName = json["channelName"].String();
  392. std::string displayName = database->getAccountDisplayName(senderAccountID);
  393. if(TextOperations::isValidUnicodeString(messageText))
  394. return sendOperationFailed(connection, "String contains invalid characters!");
  395. std::string messageTextClean = sanitizeChatMessage(messageText);
  396. if(messageTextClean.empty())
  397. return sendOperationFailed(connection, "No printable characters in sent message!");
  398. if (channelType == "global")
  399. {
  400. try
  401. {
  402. Languages::getLanguageOptions(channelName);
  403. }
  404. catch (const std::out_of_range &)
  405. {
  406. return sendOperationFailed(connection, "Unknown language!");
  407. }
  408. database->insertChatMessage(senderAccountID, channelType, channelName, messageText);
  409. for(const auto & otherConnection : activeAccounts)
  410. sendChatMessage(otherConnection.first, channelType, channelName, senderAccountID, displayName, messageText);
  411. }
  412. if (channelType == "match")
  413. {
  414. if (!database->isPlayerInGameRoom(senderAccountID, channelName))
  415. return sendOperationFailed(connection, "Can not access room you are not part of!");
  416. database->insertChatMessage(senderAccountID, channelType, channelName, messageText);
  417. LobbyRoomState roomStatus = database->getGameRoomStatus(channelName);
  418. // Broadcast chat message only if it being sent to already closed match
  419. // Othervice it will be handled by match server
  420. if (roomStatus == LobbyRoomState::CLOSED)
  421. {
  422. for(const auto & otherConnection : activeAccounts)
  423. {
  424. if (database->isPlayerInGameRoom(otherConnection.second, channelName))
  425. sendChatMessage(otherConnection.first, channelType, channelName, senderAccountID, displayName, messageText);
  426. }
  427. }
  428. }
  429. if (channelType == "player")
  430. {
  431. const std::string & receiverAccountID = channelName;
  432. std::string roomID = std::min(senderAccountID, receiverAccountID) + "_" + std::max(senderAccountID, receiverAccountID);
  433. if (!database->isAccountIDExists(receiverAccountID))
  434. return sendOperationFailed(connection, "Such player does not exists!");
  435. database->insertChatMessage(senderAccountID, channelType, roomID, messageText);
  436. sendChatMessage(connection, channelType, receiverAccountID, senderAccountID, displayName, messageText);
  437. if (senderAccountID != receiverAccountID)
  438. {
  439. for(const auto & otherConnection : activeAccounts)
  440. if (otherConnection.second == receiverAccountID)
  441. sendChatMessage(otherConnection.first, channelType, senderAccountID, senderAccountID, displayName, messageText);
  442. }
  443. }
  444. }
  445. void LobbyServer::receiveClientRegister(const NetworkConnectionPtr & connection, const JsonNode & json)
  446. {
  447. std::string displayName = json["displayName"].String();
  448. std::string language = json["language"].String();
  449. if(!isAccountNameValid(displayName))
  450. return sendOperationFailed(connection, "Illegal account name");
  451. if(database->isAccountNameExists(displayName))
  452. return sendOperationFailed(connection, "Account name already in use");
  453. std::string accountCookie = boost::uuids::to_string(boost::uuids::random_generator()());
  454. std::string accountID = boost::uuids::to_string(boost::uuids::random_generator()());
  455. database->insertAccount(accountID, displayName);
  456. database->insertAccessCookie(accountID, accountCookie);
  457. sendAccountCreated(connection, accountID, accountCookie);
  458. }
  459. void LobbyServer::receiveClientLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  460. {
  461. std::string accountID = json["accountID"].String();
  462. std::string accountCookie = json["accountCookie"].String();
  463. std::string language = json["language"].String();
  464. std::string version = json["version"].String();
  465. if(!database->isAccountIDExists(accountID))
  466. return sendOperationFailed(connection, "Account not found");
  467. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  468. if(clientCookieStatus == LobbyCookieStatus::INVALID)
  469. return sendOperationFailed(connection, "Authentification failure");
  470. database->updateAccountLoginTime(accountID);
  471. database->setAccountOnline(accountID, true);
  472. std::string displayName = database->getAccountDisplayName(accountID);
  473. activeAccounts[connection] = accountID;
  474. sendClientLoginSuccess(connection, accountCookie, displayName);
  475. sendRecentChatHistory(connection, "global", "english");
  476. if (language != "english")
  477. sendRecentChatHistory(connection, "global", language);
  478. // send active game rooms list to new account
  479. // and update acount list to everybody else including new account
  480. broadcastActiveAccounts();
  481. sendMessage(connection, prepareActiveGameRooms());
  482. sendMatchesHistory(connection);
  483. }
  484. void LobbyServer::receiveServerLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  485. {
  486. std::string gameRoomID = json["gameRoomID"].String();
  487. std::string accountID = json["accountID"].String();
  488. std::string accountCookie = json["accountCookie"].String();
  489. std::string version = json["version"].String();
  490. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  491. if(clientCookieStatus == LobbyCookieStatus::INVALID)
  492. {
  493. sendOperationFailed(connection, "Invalid credentials");
  494. }
  495. else
  496. {
  497. database->insertGameRoom(gameRoomID, accountID);
  498. activeGameRooms[connection] = gameRoomID;
  499. sendServerLoginSuccess(connection, accountCookie);
  500. broadcastActiveGameRooms();
  501. }
  502. }
  503. void LobbyServer::receiveClientProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  504. {
  505. std::string gameRoomID = json["gameRoomID"].String();
  506. std::string accountID = json["accountID"].String();
  507. std::string accountCookie = json["accountCookie"].String();
  508. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  509. if(clientCookieStatus != LobbyCookieStatus::INVALID)
  510. {
  511. for(auto & proxyEntry : awaitingProxies)
  512. {
  513. if(proxyEntry.accountID != accountID)
  514. continue;
  515. if(proxyEntry.roomID != gameRoomID)
  516. continue;
  517. proxyEntry.accountConnection = connection;
  518. auto gameRoomConnection = proxyEntry.roomConnection.lock();
  519. if(gameRoomConnection)
  520. {
  521. activeProxies[gameRoomConnection] = connection;
  522. activeProxies[connection] = gameRoomConnection;
  523. }
  524. return;
  525. }
  526. }
  527. sendOperationFailed(connection, "Invalid credentials");
  528. connection->close();
  529. }
  530. void LobbyServer::receiveServerProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  531. {
  532. std::string gameRoomID = json["gameRoomID"].String();
  533. std::string guestAccountID = json["guestAccountID"].String();
  534. std::string accountCookie = json["accountCookie"].String();
  535. // FIXME: find host account ID and validate his cookie
  536. //auto clientCookieStatus = database->getAccountCookieStatus(hostAccountID, accountCookie, accountCookieLifetime);
  537. //if(clientCookieStatus != LobbyCookieStatus::INVALID)
  538. {
  539. NetworkConnectionPtr targetAccount = findAccount(guestAccountID);
  540. if(targetAccount == nullptr)
  541. {
  542. sendOperationFailed(connection, "Invalid credentials");
  543. return; // unknown / disconnected account
  544. }
  545. sendJoinRoomSuccess(targetAccount, gameRoomID, true);
  546. AwaitingProxyState proxy;
  547. proxy.accountID = guestAccountID;
  548. proxy.roomID = gameRoomID;
  549. proxy.roomConnection = connection;
  550. awaitingProxies.push_back(proxy);
  551. return;
  552. }
  553. //connection->close();
  554. }
  555. void LobbyServer::receiveActivateGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  556. {
  557. std::string hostAccountID = json["hostAccountID"].String();
  558. std::string accountID = activeAccounts[connection];
  559. int playerLimit = json["playerLimit"].Integer();
  560. if(database->isPlayerInGameRoom(accountID))
  561. return sendOperationFailed(connection, "Player already in the room!");
  562. std::string gameRoomID = database->getIdleGameRoom(hostAccountID);
  563. if(gameRoomID.empty())
  564. return sendOperationFailed(connection, "Failed to find idle server to join!");
  565. std::string roomType = json["roomType"].String();
  566. if(roomType != "public" && roomType != "private")
  567. return sendOperationFailed(connection, "Invalid room type!");
  568. if(roomType == "public")
  569. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PUBLIC);
  570. if(roomType == "private")
  571. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PRIVATE);
  572. database->updateRoomPlayerLimit(gameRoomID, playerLimit);
  573. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  574. broadcastActiveGameRooms();
  575. sendJoinRoomSuccess(connection, gameRoomID, false);
  576. }
  577. void LobbyServer::receiveJoinGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  578. {
  579. std::string gameRoomID = json["gameRoomID"].String();
  580. std::string accountID = activeAccounts[connection];
  581. if(database->isPlayerInGameRoom(accountID))
  582. return sendOperationFailed(connection, "Player already in the room!");
  583. NetworkConnectionPtr targetRoom = findGameRoom(gameRoomID);
  584. if(targetRoom == nullptr)
  585. return sendOperationFailed(connection, "Failed to find game room to join!");
  586. auto roomStatus = database->getGameRoomStatus(gameRoomID);
  587. if(roomStatus != LobbyRoomState::PRIVATE && roomStatus != LobbyRoomState::PUBLIC)
  588. return sendOperationFailed(connection, "Room does not accepts new players!");
  589. if(roomStatus == LobbyRoomState::PRIVATE)
  590. {
  591. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::INVITED)
  592. return sendOperationFailed(connection, "You are not permitted to join private room without invite!");
  593. }
  594. if(database->getGameRoomFreeSlots(gameRoomID) == 0)
  595. return sendOperationFailed(connection, "Room is already full!");
  596. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  597. sendAccountJoinsRoom(targetRoom, accountID);
  598. //No reply to client - will be sent once match server establishes proxy connection with lobby
  599. broadcastActiveGameRooms();
  600. }
  601. void LobbyServer::receiveChangeRoomDescription(const NetworkConnectionPtr & connection, const JsonNode & json)
  602. {
  603. std::string gameRoomID = activeGameRooms[connection];
  604. std::string description = json["description"].String();
  605. database->updateRoomDescription(gameRoomID, description);
  606. broadcastActiveGameRooms();
  607. }
  608. void LobbyServer::receiveGameStarted(const NetworkConnectionPtr & connection, const JsonNode & json)
  609. {
  610. std::string gameRoomID = activeGameRooms[connection];
  611. database->setGameRoomStatus(gameRoomID, LobbyRoomState::BUSY);
  612. broadcastActiveGameRooms();
  613. }
  614. void LobbyServer::receiveLeaveGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  615. {
  616. std::string accountID = json["accountID"].String();
  617. std::string gameRoomID = activeGameRooms[connection];
  618. if(!database->isPlayerInGameRoom(accountID, gameRoomID))
  619. return sendOperationFailed(connection, "You are not in the room!");
  620. database->deletePlayerFromGameRoom(accountID, gameRoomID);
  621. broadcastActiveGameRooms();
  622. }
  623. void LobbyServer::receiveSendInvite(const NetworkConnectionPtr & connection, const JsonNode & json)
  624. {
  625. std::string senderName = activeAccounts[connection];
  626. std::string accountID = json["accountID"].String();
  627. std::string gameRoomID = database->getAccountGameRoom(senderName);
  628. auto targetAccountConnection = findAccount(accountID);
  629. if(!targetAccountConnection)
  630. return sendOperationFailed(connection, "Player is offline or does not exists!");
  631. if(!database->isPlayerInGameRoom(senderName))
  632. return sendOperationFailed(connection, "You are not in the room!");
  633. if(database->isPlayerInGameRoom(accountID))
  634. return sendOperationFailed(connection, "This player is already in a room!");
  635. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::NOT_INVITED)
  636. return sendOperationFailed(connection, "This player is already invited!");
  637. database->insertGameRoomInvite(accountID, gameRoomID);
  638. sendInviteReceived(targetAccountConnection, senderName, gameRoomID);
  639. }
  640. LobbyServer::~LobbyServer() = default;
  641. LobbyServer::LobbyServer(const boost::filesystem::path & databasePath)
  642. : database(std::make_unique<LobbyDatabase>(databasePath))
  643. , networkHandler(INetworkHandler::createHandler())
  644. , networkServer(networkHandler->createServerTCP(*this))
  645. {
  646. }
  647. void LobbyServer::start(uint16_t port)
  648. {
  649. networkServer->start(port);
  650. }
  651. void LobbyServer::run()
  652. {
  653. networkHandler->run();
  654. }