CServerHandler.cpp 23 KB

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