2
0

CServerHandler.cpp 18 KB

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