CServerHandler.cpp 25 KB

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