CServerHandler.cpp 22 KB

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