CServerHandler.cpp 25 KB

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