CServerHandler.cpp 25 KB

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