LobbyServer.cpp 20 KB

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