CServerHandler.cpp 20 KB

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