CServerHandler.cpp 19 KB

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