CServerHandler.cpp 25 KB

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