LobbyServer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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 <boost/uuid/uuid_generators.hpp>
  17. #include <boost/uuid/uuid_io.hpp>
  18. bool LobbyServer::isAccountNameValid(const std::string & accountName) const
  19. {
  20. if(accountName.size() < 4)
  21. return false;
  22. if(accountName.size() > 20)
  23. return false;
  24. for(const auto & c : accountName)
  25. if(!std::isalnum(c))
  26. return false;
  27. return true;
  28. }
  29. std::string LobbyServer::sanitizeChatMessage(const std::string & inputString) const
  30. {
  31. // TODO: sanitize message and remove any "weird" symbols from it
  32. return inputString;
  33. }
  34. NetworkConnectionPtr LobbyServer::findAccount(const std::string & accountID) const
  35. {
  36. for(const auto & account : activeAccounts)
  37. if(account.second == accountID)
  38. return account.first;
  39. return nullptr;
  40. }
  41. NetworkConnectionPtr LobbyServer::findGameRoom(const std::string & gameRoomID) const
  42. {
  43. for(const auto & account : activeGameRooms)
  44. if(account.second == gameRoomID)
  45. return account.first;
  46. return nullptr;
  47. }
  48. void LobbyServer::sendMessage(const NetworkConnectionPtr & target, const JsonNode & json)
  49. {
  50. assert(JsonUtils::validate(json, "vcmi:lobbyProtocol/" + json["type"].String(), "network"));
  51. target->sendPacket(json.toBytes());
  52. }
  53. void LobbyServer::sendAccountCreated(const NetworkConnectionPtr & target, const std::string & accountID, const std::string & accountCookie)
  54. {
  55. JsonNode reply;
  56. reply["type"].String() = "accountCreated";
  57. reply["accountID"].String() = accountID;
  58. reply["accountCookie"].String() = accountCookie;
  59. sendMessage(target, reply);
  60. }
  61. void LobbyServer::sendInviteReceived(const NetworkConnectionPtr & target, const std::string & accountID, const std::string & gameRoomID)
  62. {
  63. JsonNode reply;
  64. reply["type"].String() = "inviteReceived";
  65. reply["accountID"].String() = accountID;
  66. reply["gameRoomID"].String() = gameRoomID;
  67. sendMessage(target, reply);
  68. }
  69. void LobbyServer::sendOperationFailed(const NetworkConnectionPtr & target, const std::string & reason)
  70. {
  71. JsonNode reply;
  72. reply["type"].String() = "operationFailed";
  73. reply["reason"].String() = reason;
  74. sendMessage(target, reply);
  75. }
  76. void LobbyServer::sendLoginSuccess(const NetworkConnectionPtr & target, const std::string & accountCookie, const std::string & displayName)
  77. {
  78. JsonNode reply;
  79. reply["type"].String() = "loginSuccess";
  80. reply["accountCookie"].String() = accountCookie;
  81. if(!displayName.empty())
  82. reply["displayName"].String() = displayName;
  83. sendMessage(target, reply);
  84. }
  85. void LobbyServer::sendChatHistory(const NetworkConnectionPtr & target, const std::vector<LobbyChatMessage> & history)
  86. {
  87. JsonNode reply;
  88. reply["type"].String() = "chatHistory";
  89. for(const auto & message : boost::adaptors::reverse(history))
  90. {
  91. JsonNode jsonEntry;
  92. jsonEntry["accountID"].String() = message.accountID;
  93. jsonEntry["displayName"].String() = message.displayName;
  94. jsonEntry["messageText"].String() = message.messageText;
  95. jsonEntry["ageSeconds"].Integer() = message.age.count();
  96. reply["messages"].Vector().push_back(jsonEntry);
  97. }
  98. sendMessage(target, reply);
  99. }
  100. void LobbyServer::broadcastActiveAccounts()
  101. {
  102. auto activeAccountsStats = database->getActiveAccounts();
  103. JsonNode reply;
  104. reply["type"].String() = "activeAccounts";
  105. for(const auto & account : activeAccountsStats)
  106. {
  107. JsonNode jsonEntry;
  108. jsonEntry["accountID"].String() = account.accountID;
  109. jsonEntry["displayName"].String() = account.displayName;
  110. jsonEntry["status"].String() = "In Lobby"; // TODO: in room status, in match status, offline status(?)
  111. reply["accounts"].Vector().push_back(jsonEntry);
  112. }
  113. for(const auto & connection : activeAccounts)
  114. sendMessage(connection.first, reply);
  115. }
  116. JsonNode LobbyServer::prepareActiveGameRooms()
  117. {
  118. auto activeGameRoomStats = database->getActiveGameRooms();
  119. JsonNode reply;
  120. reply["type"].String() = "activeGameRooms";
  121. for(const auto & gameRoom : activeGameRoomStats)
  122. {
  123. JsonNode jsonEntry;
  124. jsonEntry["gameRoomID"].String() = gameRoom.roomID;
  125. jsonEntry["hostAccountID"].String() = gameRoom.hostAccountID;
  126. jsonEntry["hostAccountDisplayName"].String() = gameRoom.hostAccountDisplayName;
  127. jsonEntry["description"].String() = "TODO: ROOM DESCRIPTION";
  128. jsonEntry["playersCount"].Integer() = gameRoom.playersCount;
  129. jsonEntry["playersLimit"].Integer() = gameRoom.playersLimit;
  130. reply["gameRooms"].Vector().push_back(jsonEntry);
  131. }
  132. return reply;
  133. }
  134. void LobbyServer::broadcastActiveGameRooms()
  135. {
  136. auto reply = prepareActiveGameRooms();
  137. for(const auto & connection : activeAccounts)
  138. sendMessage(connection.first, reply);
  139. }
  140. void LobbyServer::sendAccountJoinsRoom(const NetworkConnectionPtr & target, const std::string & accountID)
  141. {
  142. JsonNode reply;
  143. reply["type"].String() = "accountJoinsRoom";
  144. reply["accountID"].String() = accountID;
  145. sendMessage(target, reply);
  146. }
  147. void LobbyServer::sendJoinRoomSuccess(const NetworkConnectionPtr & target, const std::string & gameRoomID, bool proxyMode)
  148. {
  149. JsonNode reply;
  150. reply["type"].String() = "joinRoomSuccess";
  151. reply["gameRoomID"].String() = gameRoomID;
  152. reply["proxyMode"].Bool() = proxyMode;
  153. sendMessage(target, reply);
  154. }
  155. void LobbyServer::sendChatMessage(const NetworkConnectionPtr & target, const std::string & roomMode, const std::string & roomName, const std::string & accountID, const std::string & displayName, const std::string & messageText)
  156. {
  157. JsonNode reply;
  158. reply["type"].String() = "chatMessage";
  159. reply["messageText"].String() = messageText;
  160. reply["accountID"].String() = accountID;
  161. reply["displayName"].String() = displayName;
  162. reply["roomMode"].String() = roomMode;
  163. reply["roomName"].String() = roomName;
  164. sendMessage(target, reply);
  165. }
  166. void LobbyServer::onNewConnection(const NetworkConnectionPtr & connection)
  167. {
  168. // no-op - waiting for incoming data
  169. }
  170. void LobbyServer::onDisconnected(const NetworkConnectionPtr & connection, const std::string & errorMessage)
  171. {
  172. if(activeAccounts.count(connection))
  173. {
  174. database->setAccountOnline(activeAccounts.at(connection), false);
  175. activeAccounts.erase(connection);
  176. }
  177. if(activeGameRooms.count(connection))
  178. {
  179. database->setGameRoomStatus(activeGameRooms.at(connection), LobbyRoomState::CLOSED);
  180. activeGameRooms.erase(connection);
  181. }
  182. if(activeProxies.count(connection))
  183. {
  184. const auto & otherConnection = activeProxies.at(connection);
  185. if (otherConnection)
  186. otherConnection->close();
  187. activeProxies.erase(connection);
  188. activeProxies.erase(otherConnection);
  189. }
  190. broadcastActiveAccounts();
  191. broadcastActiveGameRooms();
  192. }
  193. JsonNode LobbyServer::parseAndValidateMessage(const std::vector<std::byte> & message) const
  194. {
  195. JsonParsingSettings parserSettings;
  196. parserSettings.mode = JsonParsingSettings::JsonFormatMode::JSON;
  197. parserSettings.maxDepth = 2;
  198. parserSettings.strict = true;
  199. JsonNode json;
  200. try
  201. {
  202. JsonNode jsonTemp(message.data(), message.size());
  203. json = std::move(jsonTemp);
  204. }
  205. catch (const JsonFormatException & e)
  206. {
  207. logGlobal->info(std::string("Json parsing error encountered: ") + e.what());
  208. return JsonNode();
  209. }
  210. std::string messageType = json["type"].String();
  211. if (messageType.empty())
  212. {
  213. logGlobal->info("Json parsing error encountered: Message type not set!");
  214. return JsonNode();
  215. }
  216. std::string schemaName = "vcmi:lobbyProtocol/" + messageType;
  217. if (!JsonUtils::validate(json, schemaName, "network"))
  218. {
  219. logGlobal->info("Json validation error encountered!");
  220. assert(0);
  221. return JsonNode();
  222. }
  223. return json;
  224. }
  225. void LobbyServer::onPacketReceived(const NetworkConnectionPtr & connection, const std::vector<std::byte> & message)
  226. {
  227. // proxy connection - no processing, only redirect
  228. if(activeProxies.count(connection))
  229. {
  230. auto lockedPtr = activeProxies.at(connection);
  231. if(lockedPtr)
  232. return lockedPtr->sendPacket(message);
  233. logGlobal->info("Received unexpected message for inactive proxy!");
  234. }
  235. JsonNode json = parseAndValidateMessage(message);
  236. std::string messageType = json["type"].String();
  237. // communication messages from vcmiclient
  238. if(activeAccounts.count(connection))
  239. {
  240. std::string accountName = activeAccounts.at(connection);
  241. logGlobal->info("%s: Received message of type %s", accountName, messageType);
  242. if(messageType == "sendChatMessage")
  243. return receiveSendChatMessage(connection, json);
  244. if(messageType == "activateGameRoom")
  245. return receiveActivateGameRoom(connection, json);
  246. if(messageType == "joinGameRoom")
  247. return receiveJoinGameRoom(connection, json);
  248. if(messageType == "sendInvite")
  249. return receiveSendInvite(connection, json);
  250. if(messageType == "declineInvite")
  251. return receiveDeclineInvite(connection, json);
  252. logGlobal->warn("%s: Unknown message type: %s", accountName, messageType);
  253. return;
  254. }
  255. // communication messages from vcmiserver
  256. if(activeGameRooms.count(connection))
  257. {
  258. std::string roomName = activeGameRooms.at(connection);
  259. logGlobal->info("%s: Received message of type %s", roomName, messageType);
  260. if(messageType == "leaveGameRoom")
  261. return receiveLeaveGameRoom(connection, json);
  262. logGlobal->warn("%s: Unknown message type: %s", roomName, messageType);
  263. return;
  264. }
  265. logGlobal->info("(unauthorised): Received message of type %s", messageType);
  266. // unauthorized connections - permit only login or register attempts
  267. if(messageType == "clientLogin")
  268. return receiveClientLogin(connection, json);
  269. if(messageType == "clientRegister")
  270. return receiveClientRegister(connection, json);
  271. if(messageType == "serverLogin")
  272. return receiveServerLogin(connection, json);
  273. if(messageType == "clientProxyLogin")
  274. return receiveClientProxyLogin(connection, json);
  275. if(messageType == "serverProxyLogin")
  276. return receiveServerProxyLogin(connection, json);
  277. connection->close();
  278. logGlobal->info("(unauthorised): Unknown message type %s", messageType);
  279. }
  280. void LobbyServer::receiveSendChatMessage(const NetworkConnectionPtr & connection, const JsonNode & json)
  281. {
  282. std::string accountID = activeAccounts[connection];
  283. std::string messageText = json["messageText"].String();
  284. std::string messageTextClean = sanitizeChatMessage(messageText);
  285. std::string displayName = database->getAccountDisplayName(accountID);
  286. if(messageTextClean.empty())
  287. return sendOperationFailed(connection, "No printable characters in sent message!");
  288. database->insertChatMessage(accountID, "global", "english", messageText);
  289. for(const auto & otherConnection : activeAccounts)
  290. sendChatMessage(otherConnection.first, "global", "english", accountID, displayName, messageText);
  291. }
  292. void LobbyServer::receiveClientRegister(const NetworkConnectionPtr & connection, const JsonNode & json)
  293. {
  294. std::string displayName = json["displayName"].String();
  295. std::string language = json["language"].String();
  296. if(isAccountNameValid(displayName))
  297. return sendOperationFailed(connection, "Illegal account name");
  298. if(database->isAccountNameExists(displayName))
  299. return sendOperationFailed(connection, "Account name already in use");
  300. std::string accountCookie = boost::uuids::to_string(boost::uuids::random_generator()());
  301. std::string accountID = boost::uuids::to_string(boost::uuids::random_generator()());
  302. database->insertAccount(accountID, displayName);
  303. database->insertAccessCookie(accountID, accountCookie);
  304. sendAccountCreated(connection, accountID, accountCookie);
  305. }
  306. void LobbyServer::receiveClientLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  307. {
  308. std::string accountID = json["accountID"].String();
  309. std::string accountCookie = json["accountCookie"].String();
  310. std::string language = json["language"].String();
  311. std::string version = json["version"].String();
  312. if(!database->isAccountIDExists(accountID))
  313. return sendOperationFailed(connection, "Account not found");
  314. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  315. if(clientCookieStatus == LobbyCookieStatus::INVALID)
  316. return sendOperationFailed(connection, "Authentification failure");
  317. database->updateAccountLoginTime(accountID);
  318. database->setAccountOnline(accountID, true);
  319. std::string displayName = database->getAccountDisplayName(accountID);
  320. activeAccounts[connection] = accountID;
  321. sendLoginSuccess(connection, accountCookie, displayName);
  322. sendChatHistory(connection, database->getRecentMessageHistory());
  323. // send active game rooms list to new account
  324. // and update acount list to everybody else including new account
  325. broadcastActiveAccounts();
  326. sendMessage(connection, prepareActiveGameRooms());
  327. }
  328. void LobbyServer::receiveServerLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  329. {
  330. std::string gameRoomID = json["gameRoomID"].String();
  331. std::string accountID = json["accountID"].String();
  332. std::string accountCookie = json["accountCookie"].String();
  333. std::string version = json["version"].String();
  334. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  335. if(clientCookieStatus == LobbyCookieStatus::INVALID)
  336. {
  337. sendOperationFailed(connection, "Invalid credentials");
  338. }
  339. else
  340. {
  341. database->insertGameRoom(gameRoomID, accountID);
  342. activeGameRooms[connection] = gameRoomID;
  343. sendLoginSuccess(connection, accountCookie, {});
  344. broadcastActiveGameRooms();
  345. }
  346. }
  347. void LobbyServer::receiveClientProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  348. {
  349. std::string gameRoomID = json["gameRoomID"].String();
  350. std::string accountID = json["accountID"].String();
  351. std::string accountCookie = json["accountCookie"].String();
  352. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie);
  353. if(clientCookieStatus != LobbyCookieStatus::INVALID)
  354. {
  355. for(auto & proxyEntry : awaitingProxies)
  356. {
  357. if(proxyEntry.accountID != accountID)
  358. continue;
  359. if(proxyEntry.roomID != gameRoomID)
  360. continue;
  361. proxyEntry.accountConnection = connection;
  362. auto gameRoomConnection = proxyEntry.roomConnection.lock();
  363. if(gameRoomConnection)
  364. {
  365. activeProxies[gameRoomConnection] = connection;
  366. activeProxies[connection] = gameRoomConnection;
  367. }
  368. return;
  369. }
  370. }
  371. sendOperationFailed(connection, "Invalid credentials");
  372. connection->close();
  373. }
  374. void LobbyServer::receiveServerProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  375. {
  376. std::string gameRoomID = json["gameRoomID"].String();
  377. std::string guestAccountID = json["guestAccountID"].String();
  378. std::string accountCookie = json["accountCookie"].String();
  379. // FIXME: find host account ID and validate his cookie
  380. //auto clientCookieStatus = database->getAccountCookieStatus(hostAccountID, accountCookie, accountCookieLifetime);
  381. //if(clientCookieStatus != LobbyCookieStatus::INVALID)
  382. {
  383. NetworkConnectionPtr targetAccount = findAccount(guestAccountID);
  384. if(targetAccount == nullptr)
  385. {
  386. sendOperationFailed(connection, "Invalid credentials");
  387. return; // unknown / disconnected account
  388. }
  389. sendJoinRoomSuccess(targetAccount, gameRoomID, true);
  390. AwaitingProxyState proxy;
  391. proxy.accountID = guestAccountID;
  392. proxy.roomID = gameRoomID;
  393. proxy.roomConnection = connection;
  394. awaitingProxies.push_back(proxy);
  395. return;
  396. }
  397. //connection->close();
  398. }
  399. void LobbyServer::receiveActivateGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  400. {
  401. std::string hostAccountID = json["hostAccountID"].String();
  402. std::string accountID = activeAccounts[connection];
  403. if(database->isPlayerInGameRoom(accountID))
  404. return sendOperationFailed(connection, "Player already in the room!");
  405. std::string gameRoomID = database->getIdleGameRoom(hostAccountID);
  406. if(gameRoomID.empty())
  407. return sendOperationFailed(connection, "Failed to find idle server to join!");
  408. std::string roomType = json["roomType"].String();
  409. if(roomType != "public" && roomType != "private")
  410. return sendOperationFailed(connection, "Invalid room type!");
  411. if(roomType == "public")
  412. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PUBLIC);
  413. if(roomType == "private")
  414. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PRIVATE);
  415. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  416. broadcastActiveGameRooms();
  417. sendJoinRoomSuccess(connection, gameRoomID, false);
  418. }
  419. void LobbyServer::receiveJoinGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  420. {
  421. std::string gameRoomID = json["gameRoomID"].String();
  422. std::string accountID = activeAccounts[connection];
  423. if(database->isPlayerInGameRoom(accountID))
  424. return sendOperationFailed(connection, "Player already in the room!");
  425. NetworkConnectionPtr targetRoom = findGameRoom(gameRoomID);
  426. if(targetRoom == nullptr)
  427. return sendOperationFailed(connection, "Failed to find game room to join!");
  428. auto roomStatus = database->getGameRoomStatus(gameRoomID);
  429. if(roomStatus != LobbyRoomState::PRIVATE && roomStatus != LobbyRoomState::PUBLIC)
  430. return sendOperationFailed(connection, "Room does not accepts new players!");
  431. if(roomStatus == LobbyRoomState::PRIVATE)
  432. {
  433. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::INVITED)
  434. return sendOperationFailed(connection, "You are not permitted to join private room without invite!");
  435. }
  436. if(database->getGameRoomFreeSlots(gameRoomID) == 0)
  437. return sendOperationFailed(connection, "Room is already full!");
  438. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  439. sendAccountJoinsRoom(targetRoom, accountID);
  440. //No reply to client - will be sent once match server establishes proxy connection with lobby
  441. broadcastActiveGameRooms();
  442. }
  443. void LobbyServer::receiveLeaveGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  444. {
  445. std::string accountID = json["accountID"].String();
  446. std::string gameRoomID = activeGameRooms[connection];
  447. if(!database->isPlayerInGameRoom(accountID, gameRoomID))
  448. return sendOperationFailed(connection, "You are not in the room!");
  449. database->deletePlayerFromGameRoom(accountID, gameRoomID);
  450. broadcastActiveGameRooms();
  451. }
  452. void LobbyServer::receiveSendInvite(const NetworkConnectionPtr & connection, const JsonNode & json)
  453. {
  454. std::string senderName = activeAccounts[connection];
  455. std::string accountID = json["accountID"].String();
  456. std::string gameRoomID = database->getAccountGameRoom(senderName);
  457. auto targetAccount = findAccount(accountID);
  458. if(!targetAccount)
  459. return sendOperationFailed(connection, "Invalid account to invite!");
  460. if(!database->isPlayerInGameRoom(senderName))
  461. return sendOperationFailed(connection, "You are not in the room!");
  462. if(database->isPlayerInGameRoom(accountID))
  463. return sendOperationFailed(connection, "This player is already in a room!");
  464. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::NOT_INVITED)
  465. return sendOperationFailed(connection, "This player is already invited!");
  466. database->insertGameRoomInvite(accountID, gameRoomID);
  467. sendInviteReceived(targetAccount, senderName, gameRoomID);
  468. }
  469. void LobbyServer::receiveDeclineInvite(const NetworkConnectionPtr & connection, const JsonNode & json)
  470. {
  471. std::string accountID = activeAccounts[connection];
  472. std::string gameRoomID = json["gameRoomID"].String();
  473. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::INVITED)
  474. return sendOperationFailed(connection, "No active invite found!");
  475. database->deleteGameRoomInvite(accountID, gameRoomID);
  476. }
  477. LobbyServer::~LobbyServer() = default;
  478. LobbyServer::LobbyServer(const boost::filesystem::path & databasePath)
  479. : database(std::make_unique<LobbyDatabase>(databasePath))
  480. , networkHandler(INetworkHandler::createHandler())
  481. , networkServer(networkHandler->createServerTCP(*this))
  482. {
  483. }
  484. void LobbyServer::start(uint16_t port)
  485. {
  486. networkServer->start(port);
  487. }
  488. void LobbyServer::run()
  489. {
  490. networkHandler->run();
  491. }