LobbyServer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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)
  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 == 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), false);
  178. if (activeGameRooms.count(connection))
  179. database->setGameRoomStatus(activeGameRooms.at(connection), 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);
  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);
  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];
  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;
  289. sendLoginSuccess(connection, accountCookie, displayName);
  290. sendChatHistory(connection, database->getRecentMessageHistory());
  291. // send active accounts list to new account
  292. // and update acount list to everybody else
  293. broadcastActiveAccounts();
  294. sendMessage(connection, prepareActiveGameRooms());
  295. }
  296. void LobbyServer::receiveServerLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  297. {
  298. std::string gameRoomID = json["gameRoomID"].String();
  299. std::string accountID = json["accountID"].String();
  300. std::string accountCookie = json["accountCookie"].String();
  301. std::string version = json["version"].String();
  302. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie, accountCookieLifetime);
  303. if(clientCookieStatus == LobbyCookieStatus::INVALID)
  304. {
  305. sendOperationFailed(connection, "Invalid credentials");
  306. }
  307. else
  308. {
  309. database->insertGameRoom(gameRoomID, accountID);
  310. activeGameRooms[connection] = gameRoomID;
  311. sendLoginSuccess(connection, accountCookie, {});
  312. broadcastActiveGameRooms();
  313. }
  314. }
  315. void LobbyServer::receiveClientProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  316. {
  317. std::string gameRoomID = json["gameRoomID"].String();
  318. std::string accountID = json["accountID"].String();
  319. std::string accountCookie = json["accountCookie"].String();
  320. auto clientCookieStatus = database->getAccountCookieStatus(accountID, accountCookie, accountCookieLifetime);
  321. if(clientCookieStatus != LobbyCookieStatus::INVALID)
  322. {
  323. for(auto & proxyEntry : awaitingProxies)
  324. {
  325. if(proxyEntry.accountID != accountID)
  326. continue;
  327. if(proxyEntry.roomID != gameRoomID)
  328. continue;
  329. proxyEntry.accountConnection = connection;
  330. auto gameRoomConnection = proxyEntry.roomConnection.lock();
  331. if(gameRoomConnection)
  332. {
  333. activeProxies[gameRoomConnection] = connection;
  334. activeProxies[connection] = gameRoomConnection;
  335. }
  336. return;
  337. }
  338. }
  339. sendOperationFailed(connection, "Invalid credentials");
  340. networkServer->closeConnection(connection);
  341. }
  342. void LobbyServer::receiveServerProxyLogin(const NetworkConnectionPtr & connection, const JsonNode & json)
  343. {
  344. std::string gameRoomID = json["gameRoomID"].String();
  345. std::string guestAccountID = json["guestAccountID"].String();
  346. std::string accountCookie = json["accountCookie"].String();
  347. // FIXME: find host account ID and validate his cookie
  348. //auto clientCookieStatus = database->getAccountCookieStatus(hostAccountID, accountCookie, accountCookieLifetime);
  349. //if(clientCookieStatus != LobbyCookieStatus::INVALID)
  350. {
  351. NetworkConnectionPtr targetAccount = findAccount(guestAccountID);
  352. if(targetAccount == nullptr)
  353. {
  354. sendOperationFailed(connection, "Invalid credentials");
  355. return; // unknown / disconnected account
  356. }
  357. sendJoinRoomSuccess(targetAccount, gameRoomID, true);
  358. AwaitingProxyState proxy;
  359. proxy.accountID = guestAccountID;
  360. proxy.roomID = gameRoomID;
  361. proxy.roomConnection = connection;
  362. awaitingProxies.push_back(proxy);
  363. return;
  364. }
  365. //networkServer->closeConnection(connection);
  366. }
  367. void LobbyServer::receiveOpenGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  368. {
  369. std::string hostAccountID = json["hostAccountID"].String();
  370. std::string accountID = activeAccounts[connection];
  371. if(database->isPlayerInGameRoom(accountID))
  372. return sendOperationFailed(connection, "Player already in the room!");
  373. std::string gameRoomID = database->getIdleGameRoom(hostAccountID);
  374. if(gameRoomID.empty())
  375. return sendOperationFailed(connection, "Failed to find idle server to join!");
  376. std::string roomType = json["roomType"].String();
  377. if(roomType != "public" && roomType != "private")
  378. return sendOperationFailed(connection, "Invalid room type!");
  379. if(roomType == "public")
  380. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PUBLIC);
  381. if(roomType == "private")
  382. database->setGameRoomStatus(gameRoomID, LobbyRoomState::PRIVATE);
  383. // TODO: additional flags / initial settings, e.g. allowCheats
  384. // TODO: connection mode: direct or proxy. For now direct is assumed. Proxy might be needed later, for hosted servers
  385. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  386. broadcastActiveGameRooms();
  387. sendJoinRoomSuccess(connection, gameRoomID, false);
  388. }
  389. void LobbyServer::receiveJoinGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  390. {
  391. std::string gameRoomID = json["gameRoomID"].String();
  392. std::string accountID = activeAccounts[connection];
  393. if(database->isPlayerInGameRoom(accountID))
  394. return sendOperationFailed(connection, "Player already in the room!");
  395. NetworkConnectionPtr targetRoom = findGameRoom(gameRoomID);
  396. if(targetRoom == nullptr)
  397. return sendOperationFailed(connection, "Failed to find game room to join!");
  398. auto roomStatus = database->getGameRoomStatus(gameRoomID);
  399. if(roomStatus != LobbyRoomState::PRIVATE && roomStatus != LobbyRoomState::PUBLIC)
  400. return sendOperationFailed(connection, "Room does not accepts new players!");
  401. if(roomStatus == LobbyRoomState::PRIVATE)
  402. {
  403. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::INVITED)
  404. return sendOperationFailed(connection, "You are not permitted to join private room without invite!");
  405. }
  406. if(database->getGameRoomFreeSlots(gameRoomID) == 0)
  407. return sendOperationFailed(connection, "Room is already full!");
  408. database->insertPlayerIntoGameRoom(accountID, gameRoomID);
  409. sendAccountJoinsRoom(targetRoom, accountID);
  410. //No reply to client - will be sent once match server establishes proxy connection with lobby
  411. broadcastActiveGameRooms();
  412. }
  413. void LobbyServer::receiveLeaveGameRoom(const NetworkConnectionPtr & connection, const JsonNode & json)
  414. {
  415. std::string gameRoomID = json["gameRoomID"].String();
  416. std::string senderName = activeAccounts[connection];
  417. if(!database->isPlayerInGameRoom(senderName, gameRoomID))
  418. return sendOperationFailed(connection, "You are not in the room!");
  419. broadcastActiveGameRooms();
  420. }
  421. void LobbyServer::receiveSendInvite(const NetworkConnectionPtr & connection, const JsonNode & json)
  422. {
  423. std::string senderName = activeAccounts[connection];
  424. std::string accountID = json["accountID"].String();
  425. std::string gameRoomID = database->getAccountGameRoom(senderName);
  426. auto targetAccount = findAccount(accountID);
  427. if(!targetAccount)
  428. return sendOperationFailed(connection, "Invalid account to invite!");
  429. if(!database->isPlayerInGameRoom(senderName))
  430. return sendOperationFailed(connection, "You are not in the room!");
  431. if(database->isPlayerInGameRoom(accountID))
  432. return sendOperationFailed(connection, "This player is already in a room!");
  433. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::NOT_INVITED)
  434. return sendOperationFailed(connection, "This player is already invited!");
  435. database->insertGameRoomInvite(accountID, gameRoomID);
  436. sendInviteReceived(targetAccount, senderName, gameRoomID);
  437. }
  438. void LobbyServer::receiveDeclineInvite(const NetworkConnectionPtr & connection, const JsonNode & json)
  439. {
  440. std::string accountID = activeAccounts[connection];
  441. std::string gameRoomID = json["gameRoomID"].String();
  442. if(database->getAccountInviteStatus(accountID, gameRoomID) != LobbyInviteStatus::INVITED)
  443. return sendOperationFailed(connection, "No active invite found!");
  444. database->deleteGameRoomInvite(accountID, gameRoomID);
  445. }
  446. LobbyServer::~LobbyServer() = default;
  447. LobbyServer::LobbyServer(const boost::filesystem::path & databasePath)
  448. : database(std::make_unique<LobbyDatabase>(databasePath))
  449. , networkHandler(INetworkHandler::createHandler())
  450. , networkServer(networkHandler->createServerTCP(*this))
  451. {
  452. }
  453. void LobbyServer::start(uint16_t port)
  454. {
  455. networkServer->start(port);
  456. }
  457. void LobbyServer::run()
  458. {
  459. networkHandler->run();
  460. }