NetPacksLobbyServer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /*
  2. * NetPacksLobbyServer.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 "LobbyNetPackVisitors.h"
  12. #include "CVCMIServer.h"
  13. #include "CGameHandler.h"
  14. #include "../lib/StartInfo.h"
  15. #include "../lib/CRandomGenerator.h"
  16. #include "../lib/campaign/CampaignState.h"
  17. #include "../lib/entities/faction/CTownHandler.h"
  18. #include "../lib/entities/faction/CFaction.h"
  19. #include "../lib/serializer/Connection.h"
  20. #include "../lib/mapping/CMapInfo.h"
  21. #include "../lib/mapping/CMapHeader.h"
  22. #include "../lib/filesystem/Filesystem.h"
  23. void ClientPermissionsCheckerNetPackVisitor::visitForLobby(CPackForLobby & pack)
  24. {
  25. if(pack.isForServer())
  26. {
  27. result = srv.isClientHost(pack.c->connectionID);
  28. }
  29. }
  30. void ApplyOnServerAfterAnnounceNetPackVisitor::visitForLobby(CPackForLobby & pack)
  31. {
  32. // Propagate options after every CLobbyPackToServer
  33. if(pack.isForServer())
  34. {
  35. srv.updateAndPropagateLobbyState();
  36. }
  37. }
  38. void ClientPermissionsCheckerNetPackVisitor::visitLobbyClientConnected(LobbyClientConnected & pack)
  39. {
  40. result = srv.getState() == EServerState::LOBBY;
  41. }
  42. void ApplyOnServerNetPackVisitor::visitLobbyClientConnected(LobbyClientConnected & pack)
  43. {
  44. auto compatibleVersion = std::min(pack.version, ESerializationVersion::CURRENT);
  45. pack.c->setSerializationVersion(compatibleVersion);
  46. srv.clientConnected(pack.c, pack.names, pack.uuid, pack.mode);
  47. // Server need to pass some data to newly connected client
  48. pack.clientId = pack.c->connectionID;
  49. pack.mode = srv.si->mode;
  50. pack.hostClientId = srv.hostClientId;
  51. pack.version = compatibleVersion;
  52. result = true;
  53. }
  54. void ApplyOnServerAfterAnnounceNetPackVisitor::visitLobbyClientConnected(LobbyClientConnected & pack)
  55. {
  56. // FIXME: we need to avoid senting something to client that not yet get answer for LobbyClientConnected
  57. // Until UUID set we only pass LobbyClientConnected to this client
  58. pack.c->uuid = pack.uuid;
  59. srv.updateAndPropagateLobbyState();
  60. // FIXME: what is this??? We do NOT support reconnection into ongoing game - at the very least queries and battles are NOT serialized
  61. // if(srv.getState() == EServerState::GAMEPLAY)
  62. // {
  63. // //immediately start game
  64. // std::unique_ptr<LobbyStartGame> startGameForReconnectedPlayer(new LobbyStartGame);
  65. // startGameForReconnectedPlayer->initializedStartInfo = srv.si;
  66. // startGameForReconnectedPlayer->initializedGameState = srv.gh->gameState();
  67. // startGameForReconnectedPlayer->clientId = pack.c->connectionID;
  68. // srv.announcePack(std::move(startGameForReconnectedPlayer));
  69. // }
  70. }
  71. void ClientPermissionsCheckerNetPackVisitor::visitLobbyClientDisconnected(LobbyClientDisconnected & pack)
  72. {
  73. if(pack.clientId != pack.c->connectionID)
  74. {
  75. result = false;
  76. return;
  77. }
  78. if(pack.shutdownServer)
  79. {
  80. if(!srv.wasStartedByClient())
  81. {
  82. result = false;
  83. return;
  84. }
  85. if(pack.c->connectionID != srv.hostClientId)
  86. {
  87. result = false;
  88. return;
  89. }
  90. }
  91. result = true;
  92. }
  93. void ApplyOnServerNetPackVisitor::visitLobbyClientDisconnected(LobbyClientDisconnected & pack)
  94. {
  95. pack.c->getConnection()->close();
  96. srv.clientDisconnected(pack.c);
  97. result = true;
  98. }
  99. void ApplyOnServerAfterAnnounceNetPackVisitor::visitLobbyClientDisconnected(LobbyClientDisconnected & pack)
  100. {
  101. if(pack.shutdownServer)
  102. {
  103. logNetwork->info("Client requested shutdown, server will close itself...");
  104. srv.setState(EServerState::SHUTDOWN);
  105. return;
  106. }
  107. else if(srv.activeConnections.empty())
  108. {
  109. logNetwork->error("Last connection lost, server will close itself...");
  110. srv.setState(EServerState::SHUTDOWN);
  111. }
  112. else if(pack.c->connectionID == srv.hostClientId)
  113. {
  114. LobbyChangeHost ph;
  115. auto newHost = srv.activeConnections.front();
  116. ph.newHostConnectionId = newHost->connectionID;
  117. srv.announcePack(ph);
  118. }
  119. srv.updateAndPropagateLobbyState();
  120. // if(srv.getState() != EServerState::SHUTDOWN && srv.remoteConnections.count(pack.c))
  121. // {
  122. // srv.remoteConnections -= pack.c;
  123. // srv.connectToRemote();
  124. // }
  125. }
  126. void ClientPermissionsCheckerNetPackVisitor::visitLobbyChatMessage(LobbyChatMessage & pack)
  127. {
  128. result = true;
  129. }
  130. void ApplyOnServerNetPackVisitor::visitLobbySetMap(LobbySetMap & pack)
  131. {
  132. if(srv.getState() != EServerState::LOBBY)
  133. {
  134. result = false;
  135. return;
  136. }
  137. srv.updateStartInfoOnMapChange(pack.mapInfo, pack.mapGenOpts);
  138. result = true;
  139. }
  140. void ApplyOnServerNetPackVisitor::visitLobbySetCampaign(LobbySetCampaign & pack)
  141. {
  142. srv.si->mapname = pack.ourCampaign->getFilename();
  143. srv.si->mode = EStartMode::CAMPAIGN;
  144. srv.si->campState = pack.ourCampaign;
  145. srv.si->turnTimerInfo = TurnTimerInfo{};
  146. bool isCurrentMapConquerable = pack.ourCampaign->currentScenario() && pack.ourCampaign->isAvailable(*pack.ourCampaign->currentScenario());
  147. for(auto scenarioID : pack.ourCampaign->allScenarios())
  148. {
  149. if(pack.ourCampaign->isAvailable(scenarioID))
  150. {
  151. if(!isCurrentMapConquerable || (isCurrentMapConquerable && scenarioID == *pack.ourCampaign->currentScenario()))
  152. {
  153. srv.setCampaignMap(scenarioID);
  154. }
  155. }
  156. }
  157. result = true;
  158. }
  159. void ApplyOnServerNetPackVisitor::visitLobbySetCampaignMap(LobbySetCampaignMap & pack)
  160. {
  161. srv.setCampaignMap(pack.mapId);
  162. result = true;
  163. }
  164. void ApplyOnServerNetPackVisitor::visitLobbySetCampaignBonus(LobbySetCampaignBonus & pack)
  165. {
  166. srv.setCampaignBonus(pack.bonusId);
  167. result = true;
  168. }
  169. void ClientPermissionsCheckerNetPackVisitor::visitLobbyGuiAction(LobbyGuiAction & pack)
  170. {
  171. result = srv.isClientHost(pack.c->connectionID);
  172. }
  173. void ClientPermissionsCheckerNetPackVisitor::visitLobbyRestartGame(LobbyRestartGame & pack)
  174. {
  175. result = srv.isClientHost(pack.c->connectionID);
  176. }
  177. void ApplyOnServerNetPackVisitor::visitLobbyRestartGame(LobbyRestartGame & pack)
  178. {
  179. srv.prepareToRestart();
  180. result = true;
  181. }
  182. void ApplyOnServerAfterAnnounceNetPackVisitor::visitLobbyRestartGame(LobbyRestartGame & pack)
  183. {
  184. for(const auto & connection : srv.activeConnections)
  185. connection->enterLobbyConnectionMode();
  186. }
  187. void ClientPermissionsCheckerNetPackVisitor::visitLobbyPrepareStartGame(LobbyPrepareStartGame & pack)
  188. {
  189. result = srv.isClientHost(pack.c->connectionID);
  190. }
  191. void ClientPermissionsCheckerNetPackVisitor::visitLobbyStartGame(LobbyStartGame & pack)
  192. {
  193. result = srv.isClientHost(pack.c->connectionID);
  194. }
  195. void ApplyOnServerNetPackVisitor::visitLobbyStartGame(LobbyStartGame & pack)
  196. {
  197. try
  198. {
  199. srv.verifyStateBeforeStart(true);
  200. }
  201. catch(...)
  202. {
  203. result = false;
  204. return;
  205. }
  206. // Server will prepare gamestate and we announce StartInfo to clients
  207. if(!srv.prepareToStartGame())
  208. {
  209. result = false;
  210. return;
  211. }
  212. pack.initializedStartInfo = std::make_shared<StartInfo>(*srv.gh->getStartInfo(true));
  213. pack.initializedGameState = srv.gh->gameState();
  214. result = true;
  215. }
  216. void ApplyOnServerAfterAnnounceNetPackVisitor::visitLobbyStartGame(LobbyStartGame & pack)
  217. {
  218. if(pack.clientId == -1) //do not restart game for single client only
  219. srv.startGameImmediately();
  220. else
  221. {
  222. for(const auto & connection : srv.activeConnections)
  223. {
  224. if(connection->connectionID == pack.clientId)
  225. {
  226. connection->enterGameplayConnectionMode(srv.gh->gameState());
  227. srv.reconnectPlayer(pack.clientId);
  228. }
  229. }
  230. }
  231. }
  232. void ClientPermissionsCheckerNetPackVisitor::visitLobbyChangeHost(LobbyChangeHost & pack)
  233. {
  234. result = srv.isClientHost(pack.c->connectionID);
  235. }
  236. void ApplyOnServerNetPackVisitor::visitLobbyChangeHost(LobbyChangeHost & pack)
  237. {
  238. result = true;
  239. }
  240. void ApplyOnServerAfterAnnounceNetPackVisitor::visitLobbyChangeHost(LobbyChangeHost & pack)
  241. {
  242. auto result = srv.passHost(pack.newHostConnectionId);
  243. if(!result)
  244. {
  245. logGlobal->error("passHost returned false. What does it mean?");
  246. }
  247. }
  248. void ClientPermissionsCheckerNetPackVisitor::visitLobbyChangePlayerOption(LobbyChangePlayerOption & pack)
  249. {
  250. if(srv.isClientHost(pack.c->connectionID))
  251. {
  252. result = true;
  253. return;
  254. }
  255. if(vstd::contains(srv.getAllClientPlayers(pack.c->connectionID), pack.color))
  256. {
  257. result = true;
  258. return;
  259. }
  260. result = false;
  261. }
  262. void ApplyOnServerNetPackVisitor::visitLobbyChangePlayerOption(LobbyChangePlayerOption & pack)
  263. {
  264. switch(pack.what)
  265. {
  266. case LobbyChangePlayerOption::TOWN_ID:
  267. srv.optionSetCastle(pack.color, FactionID(pack.value));
  268. break;
  269. case LobbyChangePlayerOption::TOWN:
  270. srv.optionNextCastle(pack.color, pack.value);
  271. break;
  272. case LobbyChangePlayerOption::HERO_ID:
  273. srv.optionSetHero(pack.color, HeroTypeID(pack.value));
  274. break;
  275. case LobbyChangePlayerOption::HERO:
  276. srv.optionNextHero(pack.color, pack.value);
  277. break;
  278. case LobbyChangePlayerOption::BONUS_ID:
  279. srv.optionSetBonus(pack.color, PlayerStartingBonus(pack.value));
  280. break;
  281. case LobbyChangePlayerOption::BONUS:
  282. srv.optionNextBonus(pack.color, pack.value);
  283. break;
  284. }
  285. result = true;
  286. }
  287. void ApplyOnServerNetPackVisitor::visitLobbySetPlayer(LobbySetPlayer & pack)
  288. {
  289. srv.setPlayer(pack.clickedColor);
  290. result = true;
  291. }
  292. void ApplyOnServerNetPackVisitor::visitLobbySetPlayerName(LobbySetPlayerName & pack)
  293. {
  294. srv.setPlayerName(pack.color, pack.name);
  295. result = true;
  296. }
  297. void ApplyOnServerNetPackVisitor::visitLobbySetPlayerHandicap(LobbySetPlayerHandicap & pack)
  298. {
  299. srv.setPlayerHandicap(pack.color, pack.handicap);
  300. result = true;
  301. }
  302. void ApplyOnServerNetPackVisitor::visitLobbySetSimturns(LobbySetSimturns & pack)
  303. {
  304. srv.si->simturnsInfo = pack.simturnsInfo;
  305. result = true;
  306. }
  307. void ApplyOnServerNetPackVisitor::visitLobbySetTurnTime(LobbySetTurnTime & pack)
  308. {
  309. srv.si->turnTimerInfo = pack.turnTimerInfo;
  310. result = true;
  311. }
  312. void ApplyOnServerNetPackVisitor::visitLobbySetExtraOptions(LobbySetExtraOptions & pack)
  313. {
  314. srv.si->extraOptionsInfo = pack.extraOptionsInfo;
  315. result = true;
  316. }
  317. void ApplyOnServerNetPackVisitor::visitLobbySetDifficulty(LobbySetDifficulty & pack)
  318. {
  319. srv.si->difficulty = std::clamp<uint8_t>(pack.difficulty, 0, 4);
  320. result = true;
  321. }
  322. void ApplyOnServerNetPackVisitor::visitLobbyForceSetPlayer(LobbyForceSetPlayer & pack)
  323. {
  324. srv.si->playerInfos[pack.targetPlayerColor].connectedPlayerIDs.insert(pack.targetConnectedPlayer);
  325. result = true;
  326. }
  327. void ClientPermissionsCheckerNetPackVisitor::visitLobbyPvPAction(LobbyPvPAction & pack)
  328. {
  329. result = true;
  330. }
  331. void ApplyOnServerNetPackVisitor::visitLobbyPvPAction(LobbyPvPAction & pack)
  332. {
  333. std::vector<FactionID> allowedTowns;
  334. for (auto const & factionID : VLC->townh->getDefaultAllowed())
  335. if(std::find(pack.bannedTowns.begin(), pack.bannedTowns.end(), factionID) == pack.bannedTowns.end())
  336. allowedTowns.push_back(factionID);
  337. std::vector<FactionID> randomFaction1;
  338. std::sample(allowedTowns.begin(), allowedTowns.end(), std::back_inserter(randomFaction1), 1, std::mt19937{std::random_device{}()});
  339. std::vector<FactionID> randomFaction2;
  340. std::sample(allowedTowns.begin(), allowedTowns.end(), std::back_inserter(randomFaction2), 1, std::mt19937{std::random_device{}()});
  341. MetaString txt;
  342. switch(pack.action) {
  343. case LobbyPvPAction::COIN:
  344. txt.appendTextID("vcmi.lobby.pvp.coin.hover");
  345. txt.appendRawString(" - " + std::to_string(std::rand()%2));
  346. srv.announceTxt(txt);
  347. break;
  348. case LobbyPvPAction::RANDOM_TOWN:
  349. if(!allowedTowns.size())
  350. break;
  351. txt.appendTextID("core.overview.3");
  352. txt.appendRawString(" - ");
  353. txt.appendTextID(VLC->townh->getById(randomFaction1[0])->getNameTextID());
  354. srv.announceTxt(txt);
  355. break;
  356. case LobbyPvPAction::RANDOM_TOWN_VS:
  357. if(!allowedTowns.size())
  358. break;
  359. txt.appendTextID("core.overview.3");
  360. txt.appendRawString(" - ");
  361. txt.appendTextID(VLC->townh->getById(randomFaction1[0])->getNameTextID());
  362. txt.appendRawString(" ");
  363. txt.appendTextID("vcmi.lobby.pvp.versus");
  364. txt.appendRawString(" ");
  365. txt.appendTextID(VLC->townh->getById(randomFaction2[0])->getNameTextID());
  366. srv.announceTxt(txt);
  367. break;
  368. }
  369. result = true;
  370. }
  371. void ClientPermissionsCheckerNetPackVisitor::visitLobbyDelete(LobbyDelete & pack)
  372. {
  373. result = srv.isClientHost(pack.c->connectionID);
  374. }
  375. void ApplyOnServerNetPackVisitor::visitLobbyDelete(LobbyDelete & pack)
  376. {
  377. if(pack.type == LobbyDelete::EType::SAVEGAME || pack.type == LobbyDelete::EType::RANDOMMAP)
  378. {
  379. auto res = ResourcePath(pack.name, pack.type == LobbyDelete::EType::SAVEGAME ? EResType::SAVEGAME : EResType::MAP);
  380. auto name = CResourceHandler::get()->getResourceName(res);
  381. if (!name)
  382. {
  383. logGlobal->error("Failed to find resource with name '%s'", res.getOriginalName());
  384. return;
  385. }
  386. auto file = boost::filesystem::canonical(*name);
  387. boost::filesystem::remove(file);
  388. if(boost::filesystem::is_empty(file.parent_path()))
  389. boost::filesystem::remove(file.parent_path());
  390. }
  391. else if(pack.type == LobbyDelete::EType::SAVEGAME_FOLDER)
  392. {
  393. auto res = ResourcePath("Saves/" + pack.name, EResType::DIRECTORY);
  394. auto name = CResourceHandler::get()->getResourceName(res);
  395. if (!name)
  396. {
  397. logGlobal->error("Failed to find folder with name '%s'", res.getOriginalName());
  398. return;
  399. }
  400. auto folder = boost::filesystem::canonical(*name);
  401. boost::filesystem::remove_all(folder);
  402. }
  403. LobbyUpdateState lus;
  404. lus.state = srv;
  405. lus.refreshList = true;
  406. srv.announcePack(lus);
  407. }