CServerHandler.cpp 24 KB

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