CServerHandler.cpp 26 KB

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