CServerHandler.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. /*
  2. * CServerHandler.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 "CServerHandler.h"
  12. #include "Client.h"
  13. #include "CGameInfo.h"
  14. #include "CPlayerInterface.h"
  15. #include "gui/CGuiHandler.h"
  16. #include "gui/WindowHandler.h"
  17. #include "lobby/CSelectionBase.h"
  18. #include "lobby/CLobbyScreen.h"
  19. #include "windows/InfoWindows.h"
  20. #include "mainmenu/CMainMenu.h"
  21. #include "mainmenu/CPrologEpilogVideo.h"
  22. #include "mainmenu/CHighScoreScreen.h"
  23. #ifdef VCMI_ANDROID
  24. #include "../lib/CAndroidVMHelper.h"
  25. #elif defined(VCMI_IOS)
  26. #include "ios/utils.h"
  27. #include <dispatch/dispatch.h>
  28. #endif
  29. #ifdef SINGLE_PROCESS_APP
  30. #include "../server/CVCMIServer.h"
  31. #endif
  32. #include "../lib/CConfigHandler.h"
  33. #include "../lib/CGeneralTextHandler.h"
  34. #include "../lib/CThreadHelper.h"
  35. #include "../lib/NetPackVisitor.h"
  36. #include "../lib/StartInfo.h"
  37. #include "../lib/TurnTimerInfo.h"
  38. #include "../lib/VCMIDirs.h"
  39. #include "../lib/campaign/CampaignState.h"
  40. #include "../lib/mapping/CMapInfo.h"
  41. #include "../lib/mapObjects/MiscObjects.h"
  42. #include "../lib/modding/ModIncompatibility.h"
  43. #include "../lib/rmg/CMapGenOptions.h"
  44. #include "../lib/filesystem/Filesystem.h"
  45. #include "../lib/registerTypes/RegisterTypes.h"
  46. #include "../lib/serializer/Connection.h"
  47. #include "../lib/serializer/CMemorySerializer.h"
  48. #include <boost/uuid/uuid.hpp>
  49. #include <boost/uuid/uuid_io.hpp>
  50. #include <boost/uuid/uuid_generators.hpp>
  51. #include <boost/asio.hpp>
  52. #include "../lib/serializer/Cast.h"
  53. #include "LobbyClientNetPackVisitors.h"
  54. #include <vcmi/events/EventBus.h>
  55. #ifdef VCMI_WINDOWS
  56. #include <windows.h>
  57. #endif
  58. template<typename T> class CApplyOnLobby;
  59. const std::string CServerHandler::localhostAddress{"127.0.0.1"};
  60. #if defined(VCMI_ANDROID) && !defined(SINGLE_PROCESS_APP)
  61. extern std::atomic_bool androidTestServerReadyFlag;
  62. #endif
  63. class CBaseForLobbyApply
  64. {
  65. public:
  66. virtual bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const = 0;
  67. virtual void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const = 0;
  68. virtual ~CBaseForLobbyApply(){};
  69. template<typename U> static CBaseForLobbyApply * getApplier(const U * t = nullptr)
  70. {
  71. return new CApplyOnLobby<U>();
  72. }
  73. };
  74. template<typename T> class CApplyOnLobby : public CBaseForLobbyApply
  75. {
  76. public:
  77. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  78. {
  79. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  80. T * ptr = static_cast<T *>(pack);
  81. ApplyOnLobbyHandlerNetPackVisitor visitor(*handler);
  82. logNetwork->trace("\tImmediately apply on lobby: %s", typeList.getTypeInfo(ptr)->name());
  83. ptr->visit(visitor);
  84. return visitor.getResult();
  85. }
  86. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  87. {
  88. T * ptr = static_cast<T *>(pack);
  89. ApplyOnLobbyScreenNetPackVisitor visitor(*handler, lobby);
  90. logNetwork->trace("\tApply on lobby from queue: %s", typeList.getTypeInfo(ptr)->name());
  91. ptr->visit(visitor);
  92. }
  93. };
  94. template<> class CApplyOnLobby<CPack>: public CBaseForLobbyApply
  95. {
  96. public:
  97. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  98. {
  99. logGlobal->error("Cannot apply plain CPack!");
  100. assert(0);
  101. return false;
  102. }
  103. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  104. {
  105. logGlobal->error("Cannot apply plain CPack!");
  106. assert(0);
  107. }
  108. };
  109. static const std::string NAME_AFFIX = "client";
  110. static const std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  111. CServerHandler::CServerHandler()
  112. : state(EClientState::NONE), mx(std::make_shared<boost::recursive_mutex>()), client(nullptr), loadMode(0), campaignStateToSend(nullptr), campaignServerRestartLock(false)
  113. {
  114. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  115. //read from file to restore last session
  116. if(!settings["server"]["uuid"].isNull() && !settings["server"]["uuid"].String().empty())
  117. uuid = settings["server"]["uuid"].String();
  118. applier = std::make_shared<CApplier<CBaseForLobbyApply>>();
  119. registerTypesLobbyPacks(*applier);
  120. }
  121. void CServerHandler::resetStateForLobby(const StartInfo::EMode mode, const std::vector<std::string> * names)
  122. {
  123. hostClientId = -1;
  124. state = EClientState::NONE;
  125. mapToStart = nullptr;
  126. th = std::make_unique<CStopWatch>();
  127. packsForLobbyScreen.clear();
  128. c.reset();
  129. si = std::make_shared<StartInfo>();
  130. playerNames.clear();
  131. si->difficulty = 1;
  132. si->mode = mode;
  133. myNames.clear();
  134. if(names && !names->empty()) //if have custom set of player names - use it
  135. myNames = *names;
  136. else
  137. myNames.push_back(settings["general"]["playerName"].String());
  138. }
  139. void CServerHandler::startLocalServerAndConnect()
  140. {
  141. if(threadRunLocalServer)
  142. threadRunLocalServer->join();
  143. th->update();
  144. auto errorMsg = CGI->generaltexth->translate("vcmi.server.errors.existingProcess");
  145. try
  146. {
  147. CConnection testConnection(localhostAddress, getDefaultPort(), NAME, uuid);
  148. logNetwork->error("Port is busy, check if another instance of vcmiserver is working");
  149. CInfoWindow::showInfoDialog(errorMsg, {});
  150. return;
  151. }
  152. catch(std::runtime_error & error)
  153. {
  154. //no connection means that port is not busy and we can start local server
  155. }
  156. #if defined(SINGLE_PROCESS_APP)
  157. boost::condition_variable cond;
  158. std::vector<std::string> args{"--uuid=" + uuid, "--port=" + std::to_string(getHostPort())};
  159. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  160. {
  161. args.push_back("--lobby=" + settings["session"]["address"].String());
  162. args.push_back("--connections=" + settings["session"]["hostConnections"].String());
  163. args.push_back("--lobby-port=" + std::to_string(settings["session"]["port"].Integer()));
  164. args.push_back("--lobby-uuid=" + settings["session"]["hostUuid"].String());
  165. }
  166. threadRunLocalServer = std::make_shared<boost::thread>([&cond, args, this] {
  167. setThreadName("CVCMIServer");
  168. CVCMIServer::create(&cond, args);
  169. onServerFinished();
  170. });
  171. threadRunLocalServer->detach();
  172. #elif defined(VCMI_ANDROID)
  173. {
  174. CAndroidVMHelper envHelper;
  175. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "startServer", true);
  176. }
  177. #else
  178. threadRunLocalServer = std::make_shared<boost::thread>(&CServerHandler::threadRunServer, this); //runs server executable;
  179. #endif
  180. logNetwork->trace("Setting up thread calling server: %d ms", th->getDiff());
  181. th->update();
  182. #ifdef SINGLE_PROCESS_APP
  183. {
  184. #ifdef VCMI_IOS
  185. dispatch_sync(dispatch_get_main_queue(), ^{
  186. iOS_utils::showLoadingIndicator();
  187. });
  188. #endif
  189. boost::mutex m;
  190. boost::unique_lock<boost::mutex> lock{m};
  191. logNetwork->info("waiting for server");
  192. cond.wait(lock);
  193. logNetwork->info("server is ready");
  194. #ifdef VCMI_IOS
  195. dispatch_sync(dispatch_get_main_queue(), ^{
  196. iOS_utils::hideLoadingIndicator();
  197. });
  198. #endif
  199. }
  200. #elif defined(VCMI_ANDROID)
  201. logNetwork->info("waiting for server");
  202. while(!androidTestServerReadyFlag.load())
  203. {
  204. logNetwork->info("still waiting...");
  205. boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
  206. }
  207. logNetwork->info("waiting for server finished...");
  208. androidTestServerReadyFlag = false;
  209. #endif
  210. logNetwork->trace("Waiting for server: %d ms", th->getDiff());
  211. th->update(); //put breakpoint here to attach to server before it does something stupid
  212. justConnectToServer(localhostAddress, 0);
  213. logNetwork->trace("\tConnecting to the server: %d ms", th->getDiff());
  214. }
  215. void CServerHandler::justConnectToServer(const std::string & addr, const ui16 port)
  216. {
  217. state = EClientState::CONNECTING;
  218. while(!c && state != EClientState::CONNECTION_CANCELLED)
  219. {
  220. try
  221. {
  222. logNetwork->info("Establishing connection...");
  223. c = std::make_shared<CConnection>(
  224. addr.size() ? addr : getHostAddress(),
  225. port ? port : getHostPort(),
  226. NAME, uuid);
  227. }
  228. catch(std::runtime_error & error)
  229. {
  230. logNetwork->warn("\nCannot establish connection. %s Retrying in 1 second", error.what());
  231. boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
  232. }
  233. }
  234. if(state == EClientState::CONNECTION_CANCELLED)
  235. {
  236. logNetwork->info("Connection aborted by player!");
  237. return;
  238. }
  239. c->handler = std::make_shared<boost::thread>(&CServerHandler::threadHandleConnection, this);
  240. if(!addr.empty() && addr != getHostAddress())
  241. {
  242. Settings serverAddress = settings.write["server"]["server"];
  243. serverAddress->String() = addr;
  244. }
  245. if(port && port != getHostPort())
  246. {
  247. Settings serverPort = settings.write["server"]["port"];
  248. serverPort->Integer() = port;
  249. }
  250. }
  251. void CServerHandler::applyPacksOnLobbyScreen()
  252. {
  253. if(!c || !c->handler)
  254. return;
  255. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  256. while(!packsForLobbyScreen.empty())
  257. {
  258. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  259. CPackForLobby * pack = packsForLobbyScreen.front();
  260. packsForLobbyScreen.pop_front();
  261. CBaseForLobbyApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  262. apply->applyOnLobbyScreen(static_cast<CLobbyScreen *>(SEL), this, pack);
  263. GH.windows().totalRedraw();
  264. delete pack;
  265. }
  266. }
  267. void CServerHandler::stopServerConnection()
  268. {
  269. if(c->handler)
  270. {
  271. while(!c->handler->timed_join(boost::chrono::milliseconds(50)))
  272. applyPacksOnLobbyScreen();
  273. c->handler->join();
  274. }
  275. }
  276. std::set<PlayerColor> CServerHandler::getHumanColors()
  277. {
  278. return clientHumanColors(c->connectionID);
  279. }
  280. PlayerColor CServerHandler::myFirstColor() const
  281. {
  282. return clientFirstColor(c->connectionID);
  283. }
  284. bool CServerHandler::isMyColor(PlayerColor color) const
  285. {
  286. return isClientColor(c->connectionID, color);
  287. }
  288. ui8 CServerHandler::myFirstId() const
  289. {
  290. return clientFirstId(c->connectionID);
  291. }
  292. bool CServerHandler::isServerLocal() const
  293. {
  294. if(threadRunLocalServer)
  295. return true;
  296. return false;
  297. }
  298. bool CServerHandler::isHost() const
  299. {
  300. return c && hostClientId == c->connectionID;
  301. }
  302. bool CServerHandler::isGuest() const
  303. {
  304. return !c || hostClientId != c->connectionID;
  305. }
  306. ui16 CServerHandler::getDefaultPort()
  307. {
  308. return static_cast<ui16>(settings["server"]["port"].Integer());
  309. }
  310. std::string CServerHandler::getDefaultPortStr()
  311. {
  312. return std::to_string(getDefaultPort());
  313. }
  314. std::string CServerHandler::getHostAddress() const
  315. {
  316. if(settings["session"]["lobby"].isNull() || !settings["session"]["lobby"].Bool())
  317. return settings["server"]["server"].String();
  318. if(settings["session"]["host"].Bool())
  319. return localhostAddress;
  320. return settings["session"]["address"].String();
  321. }
  322. ui16 CServerHandler::getHostPort() const
  323. {
  324. if(settings["session"]["lobby"].isNull() || !settings["session"]["lobby"].Bool())
  325. return getDefaultPort();
  326. if(settings["session"]["host"].Bool())
  327. return getDefaultPort();
  328. return settings["session"]["port"].Integer();
  329. }
  330. void CServerHandler::sendClientConnecting() const
  331. {
  332. LobbyClientConnected lcc;
  333. lcc.uuid = uuid;
  334. lcc.names = myNames;
  335. lcc.mode = si->mode;
  336. sendLobbyPack(lcc);
  337. }
  338. void CServerHandler::sendClientDisconnecting()
  339. {
  340. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  341. if(state == EClientState::DISCONNECTING)
  342. return;
  343. state = EClientState::DISCONNECTING;
  344. mapToStart = nullptr;
  345. LobbyClientDisconnected lcd;
  346. lcd.clientId = c->connectionID;
  347. logNetwork->info("Connection has been requested to be closed.");
  348. if(isServerLocal())
  349. {
  350. lcd.shutdownServer = true;
  351. logNetwork->info("Sent closing signal to the server");
  352. }
  353. else
  354. {
  355. logNetwork->info("Sent leaving signal to the server");
  356. }
  357. sendLobbyPack(lcd);
  358. c->close();
  359. c.reset();
  360. }
  361. void CServerHandler::setCampaignState(std::shared_ptr<CampaignState> newCampaign)
  362. {
  363. state = EClientState::LOBBY_CAMPAIGN;
  364. LobbySetCampaign lsc;
  365. lsc.ourCampaign = newCampaign;
  366. sendLobbyPack(lsc);
  367. }
  368. void CServerHandler::setCampaignMap(CampaignScenarioID mapId) const
  369. {
  370. if(state == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  371. return;
  372. LobbySetCampaignMap lscm;
  373. lscm.mapId = mapId;
  374. sendLobbyPack(lscm);
  375. }
  376. void CServerHandler::setCampaignBonus(int bonusId) const
  377. {
  378. if(state == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  379. return;
  380. LobbySetCampaignBonus lscb;
  381. lscb.bonusId = bonusId;
  382. sendLobbyPack(lscb);
  383. }
  384. void CServerHandler::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  385. {
  386. LobbySetMap lsm;
  387. lsm.mapInfo = to;
  388. lsm.mapGenOpts = mapGenOpts;
  389. sendLobbyPack(lsm);
  390. }
  391. void CServerHandler::setPlayer(PlayerColor color) const
  392. {
  393. LobbySetPlayer lsp;
  394. lsp.clickedColor = color;
  395. sendLobbyPack(lsp);
  396. }
  397. void CServerHandler::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  398. {
  399. LobbyChangePlayerOption lcpo;
  400. lcpo.what = what;
  401. lcpo.value = value;
  402. lcpo.color = player;
  403. sendLobbyPack(lcpo);
  404. }
  405. void CServerHandler::setDifficulty(int to) const
  406. {
  407. LobbySetDifficulty lsd;
  408. lsd.difficulty = to;
  409. sendLobbyPack(lsd);
  410. }
  411. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  412. {
  413. LobbySetSimturns pack;
  414. pack.simturnsInfo = info;
  415. sendLobbyPack(pack);
  416. }
  417. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  418. {
  419. LobbySetTurnTime lstt;
  420. lstt.turnTimerInfo = info;
  421. sendLobbyPack(lstt);
  422. }
  423. void CServerHandler::sendMessage(const std::string & txt) const
  424. {
  425. std::istringstream readed;
  426. readed.str(txt);
  427. std::string command;
  428. readed >> command;
  429. if(command == "!passhost")
  430. {
  431. std::string id;
  432. readed >> id;
  433. if(id.length())
  434. {
  435. LobbyChangeHost lch;
  436. lch.newHostConnectionId = boost::lexical_cast<int>(id);
  437. sendLobbyPack(lch);
  438. }
  439. }
  440. else if(command == "!forcep")
  441. {
  442. std::string connectedId, playerColorId;
  443. readed >> connectedId;
  444. readed >> playerColorId;
  445. if(connectedId.length() && playerColorId.length())
  446. {
  447. ui8 connected = boost::lexical_cast<int>(connectedId);
  448. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  449. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  450. {
  451. LobbyForceSetPlayer lfsp;
  452. lfsp.targetConnectedPlayer = connected;
  453. lfsp.targetPlayerColor = color;
  454. sendLobbyPack(lfsp);
  455. }
  456. }
  457. }
  458. else
  459. {
  460. LobbyChatMessage lcm;
  461. lcm.message = txt;
  462. lcm.playerName = playerNames.find(myFirstId())->second.name;
  463. sendLobbyPack(lcm);
  464. }
  465. }
  466. void CServerHandler::sendGuiAction(ui8 action) const
  467. {
  468. LobbyGuiAction lga;
  469. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  470. sendLobbyPack(lga);
  471. }
  472. void CServerHandler::sendRestartGame() const
  473. {
  474. GH.windows().createAndPushWindow<CLoadingScreen>();
  475. LobbyEndGame endGame;
  476. endGame.closeConnection = false;
  477. endGame.restart = true;
  478. sendLobbyPack(endGame);
  479. }
  480. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  481. {
  482. try
  483. {
  484. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  485. }
  486. catch(ModIncompatibility & e)
  487. {
  488. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  489. std::string errorMsg;
  490. if(!e.whatMissing().empty())
  491. {
  492. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  493. errorMsg += e.whatMissing();
  494. }
  495. if(!e.whatExcessive().empty())
  496. {
  497. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  498. errorMsg += e.whatExcessive();
  499. }
  500. showServerError(errorMsg);
  501. return false;
  502. }
  503. catch(std::exception & e)
  504. {
  505. logGlobal->error("Exception during startScenario: %s", e.what());
  506. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  507. return false;
  508. }
  509. return true;
  510. }
  511. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  512. {
  513. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  514. GH.windows().createAndPushWindow<CLoadingScreen>();
  515. LobbyStartGame lsg;
  516. if(client)
  517. {
  518. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  519. lsg.initializedStartInfo->mode = StartInfo::NEW_GAME;
  520. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  521. * si = * lsg.initializedStartInfo;
  522. }
  523. sendLobbyPack(lsg);
  524. c->enterLobbyConnectionMode();
  525. c->disableStackSendingByID();
  526. }
  527. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  528. {
  529. mapToStart = to;
  530. }
  531. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  532. {
  533. if(CMM)
  534. CMM->disable();
  535. client = new CClient();
  536. highScoreCalc = nullptr;
  537. switch(si->mode)
  538. {
  539. case StartInfo::NEW_GAME:
  540. client->newGame(gameState);
  541. break;
  542. case StartInfo::CAMPAIGN:
  543. client->newGame(gameState);
  544. break;
  545. case StartInfo::LOAD_GAME:
  546. client->loadGame(gameState);
  547. break;
  548. default:
  549. throw std::runtime_error("Invalid mode");
  550. }
  551. // After everything initialized we can accept CPackToClient netpacks
  552. c->enterGameplayConnectionMode(client->gameState());
  553. state = EClientState::GAMEPLAY;
  554. //store settings to continue game
  555. if(!isServerLocal() && isGuest())
  556. {
  557. Settings saveSession = settings.write["server"]["reconnect"];
  558. saveSession->Bool() = true;
  559. Settings saveUuid = settings.write["server"]["uuid"];
  560. saveUuid->String() = uuid;
  561. Settings saveNames = settings.write["server"]["names"];
  562. saveNames->Vector().clear();
  563. for(auto & name : myNames)
  564. {
  565. JsonNode jsonName;
  566. jsonName.String() = name;
  567. saveNames->Vector().push_back(jsonName);
  568. }
  569. }
  570. }
  571. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  572. {
  573. client->endGame();
  574. vstd::clear_pointer(client);
  575. if(closeConnection)
  576. {
  577. // Game is ending
  578. // Tell the network thread to reach a stable state
  579. CSH->sendClientDisconnecting();
  580. logNetwork->info("Closed connection.");
  581. }
  582. if(!restart)
  583. {
  584. if(CMM)
  585. {
  586. GH.curInt = CMM.get();
  587. CMM->enable();
  588. }
  589. else
  590. {
  591. GH.curInt = CMainMenu::create().get();
  592. }
  593. }
  594. c->enterLobbyConnectionMode();
  595. c->disableStackSendingByID();
  596. //reset settings
  597. Settings saveSession = settings.write["server"]["reconnect"];
  598. saveSession->Bool() = false;
  599. }
  600. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs)
  601. {
  602. std::shared_ptr<CampaignState> ourCampaign = cs;
  603. if (!cs)
  604. ourCampaign = si->campState;
  605. if(highScoreCalc == nullptr)
  606. {
  607. highScoreCalc = std::make_shared<HighScoreCalculation>();
  608. highScoreCalc->isCampaign = true;
  609. highScoreCalc->parameters.clear();
  610. }
  611. param.campaignName = cs->getNameTranslated();
  612. highScoreCalc->parameters.push_back(param);
  613. GH.dispatchMainThread([ourCampaign, this]()
  614. {
  615. CSH->campaignServerRestartLock.set(true);
  616. CSH->endGameplay();
  617. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  618. auto finisher = [=]()
  619. {
  620. if(ourCampaign->campaignSet != "")
  621. {
  622. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  623. entry->Bool() = true;
  624. }
  625. GH.windows().pushWindow(CMM);
  626. GH.windows().pushWindow(CMM->menu);
  627. if(!ourCampaign->isCampaignFinished())
  628. CMM->openCampaignLobby(ourCampaign);
  629. else
  630. {
  631. CMM->openCampaignScreen(ourCampaign->campaignSet);
  632. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *highScoreCalc);
  633. }
  634. };
  635. if(epilogue.hasPrologEpilog)
  636. {
  637. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  638. }
  639. else
  640. {
  641. CSH->campaignServerRestartLock.waitUntil(false);
  642. finisher();
  643. }
  644. });
  645. }
  646. void CServerHandler::showServerError(const std::string & txt) const
  647. {
  648. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  649. GH.windows().popWindow(w);
  650. CInfoWindow::showInfoDialog(txt, {});
  651. }
  652. int CServerHandler::howManyPlayerInterfaces()
  653. {
  654. int playerInts = 0;
  655. for(auto pint : client->playerint)
  656. {
  657. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  658. playerInts++;
  659. }
  660. return playerInts;
  661. }
  662. ui8 CServerHandler::getLoadMode()
  663. {
  664. if(loadMode != ELoadMode::TUTORIAL && state == EClientState::GAMEPLAY)
  665. {
  666. if(si->campState)
  667. return ELoadMode::CAMPAIGN;
  668. for(auto pn : playerNames)
  669. {
  670. if(pn.second.connection != c->connectionID)
  671. return ELoadMode::MULTI;
  672. }
  673. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  674. return ELoadMode::MULTI;
  675. return ELoadMode::SINGLE;
  676. }
  677. return loadMode;
  678. }
  679. void CServerHandler::restoreLastSession()
  680. {
  681. auto loadSession = [this]()
  682. {
  683. uuid = settings["server"]["uuid"].String();
  684. for(auto & name : settings["server"]["names"].Vector())
  685. myNames.push_back(name.String());
  686. resetStateForLobby(StartInfo::LOAD_GAME, &myNames);
  687. screenType = ESelectionScreen::loadGame;
  688. justConnectToServer(settings["server"]["server"].String(), settings["server"]["port"].Integer());
  689. };
  690. auto cleanUpSession = []()
  691. {
  692. //reset settings
  693. Settings saveSession = settings.write["server"]["reconnect"];
  694. saveSession->Bool() = false;
  695. };
  696. CInfoWindow::showYesNoDialog(VLC->generaltexth->translate("vcmi.server.confirmReconnect"), {}, loadSession, cleanUpSession);
  697. }
  698. void CServerHandler::debugStartTest(std::string filename, bool save)
  699. {
  700. logGlobal->info("Starting debug test with file: %s", filename);
  701. auto mapInfo = std::make_shared<CMapInfo>();
  702. if(save)
  703. {
  704. resetStateForLobby(StartInfo::LOAD_GAME);
  705. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  706. screenType = ESelectionScreen::loadGame;
  707. }
  708. else
  709. {
  710. resetStateForLobby(StartInfo::NEW_GAME);
  711. mapInfo->mapInit(filename);
  712. screenType = ESelectionScreen::newGame;
  713. }
  714. if(settings["session"]["donotstartserver"].Bool())
  715. justConnectToServer(localhostAddress, 3030);
  716. else
  717. startLocalServerAndConnect();
  718. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  719. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  720. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  721. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  722. {
  723. setMapInfo(mapInfo);
  724. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  725. }
  726. // "Click" on color to remove us from it
  727. setPlayer(myFirstColor());
  728. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  729. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  730. while(true)
  731. {
  732. try
  733. {
  734. sendStartGame();
  735. break;
  736. }
  737. catch(...)
  738. {
  739. }
  740. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  741. }
  742. }
  743. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  744. {
  745. private:
  746. CServerHandler & handler;
  747. public:
  748. ServerHandlerCPackVisitor(CServerHandler & handler)
  749. :handler(handler)
  750. {
  751. }
  752. virtual bool callTyped() override { return false; }
  753. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  754. {
  755. handler.visitForLobby(lobbyPack);
  756. }
  757. virtual void visitForClient(CPackForClient & clientPack) override
  758. {
  759. handler.visitForClient(clientPack);
  760. }
  761. };
  762. void CServerHandler::threadHandleConnection()
  763. {
  764. setThreadName("handleConnection");
  765. c->enterLobbyConnectionMode();
  766. try
  767. {
  768. sendClientConnecting();
  769. while(c->connected)
  770. {
  771. while(state == EClientState::STARTING)
  772. boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
  773. CPack * pack = c->retrievePack();
  774. if(state == EClientState::DISCONNECTING)
  775. {
  776. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  777. // Though currently they'll be delivered and might cause crash.
  778. vstd::clear_pointer(pack);
  779. }
  780. else
  781. {
  782. ServerHandlerCPackVisitor visitor(*this);
  783. pack->visit(visitor);
  784. }
  785. }
  786. }
  787. //catch only asio exceptions
  788. catch(const boost::system::system_error & e)
  789. {
  790. if(state == EClientState::DISCONNECTING)
  791. {
  792. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  793. }
  794. else
  795. {
  796. if (e.code() == boost::asio::error::eof)
  797. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  798. else
  799. logNetwork->error("Lost connection to server, ending listening thread! Reason: %s", e.what());
  800. if(client)
  801. {
  802. state = EClientState::DISCONNECTING;
  803. GH.dispatchMainThread([]()
  804. {
  805. CSH->endGameplay();
  806. GH.defActionsDef = 63;
  807. CMM->menu->switchToTab("main");
  808. });
  809. }
  810. else
  811. {
  812. auto lcd = new LobbyClientDisconnected();
  813. lcd->clientId = c->connectionID;
  814. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  815. packsForLobbyScreen.push_back(lcd);
  816. }
  817. }
  818. }
  819. }
  820. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  821. {
  822. if(applier->getApplier(typeList.getTypeID(&lobbyPack))->applyOnLobbyHandler(this, &lobbyPack))
  823. {
  824. if(!settings["session"]["headless"].Bool())
  825. {
  826. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  827. packsForLobbyScreen.push_back(&lobbyPack);
  828. }
  829. }
  830. }
  831. void CServerHandler::visitForClient(CPackForClient & clientPack)
  832. {
  833. client->handlePack(&clientPack);
  834. }
  835. void CServerHandler::threadRunServer()
  836. {
  837. #if !defined(VCMI_MOBILE)
  838. setThreadName("runServer");
  839. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  840. std::string comm = VCMIDirs::get().serverPath().string()
  841. + " --port=" + std::to_string(getHostPort())
  842. + " --run-by-client"
  843. + " --uuid=" + uuid;
  844. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  845. {
  846. comm += " --lobby=" + settings["session"]["address"].String();
  847. comm += " --connections=" + settings["session"]["hostConnections"].String();
  848. comm += " --lobby-port=" + std::to_string(settings["session"]["port"].Integer());
  849. comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
  850. }
  851. comm += " > \"" + logName + '\"';
  852. logGlobal->info("Server command line: %s", comm);
  853. #ifdef VCMI_WINDOWS
  854. int result = -1;
  855. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  856. if(bufSize > 0)
  857. {
  858. std::wstring wComm(bufSize, {});
  859. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  860. if(convertResult > 0)
  861. result = ::_wsystem(wComm.c_str());
  862. else
  863. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  864. }
  865. else
  866. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  867. #else
  868. int result = std::system(comm.c_str());
  869. #endif
  870. if (result == 0)
  871. {
  872. logNetwork->info("Server closed correctly");
  873. }
  874. else
  875. {
  876. logNetwork->error("Error: server failed to close correctly or crashed!");
  877. logNetwork->error("Check %s for more info", logName);
  878. }
  879. onServerFinished();
  880. #endif
  881. }
  882. void CServerHandler::onServerFinished()
  883. {
  884. threadRunLocalServer.reset();
  885. CSH->campaignServerRestartLock.setn(false);
  886. }
  887. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  888. {
  889. if(state != EClientState::STARTING)
  890. c->sendPack(&pack);
  891. }