CServerHandler.cpp 20 KB

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