2
0

CServerHandler.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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 "gui/WindowHandler.h"
  17. #include "lobby/CSelectionBase.h"
  18. #include "lobby/CLobbyScreen.h"
  19. #include "windows/InfoWindows.h"
  20. #include "mainmenu/CMainMenu.h"
  21. #include "mainmenu/CPrologEpilogVideo.h"
  22. #include "mainmenu/CHighScoreScreen.h"
  23. #ifdef VCMI_ANDROID
  24. #include "../lib/CAndroidVMHelper.h"
  25. #elif defined(VCMI_IOS)
  26. #include "ios/utils.h"
  27. #include <dispatch/dispatch.h>
  28. #endif
  29. #ifdef SINGLE_PROCESS_APP
  30. #include "../server/CVCMIServer.h"
  31. #endif
  32. #include "../lib/CConfigHandler.h"
  33. #include "../lib/CGeneralTextHandler.h"
  34. #include "../lib/CThreadHelper.h"
  35. #include "../lib/NetPackVisitor.h"
  36. #include "../lib/StartInfo.h"
  37. #include "../lib/TurnTimerInfo.h"
  38. #include "../lib/VCMIDirs.h"
  39. #include "../lib/campaign/CampaignState.h"
  40. #include "../lib/mapping/CMapInfo.h"
  41. #include "../lib/mapObjects/MiscObjects.h"
  42. #include "../lib/modding/ModIncompatibility.h"
  43. #include "../lib/rmg/CMapGenOptions.h"
  44. #include "../lib/filesystem/Filesystem.h"
  45. #include "../lib/registerTypes/RegisterTypes.h"
  46. #include "../lib/serializer/Connection.h"
  47. #include "../lib/serializer/CMemorySerializer.h"
  48. #include <boost/uuid/uuid.hpp>
  49. #include <boost/uuid/uuid_io.hpp>
  50. #include <boost/uuid/uuid_generators.hpp>
  51. #include <boost/asio.hpp>
  52. #include "../lib/serializer/Cast.h"
  53. #include "LobbyClientNetPackVisitors.h"
  54. #include <vcmi/events/EventBus.h>
  55. #ifdef VCMI_WINDOWS
  56. #include <windows.h>
  57. #endif
  58. template<typename T> class CApplyOnLobby;
  59. const std::string CServerHandler::localhostAddress{"127.0.0.1"};
  60. #if defined(VCMI_ANDROID) && !defined(SINGLE_PROCESS_APP)
  61. extern std::atomic_bool androidTestServerReadyFlag;
  62. #endif
  63. class CBaseForLobbyApply
  64. {
  65. public:
  66. virtual bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const = 0;
  67. virtual void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const = 0;
  68. virtual ~CBaseForLobbyApply(){};
  69. template<typename U> static CBaseForLobbyApply * getApplier(const U * t = nullptr)
  70. {
  71. return new CApplyOnLobby<U>();
  72. }
  73. };
  74. template<typename T> class CApplyOnLobby : public CBaseForLobbyApply
  75. {
  76. public:
  77. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  78. {
  79. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  80. T * ptr = static_cast<T *>(pack);
  81. ApplyOnLobbyHandlerNetPackVisitor visitor(*handler);
  82. logNetwork->trace("\tImmediately apply on lobby: %s", typeList.getTypeInfo(ptr)->name());
  83. ptr->visit(visitor);
  84. return visitor.getResult();
  85. }
  86. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  87. {
  88. T * ptr = static_cast<T *>(pack);
  89. ApplyOnLobbyScreenNetPackVisitor visitor(*handler, lobby);
  90. logNetwork->trace("\tApply on lobby from queue: %s", typeList.getTypeInfo(ptr)->name());
  91. ptr->visit(visitor);
  92. }
  93. };
  94. template<> class CApplyOnLobby<CPack>: public CBaseForLobbyApply
  95. {
  96. public:
  97. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  98. {
  99. logGlobal->error("Cannot apply plain CPack!");
  100. assert(0);
  101. return false;
  102. }
  103. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  104. {
  105. logGlobal->error("Cannot apply plain CPack!");
  106. assert(0);
  107. }
  108. };
  109. static const std::string NAME_AFFIX = "client";
  110. static const std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  111. CServerHandler::CServerHandler()
  112. : state(EClientState::NONE), mx(std::make_shared<boost::recursive_mutex>()), client(nullptr), loadMode(0), campaignStateToSend(nullptr), campaignServerRestartLock(false)
  113. {
  114. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  115. //read from file to restore last session
  116. if(!settings["server"]["uuid"].isNull() && !settings["server"]["uuid"].String().empty())
  117. uuid = settings["server"]["uuid"].String();
  118. applier = std::make_shared<CApplier<CBaseForLobbyApply>>();
  119. registerTypesLobbyPacks(*applier);
  120. }
  121. void CServerHandler::resetStateForLobby(const StartInfo::EMode mode, const std::vector<std::string> * names)
  122. {
  123. hostClientId = -1;
  124. state = EClientState::NONE;
  125. mapToStart = nullptr;
  126. th = std::make_unique<CStopWatch>();
  127. packsForLobbyScreen.clear();
  128. c.reset();
  129. si = std::make_shared<StartInfo>();
  130. playerNames.clear();
  131. si->difficulty = 1;
  132. si->mode = mode;
  133. myNames.clear();
  134. if(names && !names->empty()) //if have custom set of player names - use it
  135. myNames = *names;
  136. else
  137. myNames.push_back(settings["general"]["playerName"].String());
  138. }
  139. void CServerHandler::startLocalServerAndConnect()
  140. {
  141. if(threadRunLocalServer)
  142. threadRunLocalServer->join();
  143. th->update();
  144. auto errorMsg = CGI->generaltexth->translate("vcmi.server.errors.existingProcess");
  145. try
  146. {
  147. CConnection testConnection(localhostAddress, getDefaultPort(), NAME, uuid);
  148. logNetwork->error("Port is busy, check if another instance of vcmiserver is working");
  149. CInfoWindow::showInfoDialog(errorMsg, {});
  150. return;
  151. }
  152. catch(std::runtime_error & error)
  153. {
  154. //no connection means that port is not busy and we can start local server
  155. }
  156. #if defined(SINGLE_PROCESS_APP)
  157. boost::condition_variable cond;
  158. std::vector<std::string> args{"--uuid=" + uuid, "--port=" + std::to_string(getHostPort())};
  159. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  160. {
  161. args.push_back("--lobby=" + settings["session"]["address"].String());
  162. args.push_back("--connections=" + settings["session"]["hostConnections"].String());
  163. args.push_back("--lobby-port=" + std::to_string(settings["session"]["port"].Integer()));
  164. args.push_back("--lobby-uuid=" + settings["session"]["hostUuid"].String());
  165. }
  166. threadRunLocalServer = std::make_shared<boost::thread>([&cond, args, this] {
  167. setThreadName("CVCMIServer");
  168. CVCMIServer::create(&cond, args);
  169. onServerFinished();
  170. });
  171. threadRunLocalServer->detach();
  172. #elif defined(VCMI_ANDROID)
  173. {
  174. CAndroidVMHelper envHelper;
  175. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "startServer", true);
  176. }
  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 SINGLE_PROCESS_APP
  183. {
  184. #ifdef VCMI_IOS
  185. dispatch_sync(dispatch_get_main_queue(), ^{
  186. iOS_utils::showLoadingIndicator();
  187. });
  188. #endif
  189. boost::mutex m;
  190. boost::unique_lock<boost::mutex> lock{m};
  191. logNetwork->info("waiting for server");
  192. cond.wait(lock);
  193. logNetwork->info("server is ready");
  194. #ifdef VCMI_IOS
  195. dispatch_sync(dispatch_get_main_queue(), ^{
  196. iOS_utils::hideLoadingIndicator();
  197. });
  198. #endif
  199. }
  200. #elif defined(VCMI_ANDROID)
  201. logNetwork->info("waiting for server");
  202. while(!androidTestServerReadyFlag.load())
  203. {
  204. logNetwork->info("still waiting...");
  205. boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
  206. }
  207. logNetwork->info("waiting for server finished...");
  208. androidTestServerReadyFlag = false;
  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. justConnectToServer(localhostAddress, 0);
  213. logNetwork->trace("\tConnecting to the server: %d ms", th->getDiff());
  214. }
  215. void CServerHandler::justConnectToServer(const std::string & addr, const ui16 port)
  216. {
  217. state = EClientState::CONNECTING;
  218. while(!c && state != EClientState::CONNECTION_CANCELLED)
  219. {
  220. try
  221. {
  222. logNetwork->info("Establishing connection...");
  223. c = std::make_shared<CConnection>(
  224. addr.size() ? addr : getHostAddress(),
  225. port ? port : getHostPort(),
  226. NAME, uuid);
  227. }
  228. catch(std::runtime_error & error)
  229. {
  230. logNetwork->warn("\nCannot establish connection. %s Retrying in 1 second", error.what());
  231. boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
  232. }
  233. }
  234. if(state == EClientState::CONNECTION_CANCELLED)
  235. {
  236. logNetwork->info("Connection aborted by player!");
  237. return;
  238. }
  239. c->handler = std::make_shared<boost::thread>(&CServerHandler::threadHandleConnection, this);
  240. if(!addr.empty() && addr != getHostAddress())
  241. {
  242. Settings serverAddress = settings.write["server"]["server"];
  243. serverAddress->String() = addr;
  244. }
  245. if(port && port != getHostPort())
  246. {
  247. Settings serverPort = settings.write["server"]["port"];
  248. serverPort->Integer() = port;
  249. }
  250. }
  251. void CServerHandler::applyPacksOnLobbyScreen()
  252. {
  253. if(!c || !c->handler)
  254. return;
  255. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  256. while(!packsForLobbyScreen.empty())
  257. {
  258. boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
  259. CPackForLobby * pack = packsForLobbyScreen.front();
  260. packsForLobbyScreen.pop_front();
  261. CBaseForLobbyApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  262. apply->applyOnLobbyScreen(static_cast<CLobbyScreen *>(SEL), this, pack);
  263. GH.windows().totalRedraw();
  264. delete pack;
  265. }
  266. }
  267. void CServerHandler::stopServerConnection()
  268. {
  269. if(c->handler)
  270. {
  271. while(!c->handler->timed_join(boost::chrono::milliseconds(50)))
  272. applyPacksOnLobbyScreen();
  273. c->handler->join();
  274. }
  275. }
  276. std::set<PlayerColor> CServerHandler::getHumanColors()
  277. {
  278. return clientHumanColors(c->connectionID);
  279. }
  280. PlayerColor CServerHandler::myFirstColor() const
  281. {
  282. return clientFirstColor(c->connectionID);
  283. }
  284. bool CServerHandler::isMyColor(PlayerColor color) const
  285. {
  286. return isClientColor(c->connectionID, color);
  287. }
  288. ui8 CServerHandler::myFirstId() const
  289. {
  290. return clientFirstId(c->connectionID);
  291. }
  292. bool CServerHandler::isServerLocal() const
  293. {
  294. if(threadRunLocalServer)
  295. return true;
  296. return false;
  297. }
  298. bool CServerHandler::isHost() const
  299. {
  300. return c && hostClientId == c->connectionID;
  301. }
  302. bool CServerHandler::isGuest() const
  303. {
  304. return !c || hostClientId != c->connectionID;
  305. }
  306. ui16 CServerHandler::getDefaultPort()
  307. {
  308. return static_cast<ui16>(settings["server"]["port"].Integer());
  309. }
  310. std::string CServerHandler::getDefaultPortStr()
  311. {
  312. return std::to_string(getDefaultPort());
  313. }
  314. std::string CServerHandler::getHostAddress() const
  315. {
  316. if(settings["session"]["lobby"].isNull() || !settings["session"]["lobby"].Bool())
  317. return settings["server"]["server"].String();
  318. if(settings["session"]["host"].Bool())
  319. return localhostAddress;
  320. return settings["session"]["address"].String();
  321. }
  322. ui16 CServerHandler::getHostPort() const
  323. {
  324. if(settings["session"]["lobby"].isNull() || !settings["session"]["lobby"].Bool())
  325. return getDefaultPort();
  326. if(settings["session"]["host"].Bool())
  327. return getDefaultPort();
  328. return settings["session"]["port"].Integer();
  329. }
  330. void CServerHandler::sendClientConnecting() const
  331. {
  332. LobbyClientConnected lcc;
  333. lcc.uuid = uuid;
  334. lcc.names = myNames;
  335. lcc.mode = si->mode;
  336. sendLobbyPack(lcc);
  337. }
  338. void CServerHandler::sendClientDisconnecting()
  339. {
  340. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  341. if(state == EClientState::DISCONNECTING)
  342. return;
  343. state = EClientState::DISCONNECTING;
  344. mapToStart = nullptr;
  345. LobbyClientDisconnected lcd;
  346. lcd.clientId = c->connectionID;
  347. logNetwork->info("Connection has been requested to be closed.");
  348. if(isServerLocal())
  349. {
  350. lcd.shutdownServer = true;
  351. logNetwork->info("Sent closing signal to the server");
  352. }
  353. else
  354. {
  355. logNetwork->info("Sent leaving signal to the server");
  356. }
  357. sendLobbyPack(lcd);
  358. }
  359. void CServerHandler::setCampaignState(std::shared_ptr<CampaignState> newCampaign)
  360. {
  361. state = EClientState::LOBBY_CAMPAIGN;
  362. LobbySetCampaign lsc;
  363. lsc.ourCampaign = newCampaign;
  364. sendLobbyPack(lsc);
  365. }
  366. void CServerHandler::setCampaignMap(CampaignScenarioID mapId) const
  367. {
  368. if(state == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  369. return;
  370. LobbySetCampaignMap lscm;
  371. lscm.mapId = mapId;
  372. sendLobbyPack(lscm);
  373. }
  374. void CServerHandler::setCampaignBonus(int bonusId) const
  375. {
  376. if(state == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  377. return;
  378. LobbySetCampaignBonus lscb;
  379. lscb.bonusId = bonusId;
  380. sendLobbyPack(lscb);
  381. }
  382. void CServerHandler::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  383. {
  384. LobbySetMap lsm;
  385. lsm.mapInfo = to;
  386. lsm.mapGenOpts = mapGenOpts;
  387. sendLobbyPack(lsm);
  388. }
  389. void CServerHandler::setPlayer(PlayerColor color) const
  390. {
  391. LobbySetPlayer lsp;
  392. lsp.clickedColor = color;
  393. sendLobbyPack(lsp);
  394. }
  395. void CServerHandler::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  396. {
  397. LobbyChangePlayerOption lcpo;
  398. lcpo.what = what;
  399. lcpo.value = value;
  400. lcpo.color = player;
  401. sendLobbyPack(lcpo);
  402. }
  403. void CServerHandler::setDifficulty(int to) const
  404. {
  405. LobbySetDifficulty lsd;
  406. lsd.difficulty = to;
  407. sendLobbyPack(lsd);
  408. }
  409. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  410. {
  411. LobbySetSimturns pack;
  412. pack.simturnsInfo = info;
  413. sendLobbyPack(pack);
  414. }
  415. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  416. {
  417. LobbySetTurnTime lstt;
  418. lstt.turnTimerInfo = info;
  419. sendLobbyPack(lstt);
  420. }
  421. void CServerHandler::sendMessage(const std::string & txt) const
  422. {
  423. std::istringstream readed;
  424. readed.str(txt);
  425. std::string command;
  426. readed >> command;
  427. if(command == "!passhost")
  428. {
  429. std::string id;
  430. readed >> id;
  431. if(id.length())
  432. {
  433. LobbyChangeHost lch;
  434. lch.newHostConnectionId = boost::lexical_cast<int>(id);
  435. sendLobbyPack(lch);
  436. }
  437. }
  438. else if(command == "!forcep")
  439. {
  440. std::string connectedId, playerColorId;
  441. readed >> connectedId;
  442. readed >> playerColorId;
  443. if(connectedId.length() && playerColorId.length())
  444. {
  445. ui8 connected = boost::lexical_cast<int>(connectedId);
  446. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  447. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  448. {
  449. LobbyForceSetPlayer lfsp;
  450. lfsp.targetConnectedPlayer = connected;
  451. lfsp.targetPlayerColor = color;
  452. sendLobbyPack(lfsp);
  453. }
  454. }
  455. }
  456. else
  457. {
  458. LobbyChatMessage lcm;
  459. lcm.message = txt;
  460. lcm.playerName = playerNames.find(myFirstId())->second.name;
  461. sendLobbyPack(lcm);
  462. }
  463. }
  464. void CServerHandler::sendGuiAction(ui8 action) const
  465. {
  466. LobbyGuiAction lga;
  467. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  468. sendLobbyPack(lga);
  469. }
  470. void CServerHandler::sendRestartGame() const
  471. {
  472. GH.windows().createAndPushWindow<CLoadingScreen>();
  473. LobbyEndGame endGame;
  474. endGame.closeConnection = false;
  475. endGame.restart = true;
  476. sendLobbyPack(endGame);
  477. }
  478. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  479. {
  480. try
  481. {
  482. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  483. }
  484. catch(ModIncompatibility & e)
  485. {
  486. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  487. std::string errorMsg;
  488. if(!e.whatMissing().empty())
  489. {
  490. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  491. errorMsg += e.whatMissing();
  492. }
  493. if(!e.whatExcessive().empty())
  494. {
  495. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  496. errorMsg += e.whatExcessive();
  497. }
  498. showServerError(errorMsg);
  499. return false;
  500. }
  501. catch(std::exception & e)
  502. {
  503. logGlobal->error("Exception during startScenario: %s", e.what());
  504. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  505. return false;
  506. }
  507. return true;
  508. }
  509. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  510. {
  511. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  512. GH.windows().createAndPushWindow<CLoadingScreen>();
  513. LobbyStartGame lsg;
  514. if(client)
  515. {
  516. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  517. lsg.initializedStartInfo->mode = StartInfo::NEW_GAME;
  518. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  519. * si = * lsg.initializedStartInfo;
  520. }
  521. sendLobbyPack(lsg);
  522. c->enterLobbyConnectionMode();
  523. c->disableStackSendingByID();
  524. }
  525. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  526. {
  527. mapToStart = to;
  528. }
  529. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  530. {
  531. setThreadName("startGameplay");
  532. if(CMM)
  533. CMM->disable();
  534. client = new CClient();
  535. highScoreCalc = nullptr;
  536. switch(si->mode)
  537. {
  538. case StartInfo::NEW_GAME:
  539. client->newGame(gameState);
  540. break;
  541. case StartInfo::CAMPAIGN:
  542. client->newGame(gameState);
  543. break;
  544. case StartInfo::LOAD_GAME:
  545. client->loadGame(gameState);
  546. break;
  547. default:
  548. throw std::runtime_error("Invalid mode");
  549. }
  550. // After everything initialized we can accept CPackToClient netpacks
  551. c->enterGameplayConnectionMode(client->gameState());
  552. state = EClientState::GAMEPLAY;
  553. //store settings to continue game
  554. if(!isServerLocal() && isGuest())
  555. {
  556. Settings saveSession = settings.write["server"]["reconnect"];
  557. saveSession->Bool() = true;
  558. Settings saveUuid = settings.write["server"]["uuid"];
  559. saveUuid->String() = uuid;
  560. Settings saveNames = settings.write["server"]["names"];
  561. saveNames->Vector().clear();
  562. for(auto & name : myNames)
  563. {
  564. JsonNode jsonName;
  565. jsonName.String() = name;
  566. saveNames->Vector().push_back(jsonName);
  567. }
  568. }
  569. }
  570. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  571. {
  572. client->endGame();
  573. vstd::clear_pointer(client);
  574. if(closeConnection)
  575. {
  576. // Game is ending
  577. // Tell the network thread to reach a stable state
  578. CSH->sendClientDisconnecting();
  579. logNetwork->info("Closed connection.");
  580. }
  581. if(!restart)
  582. {
  583. if(CMM)
  584. {
  585. GH.curInt = CMM.get();
  586. CMM->enable();
  587. }
  588. else
  589. {
  590. GH.curInt = CMainMenu::create().get();
  591. }
  592. }
  593. c->enterLobbyConnectionMode();
  594. c->disableStackSendingByID();
  595. //reset settings
  596. Settings saveSession = settings.write["server"]["reconnect"];
  597. saveSession->Bool() = false;
  598. }
  599. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs)
  600. {
  601. std::shared_ptr<CampaignState> ourCampaign = cs;
  602. if (!cs)
  603. ourCampaign = si->campState;
  604. if(highScoreCalc == nullptr)
  605. {
  606. highScoreCalc = std::make_shared<HighScoreCalculation>();
  607. highScoreCalc->isCampaign = true;
  608. highScoreCalc->parameters.clear();
  609. }
  610. param.campaignName = cs->getName();
  611. highScoreCalc->parameters.push_back(param);
  612. GH.dispatchMainThread([ourCampaign, this]()
  613. {
  614. CSH->campaignServerRestartLock.set(true);
  615. CSH->endGameplay();
  616. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  617. auto finisher = [=]()
  618. {
  619. if(ourCampaign->campaignSet != "")
  620. {
  621. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  622. entry->Bool() = true;
  623. }
  624. GH.windows().pushWindow(CMM);
  625. GH.windows().pushWindow(CMM->menu);
  626. if(!ourCampaign->isCampaignFinished())
  627. CMM->openCampaignLobby(ourCampaign);
  628. else
  629. {
  630. CMM->openCampaignScreen(ourCampaign->campaignSet);
  631. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *highScoreCalc);
  632. }
  633. };
  634. if(epilogue.hasPrologEpilog)
  635. {
  636. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  637. }
  638. else
  639. {
  640. CSH->campaignServerRestartLock.waitUntil(false);
  641. finisher();
  642. }
  643. });
  644. }
  645. void CServerHandler::showServerError(const std::string & txt) const
  646. {
  647. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  648. GH.windows().popWindow(w);
  649. CInfoWindow::showInfoDialog(txt, {});
  650. }
  651. int CServerHandler::howManyPlayerInterfaces()
  652. {
  653. int playerInts = 0;
  654. for(auto pint : client->playerint)
  655. {
  656. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  657. playerInts++;
  658. }
  659. return playerInts;
  660. }
  661. ui8 CServerHandler::getLoadMode()
  662. {
  663. if(loadMode != ELoadMode::TUTORIAL && state == EClientState::GAMEPLAY)
  664. {
  665. if(si->campState)
  666. return ELoadMode::CAMPAIGN;
  667. for(auto pn : playerNames)
  668. {
  669. if(pn.second.connection != c->connectionID)
  670. return ELoadMode::MULTI;
  671. }
  672. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  673. return ELoadMode::MULTI;
  674. return ELoadMode::SINGLE;
  675. }
  676. return loadMode;
  677. }
  678. void CServerHandler::restoreLastSession()
  679. {
  680. auto loadSession = [this]()
  681. {
  682. uuid = settings["server"]["uuid"].String();
  683. for(auto & name : settings["server"]["names"].Vector())
  684. myNames.push_back(name.String());
  685. resetStateForLobby(StartInfo::LOAD_GAME, &myNames);
  686. screenType = ESelectionScreen::loadGame;
  687. justConnectToServer(settings["server"]["server"].String(), settings["server"]["port"].Integer());
  688. };
  689. auto cleanUpSession = []()
  690. {
  691. //reset settings
  692. Settings saveSession = settings.write["server"]["reconnect"];
  693. saveSession->Bool() = false;
  694. };
  695. CInfoWindow::showYesNoDialog(VLC->generaltexth->translate("vcmi.server.confirmReconnect"), {}, loadSession, cleanUpSession);
  696. }
  697. void CServerHandler::debugStartTest(std::string filename, bool save)
  698. {
  699. logGlobal->info("Starting debug test with file: %s", filename);
  700. auto mapInfo = std::make_shared<CMapInfo>();
  701. if(save)
  702. {
  703. resetStateForLobby(StartInfo::LOAD_GAME);
  704. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  705. screenType = ESelectionScreen::loadGame;
  706. }
  707. else
  708. {
  709. resetStateForLobby(StartInfo::NEW_GAME);
  710. mapInfo->mapInit(filename);
  711. screenType = ESelectionScreen::newGame;
  712. }
  713. if(settings["session"]["donotstartserver"].Bool())
  714. justConnectToServer(localhostAddress, 3030);
  715. else
  716. startLocalServerAndConnect();
  717. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  718. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  719. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  720. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  721. {
  722. setMapInfo(mapInfo);
  723. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  724. }
  725. // "Click" on color to remove us from it
  726. setPlayer(myFirstColor());
  727. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  728. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  729. while(true)
  730. {
  731. try
  732. {
  733. sendStartGame();
  734. break;
  735. }
  736. catch(...)
  737. {
  738. }
  739. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  740. }
  741. }
  742. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  743. {
  744. private:
  745. CServerHandler & handler;
  746. public:
  747. ServerHandlerCPackVisitor(CServerHandler & handler)
  748. :handler(handler)
  749. {
  750. }
  751. virtual bool callTyped() override { return false; }
  752. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  753. {
  754. handler.visitForLobby(lobbyPack);
  755. }
  756. virtual void visitForClient(CPackForClient & clientPack) override
  757. {
  758. handler.visitForClient(clientPack);
  759. }
  760. };
  761. void CServerHandler::threadHandleConnection()
  762. {
  763. setThreadName("handleConnection");
  764. c->enterLobbyConnectionMode();
  765. try
  766. {
  767. sendClientConnecting();
  768. while(c->connected)
  769. {
  770. while(state == EClientState::STARTING)
  771. boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
  772. CPack * pack = c->retrievePack();
  773. if(state == EClientState::DISCONNECTING)
  774. {
  775. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  776. // Though currently they'll be delivered and might cause crash.
  777. vstd::clear_pointer(pack);
  778. }
  779. else
  780. {
  781. ServerHandlerCPackVisitor visitor(*this);
  782. pack->visit(visitor);
  783. }
  784. }
  785. }
  786. //catch only asio exceptions
  787. catch(const boost::system::system_error & e)
  788. {
  789. if(state == EClientState::DISCONNECTING)
  790. {
  791. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  792. }
  793. else
  794. {
  795. if (e.code() == boost::asio::error::eof)
  796. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  797. else
  798. logNetwork->error("Lost connection to server, ending listening thread! Reason: %s", e.what());
  799. if(client)
  800. {
  801. state = EClientState::DISCONNECTING;
  802. GH.dispatchMainThread([]()
  803. {
  804. CSH->endGameplay();
  805. GH.defActionsDef = 63;
  806. CMM->menu->switchToTab("main");
  807. });
  808. }
  809. else
  810. {
  811. auto lcd = new LobbyClientDisconnected();
  812. lcd->clientId = c->connectionID;
  813. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  814. packsForLobbyScreen.push_back(lcd);
  815. }
  816. }
  817. }
  818. }
  819. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  820. {
  821. if(applier->getApplier(typeList.getTypeID(&lobbyPack))->applyOnLobbyHandler(this, &lobbyPack))
  822. {
  823. if(!settings["session"]["headless"].Bool())
  824. {
  825. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  826. packsForLobbyScreen.push_back(&lobbyPack);
  827. }
  828. }
  829. }
  830. void CServerHandler::visitForClient(CPackForClient & clientPack)
  831. {
  832. client->handlePack(&clientPack);
  833. }
  834. void CServerHandler::threadRunServer()
  835. {
  836. #if !defined(VCMI_MOBILE)
  837. setThreadName("runServer");
  838. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  839. std::string comm = VCMIDirs::get().serverPath().string()
  840. + " --port=" + std::to_string(getHostPort())
  841. + " --run-by-client"
  842. + " --uuid=" + uuid;
  843. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  844. {
  845. comm += " --lobby=" + settings["session"]["address"].String();
  846. comm += " --connections=" + settings["session"]["hostConnections"].String();
  847. comm += " --lobby-port=" + std::to_string(settings["session"]["port"].Integer());
  848. comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
  849. }
  850. comm += " > \"" + logName + '\"';
  851. logGlobal->info("Server command line: %s", comm);
  852. #ifdef VCMI_WINDOWS
  853. int result = -1;
  854. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  855. if(bufSize > 0)
  856. {
  857. std::wstring wComm(bufSize, {});
  858. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  859. if(convertResult > 0)
  860. result = ::_wsystem(wComm.c_str());
  861. else
  862. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  863. }
  864. else
  865. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  866. #else
  867. int result = std::system(comm.c_str());
  868. #endif
  869. if (result == 0)
  870. {
  871. logNetwork->info("Server closed correctly");
  872. }
  873. else
  874. {
  875. logNetwork->error("Error: server failed to close correctly or crashed!");
  876. logNetwork->error("Check %s for more info", logName);
  877. }
  878. onServerFinished();
  879. #endif
  880. }
  881. void CServerHandler::onServerFinished()
  882. {
  883. threadRunLocalServer.reset();
  884. CSH->campaignServerRestartLock.setn(false);
  885. }
  886. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  887. {
  888. if(state != EClientState::STARTING)
  889. c->sendPack(&pack);
  890. }