CServerHandler.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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. logNetwork->info("justConnectToServer(%s, %d)", addr, port);
  219. std::string hostAddressFromSettings = getHostAddressFromSettings();
  220. ui16 hostPortFromSettings = getHostPortFromSettings();
  221. logNetwork->info("Host settings %s:%d", hostAddressFromSettings, hostPortFromSettings);
  222. std::string connectionAddress = addr.size() ? addr : hostAddressFromSettings;
  223. ui16 connectionPort = port ? port : hostPortFromSettings;
  224. boost::chrono::duration<long, boost::ratio<1, 1000>> sleepDuration{};
  225. int maxConnectionAttempts;
  226. if(connectionAddress == "127.0.0.1" || connectionAddress == "localhost")
  227. {
  228. logNetwork->info("Local server");
  229. sleepDuration = boost::chrono::milliseconds(10);
  230. maxConnectionAttempts = 1000;
  231. }
  232. else
  233. {
  234. logNetwork->info("Remote server");
  235. sleepDuration = boost::chrono::seconds(2);
  236. maxConnectionAttempts = 10;
  237. }
  238. logNetwork->info("Waiting for %d ms between each of the %d attempts to connect", sleepDuration.count(), maxConnectionAttempts);
  239. ui16 connectionAttemptCount = 0;
  240. while(!c && state != EClientState::CONNECTION_CANCELLED)
  241. {
  242. connectionAttemptCount++;
  243. if(connectionAttemptCount > maxConnectionAttempts)
  244. {
  245. logNetwork->error("\nExceeded 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::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  424. {
  425. LobbyChangePlayerOption lcpo;
  426. lcpo.what = what;
  427. lcpo.value = value;
  428. lcpo.color = player;
  429. sendLobbyPack(lcpo);
  430. }
  431. void CServerHandler::setDifficulty(int to) const
  432. {
  433. LobbySetDifficulty lsd;
  434. lsd.difficulty = to;
  435. sendLobbyPack(lsd);
  436. }
  437. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  438. {
  439. LobbySetSimturns pack;
  440. pack.simturnsInfo = info;
  441. sendLobbyPack(pack);
  442. }
  443. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  444. {
  445. LobbySetTurnTime lstt;
  446. lstt.turnTimerInfo = info;
  447. sendLobbyPack(lstt);
  448. }
  449. void CServerHandler::sendMessage(const std::string & txt) const
  450. {
  451. std::istringstream readed;
  452. readed.str(txt);
  453. std::string command;
  454. readed >> command;
  455. if(command == "!passhost")
  456. {
  457. std::string id;
  458. readed >> id;
  459. if(id.length())
  460. {
  461. LobbyChangeHost lch;
  462. lch.newHostConnectionId = boost::lexical_cast<int>(id);
  463. sendLobbyPack(lch);
  464. }
  465. }
  466. else if(command == "!forcep")
  467. {
  468. std::string connectedId, playerColorId;
  469. readed >> connectedId;
  470. readed >> playerColorId;
  471. if(connectedId.length() && playerColorId.length())
  472. {
  473. ui8 connected = boost::lexical_cast<int>(connectedId);
  474. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  475. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  476. {
  477. LobbyForceSetPlayer lfsp;
  478. lfsp.targetConnectedPlayer = connected;
  479. lfsp.targetPlayerColor = color;
  480. sendLobbyPack(lfsp);
  481. }
  482. }
  483. }
  484. else
  485. {
  486. LobbyChatMessage lcm;
  487. lcm.message = txt;
  488. lcm.playerName = playerNames.find(myFirstId())->second.name;
  489. sendLobbyPack(lcm);
  490. }
  491. }
  492. void CServerHandler::sendGuiAction(ui8 action) const
  493. {
  494. LobbyGuiAction lga;
  495. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  496. sendLobbyPack(lga);
  497. }
  498. void CServerHandler::sendRestartGame() const
  499. {
  500. GH.windows().createAndPushWindow<CLoadingScreen>();
  501. LobbyEndGame endGame;
  502. endGame.closeConnection = false;
  503. endGame.restart = true;
  504. sendLobbyPack(endGame);
  505. }
  506. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  507. {
  508. try
  509. {
  510. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  511. }
  512. catch(ModIncompatibility & e)
  513. {
  514. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  515. std::string errorMsg;
  516. if(!e.whatMissing().empty())
  517. {
  518. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  519. errorMsg += e.whatMissing();
  520. }
  521. if(!e.whatExcessive().empty())
  522. {
  523. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  524. errorMsg += e.whatExcessive();
  525. }
  526. showServerError(errorMsg);
  527. return false;
  528. }
  529. catch(std::exception & e)
  530. {
  531. logGlobal->error("Exception during startScenario: %s", e.what());
  532. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  533. return false;
  534. }
  535. return true;
  536. }
  537. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  538. {
  539. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  540. GH.windows().createAndPushWindow<CLoadingScreen>();
  541. LobbyStartGame lsg;
  542. if(client)
  543. {
  544. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  545. lsg.initializedStartInfo->mode = StartInfo::NEW_GAME;
  546. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  547. * si = * lsg.initializedStartInfo;
  548. }
  549. sendLobbyPack(lsg);
  550. c->enterLobbyConnectionMode();
  551. c->disableStackSendingByID();
  552. }
  553. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  554. {
  555. mapToStart = to;
  556. }
  557. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  558. {
  559. if(CMM)
  560. CMM->disable();
  561. client = new CClient();
  562. highScoreCalc = nullptr;
  563. switch(si->mode)
  564. {
  565. case StartInfo::NEW_GAME:
  566. client->newGame(gameState);
  567. break;
  568. case StartInfo::CAMPAIGN:
  569. client->newGame(gameState);
  570. break;
  571. case StartInfo::LOAD_GAME:
  572. client->loadGame(gameState);
  573. break;
  574. default:
  575. throw std::runtime_error("Invalid mode");
  576. }
  577. // After everything initialized we can accept CPackToClient netpacks
  578. c->enterGameplayConnectionMode(client->gameState());
  579. state = EClientState::GAMEPLAY;
  580. //store settings to continue game
  581. if(!isServerLocal() && isGuest())
  582. {
  583. Settings saveSession = settings.write["server"]["reconnect"];
  584. saveSession->Bool() = true;
  585. Settings saveUuid = settings.write["server"]["uuid"];
  586. saveUuid->String() = uuid;
  587. Settings saveNames = settings.write["server"]["names"];
  588. saveNames->Vector().clear();
  589. for(auto & name : myNames)
  590. {
  591. JsonNode jsonName;
  592. jsonName.String() = name;
  593. saveNames->Vector().push_back(jsonName);
  594. }
  595. }
  596. }
  597. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  598. {
  599. client->endGame();
  600. vstd::clear_pointer(client);
  601. if(closeConnection)
  602. {
  603. // Game is ending
  604. // Tell the network thread to reach a stable state
  605. CSH->sendClientDisconnecting();
  606. logNetwork->info("Closed connection.");
  607. }
  608. if(!restart)
  609. {
  610. if(CMM)
  611. {
  612. GH.curInt = CMM.get();
  613. CMM->enable();
  614. }
  615. else
  616. {
  617. GH.curInt = CMainMenu::create().get();
  618. }
  619. }
  620. if(c)
  621. {
  622. c->enterLobbyConnectionMode();
  623. c->disableStackSendingByID();
  624. }
  625. //reset settings
  626. Settings saveSession = settings.write["server"]["reconnect"];
  627. saveSession->Bool() = false;
  628. }
  629. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs)
  630. {
  631. std::shared_ptr<CampaignState> ourCampaign = cs;
  632. if (!cs)
  633. ourCampaign = si->campState;
  634. if(highScoreCalc == nullptr)
  635. {
  636. highScoreCalc = std::make_shared<HighScoreCalculation>();
  637. highScoreCalc->isCampaign = true;
  638. highScoreCalc->parameters.clear();
  639. }
  640. param.campaignName = cs->getNameTranslated();
  641. highScoreCalc->parameters.push_back(param);
  642. GH.dispatchMainThread([ourCampaign, this]()
  643. {
  644. CSH->campaignServerRestartLock.set(true);
  645. CSH->endGameplay();
  646. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  647. auto finisher = [=]()
  648. {
  649. if(ourCampaign->campaignSet != "")
  650. {
  651. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  652. entry->Bool() = true;
  653. }
  654. GH.windows().pushWindow(CMM);
  655. GH.windows().pushWindow(CMM->menu);
  656. if(!ourCampaign->isCampaignFinished())
  657. CMM->openCampaignLobby(ourCampaign);
  658. else
  659. {
  660. CMM->openCampaignScreen(ourCampaign->campaignSet);
  661. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *highScoreCalc);
  662. }
  663. };
  664. if(epilogue.hasPrologEpilog)
  665. {
  666. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  667. }
  668. else
  669. {
  670. CSH->campaignServerRestartLock.waitUntil(false);
  671. finisher();
  672. }
  673. });
  674. }
  675. void CServerHandler::showServerError(const std::string & txt) const
  676. {
  677. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  678. GH.windows().popWindow(w);
  679. CInfoWindow::showInfoDialog(txt, {});
  680. }
  681. int CServerHandler::howManyPlayerInterfaces()
  682. {
  683. int playerInts = 0;
  684. for(auto pint : client->playerint)
  685. {
  686. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  687. playerInts++;
  688. }
  689. return playerInts;
  690. }
  691. ui8 CServerHandler::getLoadMode()
  692. {
  693. if(loadMode != ELoadMode::TUTORIAL && state == EClientState::GAMEPLAY)
  694. {
  695. if(si->campState)
  696. return ELoadMode::CAMPAIGN;
  697. for(auto pn : playerNames)
  698. {
  699. if(pn.second.connection != c->connectionID)
  700. return ELoadMode::MULTI;
  701. }
  702. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  703. return ELoadMode::MULTI;
  704. return ELoadMode::SINGLE;
  705. }
  706. return loadMode;
  707. }
  708. void CServerHandler::restoreLastSession()
  709. {
  710. auto loadSession = [this]()
  711. {
  712. uuid = settings["server"]["uuid"].String();
  713. for(auto & name : settings["server"]["names"].Vector())
  714. myNames.push_back(name.String());
  715. resetStateForLobby(StartInfo::LOAD_GAME, &myNames);
  716. screenType = ESelectionScreen::loadGame;
  717. justConnectToServer(settings["server"]["server"].String(), settings["server"]["port"].Integer());
  718. };
  719. auto cleanUpSession = []()
  720. {
  721. //reset settings
  722. Settings saveSession = settings.write["server"]["reconnect"];
  723. saveSession->Bool() = false;
  724. };
  725. CInfoWindow::showYesNoDialog(VLC->generaltexth->translate("vcmi.server.confirmReconnect"), {}, loadSession, cleanUpSession);
  726. }
  727. void CServerHandler::debugStartTest(std::string filename, bool save)
  728. {
  729. logGlobal->info("Starting debug test with file: %s", filename);
  730. auto mapInfo = std::make_shared<CMapInfo>();
  731. if(save)
  732. {
  733. resetStateForLobby(StartInfo::LOAD_GAME);
  734. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  735. screenType = ESelectionScreen::loadGame;
  736. }
  737. else
  738. {
  739. resetStateForLobby(StartInfo::NEW_GAME);
  740. mapInfo->mapInit(filename);
  741. screenType = ESelectionScreen::newGame;
  742. }
  743. if(settings["session"]["donotstartserver"].Bool())
  744. justConnectToServer(localhostAddress, 3030);
  745. else
  746. startLocalServerAndConnect();
  747. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  748. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  749. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  750. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  751. {
  752. setMapInfo(mapInfo);
  753. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  754. }
  755. // "Click" on color to remove us from it
  756. setPlayer(myFirstColor());
  757. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  758. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  759. while(true)
  760. {
  761. try
  762. {
  763. sendStartGame();
  764. break;
  765. }
  766. catch(...)
  767. {
  768. }
  769. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  770. }
  771. }
  772. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  773. {
  774. private:
  775. CServerHandler & handler;
  776. public:
  777. ServerHandlerCPackVisitor(CServerHandler & handler)
  778. :handler(handler)
  779. {
  780. }
  781. virtual bool callTyped() override { return false; }
  782. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  783. {
  784. handler.visitForLobby(lobbyPack);
  785. }
  786. virtual void visitForClient(CPackForClient & clientPack) override
  787. {
  788. handler.visitForClient(clientPack);
  789. }
  790. };
  791. void CServerHandler::threadHandleConnection()
  792. {
  793. setThreadName("handleConnection");
  794. c->enterLobbyConnectionMode();
  795. try
  796. {
  797. sendClientConnecting();
  798. while(c->connected)
  799. {
  800. while(state == EClientState::STARTING)
  801. boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
  802. CPack * pack = c->retrievePack();
  803. if(state == EClientState::DISCONNECTING)
  804. {
  805. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  806. // Though currently they'll be delivered and might cause crash.
  807. vstd::clear_pointer(pack);
  808. }
  809. else
  810. {
  811. ServerHandlerCPackVisitor visitor(*this);
  812. pack->visit(visitor);
  813. }
  814. }
  815. }
  816. //catch only asio exceptions
  817. catch(const boost::system::system_error & e)
  818. {
  819. if(state == EClientState::DISCONNECTING)
  820. {
  821. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  822. }
  823. else
  824. {
  825. if (e.code() == boost::asio::error::eof)
  826. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  827. else
  828. logNetwork->error("Lost connection to server, ending listening thread! Reason: %s", e.what());
  829. if(client)
  830. {
  831. state = EClientState::DISCONNECTING;
  832. GH.dispatchMainThread([]()
  833. {
  834. CSH->endGameplay();
  835. GH.defActionsDef = 63;
  836. CMM->menu->switchToTab("main");
  837. });
  838. }
  839. else
  840. {
  841. auto lcd = new LobbyClientDisconnected();
  842. lcd->clientId = c->connectionID;
  843. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  844. packsForLobbyScreen.push_back(lcd);
  845. }
  846. }
  847. }
  848. }
  849. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  850. {
  851. if(applier->getApplier(typeList.getTypeID(&lobbyPack))->applyOnLobbyHandler(this, &lobbyPack))
  852. {
  853. if(!settings["session"]["headless"].Bool())
  854. {
  855. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  856. packsForLobbyScreen.push_back(&lobbyPack);
  857. }
  858. }
  859. }
  860. void CServerHandler::visitForClient(CPackForClient & clientPack)
  861. {
  862. client->handlePack(&clientPack);
  863. }
  864. void CServerHandler::threadRunServer()
  865. {
  866. #if !defined(VCMI_MOBILE)
  867. setThreadName("runServer");
  868. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  869. std::string comm = VCMIDirs::get().serverPath().string()
  870. + " --port=" + std::to_string(getHostPortFromSettings())
  871. + " --run-by-client"
  872. + " --uuid=" + uuid;
  873. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  874. {
  875. comm += " --lobby=" + settings["session"]["address"].String();
  876. comm += " --connections=" + settings["session"]["hostConnections"].String();
  877. comm += " --lobby-port=" + std::to_string(settings["session"]["port"].Integer());
  878. comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
  879. }
  880. comm += " > \"" + logName + '\"';
  881. logGlobal->info("Server command line: %s", comm);
  882. #ifdef VCMI_WINDOWS
  883. int result = -1;
  884. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  885. if(bufSize > 0)
  886. {
  887. std::wstring wComm(bufSize, {});
  888. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  889. if(convertResult > 0)
  890. result = ::_wsystem(wComm.c_str());
  891. else
  892. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  893. }
  894. else
  895. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  896. #else
  897. int result = std::system(comm.c_str());
  898. #endif
  899. if (result == 0)
  900. {
  901. logNetwork->info("Server closed correctly");
  902. }
  903. else
  904. {
  905. logNetwork->error("Error: server failed to close correctly or crashed!");
  906. logNetwork->error("Check %s for more info", logName);
  907. }
  908. onServerFinished();
  909. #endif
  910. }
  911. void CServerHandler::onServerFinished()
  912. {
  913. threadRunLocalServer.reset();
  914. CSH->campaignServerRestartLock.setn(false);
  915. }
  916. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  917. {
  918. if(state != EClientState::STARTING)
  919. c->sendPack(&pack);
  920. }