LobbyServer.cpp 28 KB

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