CServerHandler.cpp 19 KB

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