NetPacksLobbyServer.cpp 13 KB

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