CServerHandler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. GH.windows().createAndPushWindow<CLoadingScreen>();
  466. LobbyEndGame endGame;
  467. endGame.closeConnection = false;
  468. endGame.restart = true;
  469. sendLobbyPack(endGame);
  470. }
  471. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  472. {
  473. try
  474. {
  475. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  476. }
  477. catch(ModIncompatibility & e)
  478. {
  479. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  480. std::string errorMsg;
  481. if(!e.whatMissing().empty())
  482. {
  483. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  484. errorMsg += e.whatMissing();
  485. }
  486. if(!e.whatExcessive().empty())
  487. {
  488. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  489. errorMsg += e.whatExcessive();
  490. }
  491. showServerError(errorMsg);
  492. return false;
  493. }
  494. catch(std::exception & e)
  495. {
  496. logGlobal->error("Exception during startScenario: %s", e.what());
  497. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  498. return false;
  499. }
  500. return true;
  501. }
  502. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  503. {
  504. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  505. GH.windows().createAndPushWindow<CLoadingScreen>();
  506. LobbyStartGame lsg;
  507. if(client)
  508. {
  509. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  510. lsg.initializedStartInfo->mode = StartInfo::NEW_GAME;
  511. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  512. * si = * lsg.initializedStartInfo;
  513. }
  514. sendLobbyPack(lsg);
  515. c->enterLobbyConnectionMode();
  516. c->disableStackSendingByID();
  517. }
  518. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  519. {
  520. mapToStart = to;
  521. }
  522. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  523. {
  524. setThreadName("startGameplay");
  525. if(CMM)
  526. CMM->disable();
  527. client = new CClient();
  528. switch(si->mode)
  529. {
  530. case StartInfo::NEW_GAME:
  531. client->newGame(gameState);
  532. break;
  533. case StartInfo::CAMPAIGN:
  534. client->newGame(gameState);
  535. break;
  536. case StartInfo::LOAD_GAME:
  537. client->loadGame(gameState);
  538. break;
  539. default:
  540. throw std::runtime_error("Invalid mode");
  541. }
  542. // After everything initialized we can accept CPackToClient netpacks
  543. c->enterGameplayConnectionMode(client->gameState());
  544. state = EClientState::GAMEPLAY;
  545. //store settings to continue game
  546. if(!isServerLocal() && isGuest())
  547. {
  548. Settings saveSession = settings.write["server"]["reconnect"];
  549. saveSession->Bool() = true;
  550. Settings saveUuid = settings.write["server"]["uuid"];
  551. saveUuid->String() = uuid;
  552. Settings saveNames = settings.write["server"]["names"];
  553. saveNames->Vector().clear();
  554. for(auto & name : myNames)
  555. {
  556. JsonNode jsonName;
  557. jsonName.String() = name;
  558. saveNames->Vector().push_back(jsonName);
  559. }
  560. }
  561. }
  562. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  563. {
  564. client->endGame();
  565. vstd::clear_pointer(client);
  566. if(closeConnection)
  567. {
  568. // Game is ending
  569. // Tell the network thread to reach a stable state
  570. CSH->sendClientDisconnecting();
  571. logNetwork->info("Closed connection.");
  572. }
  573. if(!restart)
  574. {
  575. if(CMM)
  576. {
  577. GH.curInt = CMM.get();
  578. CMM->enable();
  579. }
  580. else
  581. {
  582. GH.curInt = CMainMenu::create().get();
  583. }
  584. }
  585. c->enterLobbyConnectionMode();
  586. c->disableStackSendingByID();
  587. //reset settings
  588. Settings saveSession = settings.write["server"]["reconnect"];
  589. saveSession->Bool() = false;
  590. }
  591. void CServerHandler::startCampaignScenario(std::shared_ptr<CampaignState> cs)
  592. {
  593. std::shared_ptr<CampaignState> ourCampaign = cs;
  594. if (!cs)
  595. ourCampaign = si->campState;
  596. GH.dispatchMainThread([ourCampaign]()
  597. {
  598. CSH->campaignServerRestartLock.set(true);
  599. CSH->endGameplay();
  600. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  601. auto finisher = [=]()
  602. {
  603. if(!ourCampaign->isCampaignFinished())
  604. {
  605. GH.windows().pushWindow(CMM);
  606. GH.windows().pushWindow(CMM->menu);
  607. CMM->openCampaignLobby(ourCampaign);
  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. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  624. GH.windows().popWindow(w);
  625. CInfoWindow::showInfoDialog(txt, {});
  626. }
  627. int CServerHandler::howManyPlayerInterfaces()
  628. {
  629. int playerInts = 0;
  630. for(auto pint : client->playerint)
  631. {
  632. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  633. playerInts++;
  634. }
  635. return playerInts;
  636. }
  637. ui8 CServerHandler::getLoadMode()
  638. {
  639. if(loadMode != ELoadMode::TUTORIAL && state == EClientState::GAMEPLAY)
  640. {
  641. if(si->campState)
  642. return ELoadMode::CAMPAIGN;
  643. for(auto pn : playerNames)
  644. {
  645. if(pn.second.connection != c->connectionID)
  646. return ELoadMode::MULTI;
  647. }
  648. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  649. return ELoadMode::MULTI;
  650. return ELoadMode::SINGLE;
  651. }
  652. return loadMode;
  653. }
  654. void CServerHandler::restoreLastSession()
  655. {
  656. auto loadSession = [this]()
  657. {
  658. uuid = settings["server"]["uuid"].String();
  659. for(auto & name : settings["server"]["names"].Vector())
  660. myNames.push_back(name.String());
  661. resetStateForLobby(StartInfo::LOAD_GAME, &myNames);
  662. screenType = ESelectionScreen::loadGame;
  663. justConnectToServer(settings["server"]["server"].String(), settings["server"]["port"].Integer());
  664. };
  665. auto cleanUpSession = []()
  666. {
  667. //reset settings
  668. Settings saveSession = settings.write["server"]["reconnect"];
  669. saveSession->Bool() = false;
  670. };
  671. CInfoWindow::showYesNoDialog(VLC->generaltexth->translate("vcmi.server.confirmReconnect"), {}, loadSession, cleanUpSession);
  672. }
  673. void CServerHandler::debugStartTest(std::string filename, bool save)
  674. {
  675. logGlobal->info("Starting debug test with file: %s", filename);
  676. auto mapInfo = std::make_shared<CMapInfo>();
  677. if(save)
  678. {
  679. resetStateForLobby(StartInfo::LOAD_GAME);
  680. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  681. screenType = ESelectionScreen::loadGame;
  682. }
  683. else
  684. {
  685. resetStateForLobby(StartInfo::NEW_GAME);
  686. mapInfo->mapInit(filename);
  687. screenType = ESelectionScreen::newGame;
  688. }
  689. if(settings["session"]["donotstartserver"].Bool())
  690. justConnectToServer(localhostAddress, 3030);
  691. else
  692. startLocalServerAndConnect();
  693. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  694. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  695. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  696. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  697. {
  698. setMapInfo(mapInfo);
  699. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  700. }
  701. // "Click" on color to remove us from it
  702. setPlayer(myFirstColor());
  703. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  704. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  705. while(true)
  706. {
  707. try
  708. {
  709. sendStartGame();
  710. break;
  711. }
  712. catch(...)
  713. {
  714. }
  715. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  716. }
  717. }
  718. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  719. {
  720. private:
  721. CServerHandler & handler;
  722. public:
  723. ServerHandlerCPackVisitor(CServerHandler & handler)
  724. :handler(handler)
  725. {
  726. }
  727. virtual bool callTyped() override { return false; }
  728. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  729. {
  730. handler.visitForLobby(lobbyPack);
  731. }
  732. virtual void visitForClient(CPackForClient & clientPack) override
  733. {
  734. handler.visitForClient(clientPack);
  735. }
  736. };
  737. void CServerHandler::threadHandleConnection()
  738. {
  739. setThreadName("handleConnection");
  740. c->enterLobbyConnectionMode();
  741. try
  742. {
  743. sendClientConnecting();
  744. while(c->connected)
  745. {
  746. while(state == EClientState::STARTING)
  747. boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
  748. CPack * pack = c->retrievePack();
  749. if(state == EClientState::DISCONNECTING)
  750. {
  751. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  752. // Though currently they'll be delivered and might cause crash.
  753. vstd::clear_pointer(pack);
  754. }
  755. else
  756. {
  757. ServerHandlerCPackVisitor visitor(*this);
  758. pack->visit(visitor);
  759. }
  760. }
  761. }
  762. //catch only asio exceptions
  763. catch(const boost::system::system_error & e)
  764. {
  765. if(state == EClientState::DISCONNECTING)
  766. {
  767. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  768. }
  769. else
  770. {
  771. if (e.code() == boost::asio::error::eof)
  772. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  773. else
  774. logNetwork->error("Lost connection to server, ending listening thread! Reason: %s", e.what());
  775. if(client)
  776. {
  777. state = EClientState::DISCONNECTING;
  778. GH.dispatchMainThread([]()
  779. {
  780. CSH->endGameplay();
  781. GH.defActionsDef = 63;
  782. CMM->menu->switchToTab("main");
  783. });
  784. }
  785. else
  786. {
  787. auto lcd = new LobbyClientDisconnected();
  788. lcd->clientId = c->connectionID;
  789. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  790. packsForLobbyScreen.push_back(lcd);
  791. }
  792. }
  793. }
  794. }
  795. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  796. {
  797. if(applier->getApplier(typeList.getTypeID(&lobbyPack))->applyOnLobbyHandler(this, &lobbyPack))
  798. {
  799. if(!settings["session"]["headless"].Bool())
  800. {
  801. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  802. packsForLobbyScreen.push_back(&lobbyPack);
  803. }
  804. }
  805. }
  806. void CServerHandler::visitForClient(CPackForClient & clientPack)
  807. {
  808. client->handlePack(&clientPack);
  809. }
  810. void CServerHandler::threadRunServer()
  811. {
  812. #if !defined(VCMI_MOBILE)
  813. setThreadName("runServer");
  814. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  815. std::string comm = VCMIDirs::get().serverPath().string()
  816. + " --port=" + std::to_string(getHostPort())
  817. + " --run-by-client"
  818. + " --uuid=" + uuid;
  819. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  820. {
  821. comm += " --lobby=" + settings["session"]["address"].String();
  822. comm += " --connections=" + settings["session"]["hostConnections"].String();
  823. comm += " --lobby-port=" + std::to_string(settings["session"]["port"].Integer());
  824. comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
  825. }
  826. comm += " > \"" + logName + '\"';
  827. logGlobal->info("Server command line: %s", comm);
  828. #ifdef VCMI_WINDOWS
  829. int result = -1;
  830. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  831. if(bufSize > 0)
  832. {
  833. std::wstring wComm(bufSize, {});
  834. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  835. if(convertResult > 0)
  836. result = ::_wsystem(wComm.c_str());
  837. else
  838. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  839. }
  840. else
  841. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  842. #else
  843. int result = std::system(comm.c_str());
  844. #endif
  845. if (result == 0)
  846. {
  847. logNetwork->info("Server closed correctly");
  848. }
  849. else
  850. {
  851. logNetwork->error("Error: server failed to close correctly or crashed!");
  852. logNetwork->error("Check %s for more info", logName);
  853. }
  854. onServerFinished();
  855. #endif
  856. }
  857. void CServerHandler::onServerFinished()
  858. {
  859. threadRunLocalServer.reset();
  860. CSH->campaignServerRestartLock.setn(false);
  861. }
  862. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  863. {
  864. if(state != EClientState::STARTING)
  865. c->sendPack(&pack);
  866. }