2
0

CServerHandler.cpp 19 KB

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