CServerHandler.cpp 20 KB

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