CServerHandler.cpp 27 KB

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