CServerHandler.cpp 19 KB

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