LobbyServer.cpp 27 KB

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