CServerHandler.cpp 20 KB

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