2
0

CServerHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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 "lobby/CSelectionBase.h"
  17. #include "lobby/CLobbyScreen.h"
  18. #include "mainmenu/CMainMenu.h"
  19. #ifndef VCMI_ANDROID
  20. #include "../lib/Interprocess.h"
  21. #else
  22. #include "../lib/CAndroidVMHelper.h"
  23. #endif
  24. #include "../lib/CConfigHandler.h"
  25. #include "../lib/CGeneralTextHandler.h"
  26. #include "../lib/CThreadHelper.h"
  27. #include "../lib/NetPacks.h"
  28. #include "../lib/StartInfo.h"
  29. #include "../lib/VCMIDirs.h"
  30. #include "../lib/mapping/CCampaignHandler.h"
  31. #include "../lib/mapping/CMap.h"
  32. #include "../lib/mapping/CMapInfo.h"
  33. #include "../lib/mapObjects/MiscObjects.h"
  34. #include "../lib/rmg/CMapGenOptions.h"
  35. #include "../lib/registerTypes/RegisterTypes.h"
  36. #include "../lib/serializer/Connection.h"
  37. #include "../lib/serializer/CMemorySerializer.h"
  38. #include <boost/uuid/uuid.hpp>
  39. #include <boost/uuid/uuid_io.hpp>
  40. #include <boost/uuid/uuid_generators.hpp>
  41. #include "../lib/serializer/Cast.h"
  42. template<typename T> class CApplyOnLobby;
  43. #ifdef VCMI_ANDROID
  44. extern std::atomic_bool androidTestServerReadyFlag;
  45. #endif
  46. class CBaseForLobbyApply
  47. {
  48. public:
  49. virtual bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const = 0;
  50. virtual void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const = 0;
  51. virtual ~CBaseForLobbyApply(){};
  52. template<typename U> static CBaseForLobbyApply * getApplier(const U * t = nullptr)
  53. {
  54. return new CApplyOnLobby<U>();
  55. }
  56. };
  57. template<typename T> class CApplyOnLobby : public CBaseForLobbyApply
  58. {
  59. public:
  60. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  61. {
  62. T * ptr = static_cast<T *>(pack);
  63. logNetwork->trace("\tImmidiately apply on lobby: %s", typeList.getTypeInfo(ptr)->name());
  64. return ptr->applyOnLobbyHandler(handler);
  65. }
  66. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  67. {
  68. T * ptr = static_cast<T *>(pack);
  69. logNetwork->trace("\tApply on lobby from queue: %s", typeList.getTypeInfo(ptr)->name());
  70. ptr->applyOnLobbyScreen(lobby, handler);
  71. }
  72. };
  73. template<> class CApplyOnLobby<CPack>: public CBaseForLobbyApply
  74. {
  75. public:
  76. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  77. {
  78. logGlobal->error("Cannot apply plain CPack!");
  79. assert(0);
  80. return false;
  81. }
  82. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  83. {
  84. logGlobal->error("Cannot apply plain CPack!");
  85. assert(0);
  86. }
  87. };
  88. extern std::string NAME;
  89. CServerHandler::CServerHandler()
  90. : state(EClientState::NONE), mx(std::make_shared<boost::recursive_mutex>()), client(nullptr), loadMode(0), campaignStateToSend(nullptr), campaignServerRestartLock(false)
  91. {
  92. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  93. applier = std::make_shared<CApplier<CBaseForLobbyApply>>();
  94. registerTypesLobbyPacks(*applier);
  95. }
  96. void CServerHandler::resetStateForLobby(const StartInfo::EMode mode, const std::vector<std::string> * names)
  97. {
  98. hostClientId = -1;
  99. state = EClientState::NONE;
  100. th = make_unique<CStopWatch>();
  101. packsForLobbyScreen.clear();
  102. c.reset();
  103. si = std::make_shared<StartInfo>();
  104. playerNames.clear();
  105. si->difficulty = 1;
  106. si->mode = mode;
  107. myNames.clear();
  108. if(names && !names->empty()) //if have custom set of player names - use it
  109. myNames = *names;
  110. else
  111. myNames.push_back(settings["general"]["playerName"].String());
  112. #ifndef VCMI_ANDROID
  113. shm.reset();
  114. if(!settings["session"]["disable-shm"].Bool())
  115. {
  116. std::string sharedMemoryName = "vcmi_memory";
  117. if(settings["session"]["enable-shm-uuid"].Bool())
  118. {
  119. //used or automated testing when multiple clients start simultaneously
  120. sharedMemoryName += "_" + uuid;
  121. }
  122. try
  123. {
  124. shm = std::make_shared<SharedMemory>(sharedMemoryName, true);
  125. }
  126. catch(...)
  127. {
  128. shm.reset();
  129. logNetwork->error("Cannot open interprocess memory. Continue without it...");
  130. }
  131. }
  132. #endif
  133. }
  134. void CServerHandler::startLocalServerAndConnect()
  135. {
  136. if(threadRunLocalServer)
  137. threadRunLocalServer->join();
  138. th->update();
  139. #ifdef VCMI_ANDROID
  140. {
  141. CAndroidVMHelper envHelper;
  142. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "startServer", true);
  143. }
  144. #else
  145. threadRunLocalServer = std::make_shared<boost::thread>(&CServerHandler::threadRunServer, this); //runs server executable;
  146. #endif
  147. logNetwork->trace("Setting up thread calling server: %d ms", th->getDiff());
  148. th->update();
  149. #ifndef VCMI_ANDROID
  150. if(shm)
  151. shm->sr->waitTillReady();
  152. #else
  153. logNetwork->info("waiting for server");
  154. while(!androidTestServerReadyFlag.load())
  155. {
  156. logNetwork->info("still waiting...");
  157. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  158. }
  159. logNetwork->info("waiting for server finished...");
  160. androidTestServerReadyFlag = false;
  161. #endif
  162. logNetwork->trace("Waiting for server: %d ms", th->getDiff());
  163. th->update(); //put breakpoint here to attach to server before it does something stupid
  164. #ifndef VCMI_ANDROID
  165. justConnectToServer(settings["server"]["server"].String(), shm ? shm->sr->port : 0);
  166. #else
  167. justConnectToServer(settings["server"]["server"].String());
  168. #endif
  169. logNetwork->trace("\tConnecting to the server: %d ms", th->getDiff());
  170. }
  171. void CServerHandler::justConnectToServer(const std::string & addr, const ui16 port)
  172. {
  173. state = EClientState::CONNECTING;
  174. while(!c && state != EClientState::CONNECTION_CANCELLED)
  175. {
  176. try
  177. {
  178. logNetwork->info("Establishing connection...");
  179. c = std::make_shared<CConnection>(
  180. addr.size() ? addr : settings["server"]["server"].String(),
  181. port ? port : getDefaultPort(),
  182. NAME, uuid);
  183. }
  184. catch(...)
  185. {
  186. logNetwork->error("\nCannot establish connection! Retrying within 1 second");
  187. boost::this_thread::sleep(boost::posix_time::seconds(1));
  188. }
  189. }
  190. if(state == EClientState::CONNECTION_CANCELLED)
  191. logNetwork->info("Connection aborted by player!");
  192. else
  193. c->handler = std::make_shared<boost::thread>(&CServerHandler::threadHandleConnection, this);
  194. }
  195. void CServerHandler::applyPacksOnLobbyScreen()
  196. {
  197. if(!c || !c->handler)
  198. return;
  199. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  200. while(!packsForLobbyScreen.empty())
  201. {
  202. CPackForLobby * pack = packsForLobbyScreen.front();
  203. packsForLobbyScreen.pop_front();
  204. CBaseForLobbyApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  205. apply->applyOnLobbyScreen(static_cast<CLobbyScreen *>(SEL), this, pack);
  206. GH.totalRedraw();
  207. delete pack;
  208. }
  209. }
  210. void CServerHandler::stopServerConnection()
  211. {
  212. if(c->handler)
  213. {
  214. while(!c->handler->timed_join(boost::posix_time::milliseconds(50)))
  215. applyPacksOnLobbyScreen();
  216. c->handler->join();
  217. }
  218. }
  219. std::set<PlayerColor> CServerHandler::getHumanColors()
  220. {
  221. return clientHumanColors(c->connectionID);
  222. }
  223. PlayerColor CServerHandler::myFirstColor() const
  224. {
  225. return clientFirstColor(c->connectionID);
  226. }
  227. bool CServerHandler::isMyColor(PlayerColor color) const
  228. {
  229. return isClientColor(c->connectionID, color);
  230. }
  231. ui8 CServerHandler::myFirstId() const
  232. {
  233. return clientFirstId(c->connectionID);
  234. }
  235. bool CServerHandler::isServerLocal() const
  236. {
  237. if(threadRunLocalServer)
  238. return true;
  239. return false;
  240. }
  241. bool CServerHandler::isHost() const
  242. {
  243. return c && hostClientId == c->connectionID;
  244. }
  245. bool CServerHandler::isGuest() const
  246. {
  247. return !c || hostClientId != c->connectionID;
  248. }
  249. ui16 CServerHandler::getDefaultPort()
  250. {
  251. if(settings["session"]["serverport"].Integer())
  252. return static_cast<ui16>(settings["session"]["serverport"].Integer());
  253. else
  254. return static_cast<ui16>(settings["server"]["port"].Integer());
  255. }
  256. std::string CServerHandler::getDefaultPortStr()
  257. {
  258. return boost::lexical_cast<std::string>(getDefaultPort());
  259. }
  260. void CServerHandler::sendClientConnecting() const
  261. {
  262. LobbyClientConnected lcc;
  263. lcc.uuid = uuid;
  264. lcc.names = myNames;
  265. lcc.mode = si->mode;
  266. sendLobbyPack(lcc);
  267. }
  268. void CServerHandler::sendClientDisconnecting()
  269. {
  270. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  271. if(state == EClientState::DISCONNECTING)
  272. return;
  273. state = EClientState::DISCONNECTING;
  274. LobbyClientDisconnected lcd;
  275. lcd.clientId = c->connectionID;
  276. logNetwork->info("Connection has been requested to be closed.");
  277. if(isServerLocal())
  278. {
  279. lcd.shutdownServer = true;
  280. logNetwork->info("Sent closing signal to the server");
  281. }
  282. else
  283. {
  284. logNetwork->info("Sent leaving signal to the server");
  285. }
  286. sendLobbyPack(lcd);
  287. }
  288. void CServerHandler::setCampaignState(std::shared_ptr<CCampaignState> newCampaign)
  289. {
  290. state = EClientState::LOBBY_CAMPAIGN;
  291. LobbySetCampaign lsc;
  292. lsc.ourCampaign = newCampaign;
  293. sendLobbyPack(lsc);
  294. }
  295. void CServerHandler::setCampaignMap(int mapId) const
  296. {
  297. if(state == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  298. return;
  299. LobbySetCampaignMap lscm;
  300. lscm.mapId = mapId;
  301. sendLobbyPack(lscm);
  302. }
  303. void CServerHandler::setCampaignBonus(int bonusId) const
  304. {
  305. if(state == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  306. return;
  307. LobbySetCampaignBonus lscb;
  308. lscb.bonusId = bonusId;
  309. sendLobbyPack(lscb);
  310. }
  311. void CServerHandler::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  312. {
  313. LobbySetMap lsm;
  314. lsm.mapInfo = to;
  315. lsm.mapGenOpts = mapGenOpts;
  316. sendLobbyPack(lsm);
  317. }
  318. void CServerHandler::setPlayer(PlayerColor color) const
  319. {
  320. LobbySetPlayer lsp;
  321. lsp.clickedColor = color;
  322. sendLobbyPack(lsp);
  323. }
  324. void CServerHandler::setPlayerOption(ui8 what, ui8 dir, PlayerColor player) const
  325. {
  326. LobbyChangePlayerOption lcpo;
  327. lcpo.what = what;
  328. lcpo.direction = dir;
  329. lcpo.color = player;
  330. sendLobbyPack(lcpo);
  331. }
  332. void CServerHandler::setDifficulty(int to) const
  333. {
  334. LobbySetDifficulty lsd;
  335. lsd.difficulty = to;
  336. sendLobbyPack(lsd);
  337. }
  338. void CServerHandler::setTurnLength(int npos) const
  339. {
  340. vstd::amin(npos, GameConstants::POSSIBLE_TURNTIME.size() - 1);
  341. LobbySetTurnTime lstt;
  342. lstt.turnTime = GameConstants::POSSIBLE_TURNTIME[npos];
  343. sendLobbyPack(lstt);
  344. }
  345. void CServerHandler::sendMessage(const std::string & txt) const
  346. {
  347. std::istringstream readed;
  348. readed.str(txt);
  349. std::string command;
  350. readed >> command;
  351. if(command == "!passhost")
  352. {
  353. std::string id;
  354. readed >> id;
  355. if(id.length())
  356. {
  357. LobbyChangeHost lch;
  358. lch.newHostConnectionId = boost::lexical_cast<int>(id);
  359. sendLobbyPack(lch);
  360. }
  361. }
  362. else if(command == "!forcep")
  363. {
  364. std::string connectedId, playerColorId;
  365. readed >> connectedId;
  366. readed >> playerColorId;
  367. if(connectedId.length(), playerColorId.length()) // BUG https://bugs.vcmi.eu/view.php?id=3144
  368. {
  369. ui8 connected = boost::lexical_cast<int>(connectedId);
  370. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  371. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  372. {
  373. LobbyForceSetPlayer lfsp;
  374. lfsp.targetConnectedPlayer = connected;
  375. lfsp.targetPlayerColor = color;
  376. sendLobbyPack(lfsp);
  377. }
  378. }
  379. }
  380. else
  381. {
  382. LobbyChatMessage lcm;
  383. lcm.message = txt;
  384. lcm.playerName = playerNames.find(myFirstId())->second.name;
  385. sendLobbyPack(lcm);
  386. }
  387. }
  388. void CServerHandler::sendGuiAction(ui8 action) const
  389. {
  390. LobbyGuiAction lga;
  391. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  392. sendLobbyPack(lga);
  393. }
  394. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  395. {
  396. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  397. LobbyStartGame lsg;
  398. if(client)
  399. {
  400. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  401. lsg.initializedStartInfo->mode = StartInfo::NEW_GAME;
  402. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  403. * si = * lsg.initializedStartInfo;
  404. }
  405. sendLobbyPack(lsg);
  406. }
  407. void CServerHandler::startGameplay()
  408. {
  409. if(CMM)
  410. CMM->disable();
  411. client = new CClient();
  412. switch(si->mode)
  413. {
  414. case StartInfo::NEW_GAME:
  415. client->newGame();
  416. break;
  417. case StartInfo::CAMPAIGN:
  418. client->newGame();
  419. break;
  420. case StartInfo::LOAD_GAME:
  421. client->loadGame();
  422. break;
  423. default:
  424. throw std::runtime_error("Invalid mode");
  425. }
  426. // After everything initialized we can accept CPackToClient netpacks
  427. c->enterGameplayConnectionMode(client->gameState());
  428. state = EClientState::GAMEPLAY;
  429. }
  430. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  431. {
  432. client->endGame();
  433. vstd::clear_pointer(client);
  434. if(closeConnection)
  435. {
  436. // Game is ending
  437. // Tell the network thread to reach a stable state
  438. CSH->sendClientDisconnecting();
  439. logNetwork->info("Closed connection.");
  440. }
  441. if(!restart)
  442. {
  443. if(CMM)
  444. {
  445. GH.terminate_cond->setn(false);
  446. GH.curInt = CMM.get();
  447. CMM->enable();
  448. }
  449. else
  450. {
  451. GH.curInt = CMainMenu::create().get();
  452. }
  453. }
  454. }
  455. void CServerHandler::startCampaignScenario(std::shared_ptr<CCampaignState> cs)
  456. {
  457. SDL_Event event;
  458. event.type = SDL_USEREVENT;
  459. event.user.code = EUserEvent::CAMPAIGN_START_SCENARIO;
  460. if(cs)
  461. event.user.data1 = CMemorySerializer::deepCopy(*cs.get()).release();
  462. else
  463. event.user.data1 = CMemorySerializer::deepCopy(*si->campState.get()).release();
  464. SDL_PushEvent(&event);
  465. }
  466. int CServerHandler::howManyPlayerInterfaces()
  467. {
  468. int playerInts = 0;
  469. for(auto pint : client->playerint)
  470. {
  471. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  472. playerInts++;
  473. }
  474. return playerInts;
  475. }
  476. ui8 CServerHandler::getLoadMode()
  477. {
  478. if(state == EClientState::GAMEPLAY)
  479. {
  480. if(si->campState)
  481. return ELoadMode::CAMPAIGN;
  482. for(auto pn : playerNames)
  483. {
  484. if(pn.second.connection != c->connectionID)
  485. return ELoadMode::MULTI;
  486. }
  487. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  488. return ELoadMode::MULTI;
  489. return ELoadMode::SINGLE;
  490. }
  491. return loadMode;
  492. }
  493. void CServerHandler::debugStartTest(std::string filename, bool save)
  494. {
  495. logGlobal->info("Starting debug test with file: %s", filename);
  496. auto mapInfo = std::make_shared<CMapInfo>();
  497. if(save)
  498. {
  499. resetStateForLobby(StartInfo::LOAD_GAME);
  500. mapInfo->saveInit(ResourceID(filename, EResType::CLIENT_SAVEGAME));
  501. screenType = ESelectionScreen::loadGame;
  502. }
  503. else
  504. {
  505. resetStateForLobby(StartInfo::NEW_GAME);
  506. mapInfo->mapInit(filename);
  507. screenType = ESelectionScreen::newGame;
  508. }
  509. if(settings["session"]["donotstartserver"].Bool())
  510. justConnectToServer("127.0.0.1", 3030);
  511. else
  512. startLocalServerAndConnect();
  513. while(!settings["session"]["headless"].Bool() && !dynamic_cast<CLobbyScreen *>(GH.topInt().get()))
  514. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  515. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  516. {
  517. setMapInfo(mapInfo);
  518. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  519. }
  520. // "Click" on color to remove us from it
  521. setPlayer(myFirstColor());
  522. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  523. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  524. while(true)
  525. {
  526. try
  527. {
  528. sendStartGame();
  529. break;
  530. }
  531. catch(...)
  532. {
  533. }
  534. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  535. }
  536. }
  537. void CServerHandler::threadHandleConnection()
  538. {
  539. setThreadName("CServerHandler::threadHandleConnection");
  540. c->enterLobbyConnectionMode();
  541. try
  542. {
  543. sendClientConnecting();
  544. while(c->connected)
  545. {
  546. while(state == EClientState::STARTING)
  547. boost::this_thread::sleep(boost::posix_time::milliseconds(10));
  548. CPack * pack = c->retrievePack();
  549. if(state == EClientState::DISCONNECTING)
  550. {
  551. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  552. // Though currently they'll be delivered and might cause crash.
  553. vstd::clear_pointer(pack);
  554. }
  555. else if(auto lobbyPack = dynamic_ptr_cast<CPackForLobby>(pack))
  556. {
  557. if(applier->getApplier(typeList.getTypeID(pack))->applyOnLobbyHandler(this, pack))
  558. {
  559. if(!settings["session"]["headless"].Bool())
  560. {
  561. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  562. packsForLobbyScreen.push_back(lobbyPack);
  563. }
  564. }
  565. }
  566. else if(auto clientPack = dynamic_ptr_cast<CPackForClient>(pack))
  567. {
  568. client->handlePack(clientPack);
  569. }
  570. }
  571. }
  572. //catch only asio exceptions
  573. catch(const boost::system::system_error & e)
  574. {
  575. if(state == EClientState::DISCONNECTING)
  576. {
  577. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  578. }
  579. else
  580. {
  581. logNetwork->error("Lost connection to server, ending listening thread!");
  582. logNetwork->error(e.what());
  583. if(client)
  584. {
  585. state = EClientState::DISCONNECTING;
  586. CGuiHandler::pushSDLEvent(SDL_USEREVENT, EUserEvent::RETURN_TO_MAIN_MENU);
  587. }
  588. else
  589. {
  590. auto lcd = new LobbyClientDisconnected();
  591. lcd->clientId = c->connectionID;
  592. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  593. packsForLobbyScreen.push_back(lcd);
  594. }
  595. }
  596. }
  597. catch(...)
  598. {
  599. handleException();
  600. throw;
  601. }
  602. }
  603. void CServerHandler::threadRunServer()
  604. {
  605. #ifndef VCMI_ANDROID
  606. setThreadName("CServerHandler::threadRunServer");
  607. const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
  608. std::string comm = VCMIDirs::get().serverPath().string()
  609. + " --port=" + getDefaultPortStr()
  610. + " --run-by-client"
  611. + " --uuid=" + uuid;
  612. if(shm)
  613. {
  614. comm += " --enable-shm";
  615. if(settings["session"]["enable-shm-uuid"].Bool())
  616. comm += " --enable-shm-uuid";
  617. }
  618. comm += " > \"" + logName + '\"';
  619. int result = std::system(comm.c_str());
  620. if (result == 0)
  621. {
  622. logNetwork->info("Server closed correctly");
  623. }
  624. else
  625. {
  626. logNetwork->error("Error: server failed to close correctly or crashed!");
  627. logNetwork->error("Check %s for more info", logName);
  628. }
  629. threadRunLocalServer.reset();
  630. CSH->campaignServerRestartLock.setn(false);
  631. #endif
  632. }
  633. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  634. {
  635. if(state != EClientState::STARTING)
  636. c->sendPack(&pack);
  637. }