CServerHandler.cpp 26 KB

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