LobbyServer.cpp 19 KB

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