CServerHandler.cpp 25 KB

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