CServerHandler.cpp 25 KB

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