CServerHandler.cpp 25 KB

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