CServerHandler.cpp 27 KB

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