CServerHandler.cpp 26 KB

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