LobbyServer.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. logGlobal->info("Account %s disconnecting. Accounts online: %d", activeAccounts.at(connection), activeAccounts.size() - 1);
  243. database->setAccountOnline(activeAccounts.at(connection), false);
  244. activeAccounts.erase(connection);
  245. }
  246. if(activeGameRooms.count(connection))
  247. {
  248. std::string gameRoomID = activeGameRooms.at(connection);
  249. logGlobal->info("Game room %s disconnecting. Rooms online: %d", gameRoomID, activeGameRooms.size() - 1);
  250. if (database->getGameRoomStatus(gameRoomID) == LobbyRoomState::BUSY)
  251. {
  252. database->setGameRoomStatus(gameRoomID, LobbyRoomState::CLOSED);
  253. for(const auto & accountConnection : activeAccounts)
  254. if (database->isPlayerInGameRoom(accountConnection.second, gameRoomID))
  255. sendMatchesHistory(accountConnection.first);
  256. }
  257. else
  258. database->setGameRoomStatus(gameRoomID, LobbyRoomState::CANCELLED);
  259. activeGameRooms.erase(connection);
  260. }
  261. if(activeProxies.count(connection))
  262. {
  263. const auto & otherConnection = activeProxies.at(connection);
  264. if (otherConnection)
  265. otherConnection->close();
  266. activeProxies.erase(connection);
  267. activeProxies.erase(otherConnection);
  268. }
  269. broadcastActiveAccounts();
  270. broadcastActiveGameRooms();
  271. }
  272. JsonNode LobbyServer::parseAndValidateMessage(const std::vector<std::byte> & message) const
  273. {
  274. JsonParsingSettings parserSettings;
  275. parserSettings.mode = JsonParsingSettings::JsonFormatMode::JSON;
  276. parserSettings.maxDepth = 2;
  277. parserSettings.strict = true;
  278. JsonNode json;
  279. try
  280. {
  281. JsonNode jsonTemp(message.data(), message.size());
  282. json = std::move(jsonTemp);
  283. }
  284. catch (const JsonFormatException & e)
  285. {
  286. logGlobal->info(std::string("Json parsing error encountered: ") + e.what());
  287. return JsonNode();
  288. }
  289. std::string messageType = json["type"].String();
  290. if (messageType.empty())
  291. {
  292. logGlobal->info("Json parsing error encountered: Message type not set!");
  293. return JsonNode();
  294. }
  295. std::string schemaName = "vcmi:lobbyProtocol/" + messageType;
  296. if (!JsonUtils::validate(json, schemaName, messageType + " pack"))
  297. {
  298. logGlobal->info("Json validation error encountered!");
  299. assert(0);
  300. return JsonNode();
  301. }
  302. return json;
  303. }
  304. void LobbyServer::onPacketReceived(const NetworkConnectionPtr & connection, const std::vector<std::byte> & message)
  305. {
  306. // proxy connection - no processing, only redirect
  307. if(activeProxies.count(connection))
  308. {
  309. auto lockedPtr = activeProxies.at(connection);
  310. if(lockedPtr)
  311. return lockedPtr->sendPacket(message);
  312. logGlobal->info("Received unexpected message for inactive proxy!");
  313. }
  314. JsonNode json = parseAndValidateMessage(message);
  315. std::string messageType = json["type"].String();
  316. // communication messages from vcmiclient
  317. if(activeAccounts.count(connection))
  318. {
  319. std::string accountName = activeAccounts.at(connection);
  320. logGlobal->info("%s: Received message of type %s", accountName, messageType);
  321. if(messageType == "sendChatMessage")
  322. return receiveSendChatMessage(connection, json);
  323. if(messageType == "requestChatHistory")
  324. return receiveRequestChatHistory(connection, json);
  325. if(messageType == "activateGameRoom")
  326. return receiveActivateGameRoom(connection, json);
  327. if(messageType == "joinGameRoom")
  328. return receiveJoinGameRoom(connection, json);
  329. if(messageType == "sendInvite")
  330. return receiveSendInvite(connection, json);
  331. logGlobal->warn("%s: Unknown message type: %s", accountName, messageType);
  332. return;
  333. }
  334. // communication messages from vcmiserver
  335. if(activeGameRooms.count(connection))
  336. {
  337. std::string roomName = activeGameRooms.at(connection);
  338. logGlobal->info("%s: Received message of type %s", roomName, messageType);
  339. if(messageType == "changeRoomDescription")
  340. return receiveChangeRoomDescription(connection, json);
  341. if(messageType == "gameStarted")
  342. return receiveGameStarted(connection, json);
  343. if(messageType == "leaveGameRoom")
  344. return receiveLeaveGameRoom(connection, json);
  345. logGlobal->warn("%s: Unknown message type: %s", roomName, messageType);
  346. return;
  347. }
  348. logGlobal->info("(unauthorised): Received message of type %s", messageType);
  349. // unauthorized connections - permit only login or register attempts
  350. if(messageType == "clientLogin")
  351. return receiveClientLogin(connection, json);
  352. if(messageType == "clientRegister")
  353. return receiveClientRegister(connection, json);
  354. if(messageType == "serverLogin")
  355. return receiveServerLogin(connection, json);
  356. if(messageType == "clientProxyLogin")
  357. return receiveClientProxyLogin(connection, json);
  358. if(messageType == "serverProxyLogin")
  359. return receiveServerProxyLogin(connection, json);
  360. connection->close();
  361. logGlobal->info("(unauthorised): Unknown message type %s", messageType);
  362. }
  363. void LobbyServer::receiveRequestChatHistory(const NetworkConnectionPtr & connection, const JsonNode & json)
  364. {
  365. std::string accountID = activeAccounts[connection];
  366. std::string channelType = json["channelType"].String();
  367. std::string channelName = json["channelName"].String();
  368. if (channelType == "global")
  369. {
  370. // can only be sent on connection, initiated by server
  371. sendOperationFailed(connection, "Operation not supported!");
  372. }
  373. if (channelType == "match")
  374. {
  375. if (!database->isPlayerInGameRoom(accountID, channelName))
  376. return sendOperationFailed(connection, "Can not access room you are not part of!");
  377. sendFullChatHistory(connection, channelType, channelName, channelName);
  378. }
  379. if (channelType == "player")
  380. {
  381. if (!database->isAccountIDExists(channelName))
  382. return sendOperationFailed(connection, "Such player does not exists!");
  383. // room ID for private messages is actually <player 1 ID>_<player 2 ID>, with player ID's sorted alphabetically (to generate unique room ID)
  384. std::string roomID = std::min(accountID, channelName) + "_" + std::max(accountID, channelName);
  385. sendFullChatHistory(connection, channelType, roomID, channelName);
  386. }
  387. }
  388. void LobbyServer::receiveSendChatMessage(const NetworkConnectionPtr & connection, const JsonNode & json)
  389. {
  390. std::string senderAccountID = activeAccounts[connection];
  391. std::string messageText = json["messageText"].String();
  392. std::string channelType = json["channelType"].String();
  393. std::string channelName = json["channelName"].String();
  394. std::string displayName = database->getAccountDisplayName(senderAccountID);
  395. if(!TextOperations::isValidUnicodeString(messageText))
  396. return sendOperationFailed(connection, "String contains invalid characters!");
  397. std::string messageTextClean = sanitizeChatMessage(messageText);
  398. if(messageTextClean.empty())
  399. return sendOperationFailed(connection, "No printable characters in sent message!");
  400. if (channelType == "global")
  401. {
  402. try
  403. {
  404. Languages::getLanguageOptions(channelName);
  405. }
  406. catch (const std::out_of_range &)
  407. {
  408. return sendOperationFailed(connection, "Unknown language!");
  409. }
  410. database->insertChatMessage(senderAccountID, channelType, channelName, messageText);
  411. for(const auto & otherConnection : activeAccounts)
  412. sendChatMessage(otherConnection.first, channelType, channelName, senderAccountID, displayName, messageText);
  413. }
  414. if (channelType == "match")
  415. {
  416. if (!database->isPlayerInGameRoom(senderAccountID, channelName))
  417. return sendOperationFailed(connection, "Can not access room you are not part of!");
  418. database->insertChatMessage(senderAccountID, channelType, channelName, messageText);
  419. LobbyRoomState roomStatus = database->getGameRoomStatus(channelName);
  420. // Broadcast chat message only if it being sent to already closed match
  421. // Othervice it will be handled by match server
  422. if (roomStatus == LobbyRoomState::CLOSED)
  423. {
  424. for(const auto & otherConnection : activeAccounts)
  425. {
  426. if (database->isPlayerInGameRoom(otherConnection.second, channelName))
  427. sendChatMessage(otherConnection.first, channelType, channelName, senderAccountID, displayName, messageText);
  428. }
  429. }
  430. }
  431. if (channelType == "player")
  432. {
  433. const std::string & receiverAccountID = channelName;
  434. std::string roomID = std::min(senderAccountID, receiverAccountID) + "_" + std::max(senderAccountID, receiverAccountID);
  435. if (!database->isAccountIDExists(receiverAccountID))
  436. return sendOperationFailed(connection, "Such player does not exists!");
  437. database->insertChatMessage(senderAccountID, channelType, roomID, messageText);
  438. sendChatMessage(connection, channelType, receiverAccountID, senderAccountID, displayName, messageText);
  439. if (senderAccountID != receiverAccountID)
  440. {
  441. for(const auto & otherConnection : activeAccounts)
  442. if (otherConnection.second == receiverAccountID)
  443. sendChatMessage(otherConnection.first, channelType, senderAccountID, senderAccountID, displayName, messageText);
  444. }
  445. }
  446. }
  447. void LobbyServer::receiveClientRegister(const NetworkConnectionPtr & connection, const JsonNode & json)
  448. {
  449. std::string displayName = json["displayName"].String();
  450. std::string language = json["language"].String();
  451. if(!isAccountNameValid(displayName))
  452. return sendOperationFailed(connection, "Illegal account name");
  453. if(database->isAccountNameExists(displayName))
  454. return sendOperationFailed(connection, "Account name already in use");
  455. std::string accountCookie = boost::uuids::to_string(boost::uuids::random_generator()());
  456. std::string accountID = boost::uuids::to_string(boost::uuids::random_generator()());
  457. database->insertAccount(accountID, displayName);
  458. database->insertAccessCookie(accountID, accountCookie);
  459. sendAccountCreated(connection, accountID, accountCookie);
  460. }
  461. void LobbyServer::receiveClientLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  462. {
  463. std::string accountID = json["accountID"].String();
  464. std::string accountCookie = json["accountCookie"].String();
  465. std::string language = json["language"].String();
  466. std::string version = json["version"].String();
  467. if(!database->isAccountIDExists(accountID))
  468. return sendOperationFailed(connection, "Account not found");
  469. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  470. if(clientCookieStatus == LobbyCookieStatus::INVALID)
  471. return sendOperationFailed(connection, "Authentification failure");
  472. database->updateAccountLoginTime(accountID);
  473. database->setAccountOnline(accountID, true);
  474. std::string displayName = database->getAccountDisplayName(accountID);
  475. activeAccounts[connection] = accountID;
  476. logGlobal->info("%s: Logged in as %s", accountID, displayName);
  477. sendClientLoginSuccess(connection, accountCookie, displayName);
  478. sendRecentChatHistory(connection, "global", "english");
  479. if (language != "english")
  480. sendRecentChatHistory(connection, "global", language);
  481. // send active game rooms list to new account
  482. // and update acount list to everybody else including new account
  483. broadcastActiveAccounts();
  484. sendMessage(connection, prepareActiveGameRooms());
  485. sendMatchesHistory(connection);
  486. }
  487. void LobbyServer::receiveServerLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  488. {
  489. std::string gameRoomID = json["gameRoomID"].String();
  490. std::string accountID = json["accountID"].String();
  491. std::string accountCookie = json["accountCookie"].String();
  492. std::string version = json["version"].String();
  493. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  494. if(clientCookieStatus == LobbyCookieStatus::INVALID)
  495. {
  496. sendOperationFailed(connection, "Invalid credentials");
  497. }
  498. else
  499. {
  500. database->insertGameRoom(gameRoomID, accountID);
  501. activeGameRooms[connection] = gameRoomID;
  502. sendServerLoginSuccess(connection, accountCookie);
  503. broadcastActiveGameRooms();
  504. }
  505. }
  506. void LobbyServer::receiveClientProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  507. {
  508. std::string gameRoomID = json["gameRoomID"].String();
  509. std::string accountID = json["accountID"].String();
  510. std::string accountCookie = json["accountCookie"].String();
  511. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  512. if(clientCookieStatus != LobbyCookieStatus::INVALID)
  513. {
  514. for(auto & proxyEntry : awaitingProxies)
  515. {
  516. if(proxyEntry.accountID != accountID)
  517. continue;
  518. if(proxyEntry.roomID != gameRoomID)
  519. continue;
  520. proxyEntry.accountConnection = connection;
  521. auto gameRoomConnection = proxyEntry.roomConnection.lock();
  522. if(gameRoomConnection)
  523. {
  524. activeProxies[gameRoomConnection] = connection;
  525. activeProxies[connection] = gameRoomConnection;
  526. }
  527. return;
  528. }
  529. }
  530. sendOperationFailed(connection, "Invalid credentials");
  531. connection->close();
  532. }
  533. void LobbyServer::receiveServerProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  534. {
  535. std::string gameRoomID = json["gameRoomID"].String();
  536. std::string guestAccountID = json["guestAccountID"].String();
  537. std::string accountCookie = json["accountCookie"].String();
  538. // FIXME: find host account ID and validate his cookie
  539. //auto clientCookieStatus = database->getAccountCookieStatus(hostAccountID, accountCookie, accountCookieLifetime);
  540. //if(clientCookieStatus != LobbyCookieStatus::INVALID)
  541. {
  542. NetworkConnectionPtr targetAccount = findAccount(guestAccountID);
  543. if(targetAccount == nullptr)
  544. {
  545. sendOperationFailed(connection, "Invalid credentials");
  546. return; // unknown / disconnected account
  547. }
  548. sendJoinRoomSuccess(targetAccount, gameRoomID, true);
  549. AwaitingProxyState proxy;
  550. proxy.accountID = guestAccountID;
  551. proxy.roomID = gameRoomID;
  552. proxy.roomConnection = connection;
  553. awaitingProxies.push_back(proxy);
  554. return;
  555. }
  556. //connection->close();
  557. }
  558. void LobbyServer::receiveActivateGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  559. {
  560. std::string hostAccountID = json["hostAccountID"].String();
  561. std::string accountID = activeAccounts[connection];
  562. int playerLimit = json["playerLimit"].Integer();
  563. if(database->isPlayerInGameRoom(accountID))
  564. return sendOperationFailed(connection, "Player already in the room!");
  565. std::string gameRoomID = database->getIdleGameRoom(hostAccountID);
  566. if(gameRoomID.empty())
  567. return sendOperationFailed(connection, "Failed to find idle server to join!");
  568. std::string roomType = json["roomType"].String();
  569. if(roomType != "public" && roomType != "private")
  570. return sendOperationFailed(connection, "Invalid room type!");
  571. if(roomType == "public")
  572. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PUBLIC);
  573. if(roomType == "private")
  574. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PRIVATE);
  575. database->updateRoomPlayerLimit(gameRoomID, playerLimit);
  576. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  577. broadcastActiveGameRooms();
  578. sendJoinRoomSuccess(connection, gameRoomID, false);
  579. }
  580. void LobbyServer::receiveJoinGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  581. {
  582. std::string gameRoomID = json["gameRoomID"].String();
  583. std::string accountID = activeAccounts[connection];
  584. if(database->isPlayerInGameRoom(accountID))
  585. return sendOperationFailed(connection, "Player already in the room!");
  586. NetworkConnectionPtr targetRoom = findGameRoom(gameRoomID);
  587. if(targetRoom == nullptr)
  588. return sendOperationFailed(connection, "Failed to find game room to join!");
  589. auto roomStatus = database->getGameRoomStatus(gameRoomID);
  590. if(roomStatus != LobbyRoomState::PRIVATE && roomStatus != LobbyRoomState::PUBLIC)
  591. return sendOperationFailed(connection, "Room does not accepts new players!");
  592. if(roomStatus == LobbyRoomState::PRIVATE)
  593. {
  594. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::INVITED)
  595. return sendOperationFailed(connection, "You are not permitted to join private room without invite!");
  596. }
  597. if(database->getGameRoomFreeSlots(gameRoomID) == 0)
  598. return sendOperationFailed(connection, "Room is already full!");
  599. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  600. sendAccountJoinsRoom(targetRoom, accountID);
  601. //No reply to client - will be sent once match server establishes proxy connection with lobby
  602. broadcastActiveGameRooms();
  603. }
  604. void LobbyServer::receiveChangeRoomDescription(const NetworkConnectionPtr & connection, const JsonNode & json)
  605. {
  606. std::string gameRoomID = activeGameRooms[connection];
  607. std::string description = json["description"].String();
  608. database->updateRoomDescription(gameRoomID, description);
  609. broadcastActiveGameRooms();
  610. }
  611. void LobbyServer::receiveGameStarted(const NetworkConnectionPtr & connection, const JsonNode & json)
  612. {
  613. std::string gameRoomID = activeGameRooms[connection];
  614. database->setGameRoomStatus(gameRoomID, LobbyRoomState::BUSY);
  615. broadcastActiveGameRooms();
  616. }
  617. void LobbyServer::receiveLeaveGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  618. {
  619. std::string accountID = json["accountID"].String();
  620. std::string gameRoomID = activeGameRooms[connection];
  621. if(!database->isPlayerInGameRoom(accountID, gameRoomID))
  622. return sendOperationFailed(connection, "You are not in the room!");
  623. database->deletePlayerFromGameRoom(accountID, gameRoomID);
  624. broadcastActiveGameRooms();
  625. }
  626. void LobbyServer::receiveSendInvite(const NetworkConnectionPtr & connection, const JsonNode & json)
  627. {
  628. std::string senderName = activeAccounts[connection];
  629. std::string accountID = json["accountID"].String();
  630. std::string gameRoomID = database->getAccountGameRoom(senderName);
  631. auto targetAccountConnection = findAccount(accountID);
  632. if(!targetAccountConnection)
  633. return sendOperationFailed(connection, "Player is offline or does not exists!");
  634. if(!database->isPlayerInGameRoom(senderName))
  635. return sendOperationFailed(connection, "You are not in the room!");
  636. if(database->isPlayerInGameRoom(accountID))
  637. return sendOperationFailed(connection, "This player is already in a room!");
  638. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::NOT_INVITED)
  639. return sendOperationFailed(connection, "This player is already invited!");
  640. database->insertGameRoomInvite(accountID, gameRoomID);
  641. sendInviteReceived(targetAccountConnection, senderName, gameRoomID);
  642. }
  643. LobbyServer::~LobbyServer() = default;
  644. LobbyServer::LobbyServer(const boost::filesystem::path & databasePath)
  645. : database(std::make_unique<LobbyDatabase>(databasePath))
  646. , networkHandler(INetworkHandler::createHandler())
  647. , networkServer(networkHandler->createServerTCP(*this))
  648. {
  649. }
  650. void LobbyServer::start(uint16_t port)
  651. {
  652. networkServer->start(port);
  653. }
  654. void LobbyServer::run()
  655. {
  656. networkHandler->run();
  657. }