CServerHandler.cpp 25 KB

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