CServerHandler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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(boost::posix_time::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(boost::posix_time::seconds(1));
  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::posix_time::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.turnTime = GameConstants::POSSIBLE_TURNTIME[npos];
  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. throw e;
  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.terminate_cond->setn(false);
  551. GH.curInt = CMM.get();
  552. CMM->enable();
  553. }
  554. else
  555. {
  556. GH.curInt = CMainMenu::create().get();
  557. }
  558. }
  559. c->enterLobbyConnectionMode();
  560. c->disableStackSendingByID();
  561. //reset settings
  562. Settings saveSession = settings.write["server"]["reconnect"];
  563. saveSession->Bool() = false;
  564. }
  565. void CServerHandler::startCampaignScenario(std::shared_ptr<CampaignState> cs)
  566. {
  567. std::shared_ptr<CampaignState> ourCampaign = cs;
  568. if (!cs)
  569. ourCampaign = si->campState;
  570. GH.dispatchMainThread([ourCampaign]()
  571. {
  572. CSH->campaignServerRestartLock.set(true);
  573. CSH->endGameplay();
  574. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  575. auto finisher = [=]()
  576. {
  577. if(!ourCampaign->isCampaignFinished())
  578. {
  579. GH.windows().pushWindow(CMM);
  580. GH.windows().pushWindow(CMM->menu);
  581. CMM->openCampaignLobby(ourCampaign);
  582. }
  583. };
  584. if(epilogue.hasPrologEpilog)
  585. {
  586. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  587. }
  588. else
  589. {
  590. CSH->campaignServerRestartLock.waitUntil(false);
  591. finisher();
  592. }
  593. });
  594. }
  595. void CServerHandler::showServerError(std::string txt) const
  596. {
  597. CInfoWindow::showInfoDialog(txt, {});
  598. }
  599. int CServerHandler::howManyPlayerInterfaces()
  600. {
  601. int playerInts = 0;
  602. for(auto pint : client->playerint)
  603. {
  604. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  605. playerInts++;
  606. }
  607. return playerInts;
  608. }
  609. ui8 CServerHandler::getLoadMode()
  610. {
  611. if(loadMode != ELoadMode::TUTORIAL && state == EClientState::GAMEPLAY)
  612. {
  613. if(si->campState)
  614. return ELoadMode::CAMPAIGN;
  615. for(auto pn : playerNames)
  616. {
  617. if(pn.second.connection != c->connectionID)
  618. return ELoadMode::MULTI;
  619. }
  620. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  621. return ELoadMode::MULTI;
  622. return ELoadMode::SINGLE;
  623. }
  624. return loadMode;
  625. }
  626. void CServerHandler::restoreLastSession()
  627. {
  628. auto loadSession = [this]()
  629. {
  630. uuid = settings["server"]["uuid"].String();
  631. for(auto & name : settings["server"]["names"].Vector())
  632. myNames.push_back(name.String());
  633. resetStateForLobby(StartInfo::LOAD_GAME, &myNames);
  634. screenType = ESelectionScreen::loadGame;
  635. justConnectToServer(settings["server"]["server"].String(), settings["server"]["port"].Integer());
  636. };
  637. auto cleanUpSession = []()
  638. {
  639. //reset settings
  640. Settings saveSession = settings.write["server"]["reconnect"];
  641. saveSession->Bool() = false;
  642. };
  643. CInfoWindow::showYesNoDialog(VLC->generaltexth->translate("vcmi.server.confirmReconnect"), {}, loadSession, cleanUpSession);
  644. }
  645. void CServerHandler::debugStartTest(std::string filename, bool save)
  646. {
  647. logGlobal->info("Starting debug test with file: %s", filename);
  648. auto mapInfo = std::make_shared<CMapInfo>();
  649. if(save)
  650. {
  651. resetStateForLobby(StartInfo::LOAD_GAME);
  652. mapInfo->saveInit(ResourceID(filename, EResType::SAVEGAME));
  653. screenType = ESelectionScreen::loadGame;
  654. }
  655. else
  656. {
  657. resetStateForLobby(StartInfo::NEW_GAME);
  658. mapInfo->mapInit(filename);
  659. screenType = ESelectionScreen::newGame;
  660. }
  661. if(settings["session"]["donotstartserver"].Bool())
  662. justConnectToServer(localhostAddress, 3030);
  663. else
  664. startLocalServerAndConnect();
  665. boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  666. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  667. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  668. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  669. {
  670. setMapInfo(mapInfo);
  671. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  672. }
  673. // "Click" on color to remove us from it
  674. setPlayer(myFirstColor());
  675. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  676. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  677. while(true)
  678. {
  679. try
  680. {
  681. sendStartGame();
  682. break;
  683. }
  684. catch(...)
  685. {
  686. }
  687. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  688. }
  689. }
  690. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  691. {
  692. private:
  693. CServerHandler & handler;
  694. public:
  695. ServerHandlerCPackVisitor(CServerHandler & handler)
  696. :handler(handler)
  697. {
  698. }
  699. virtual bool callTyped() override { return false; }
  700. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  701. {
  702. handler.visitForLobby(lobbyPack);
  703. }
  704. virtual void visitForClient(CPackForClient & clientPack) override
  705. {
  706. handler.visitForClient(clientPack);
  707. }
  708. };
  709. void CServerHandler::threadHandleConnection()
  710. {
  711. setThreadName("CServerHandler::threadHandleConnection");
  712. c->enterLobbyConnectionMode();
  713. try
  714. {
  715. sendClientConnecting();
  716. while(c->connected)
  717. {
  718. while(state == EClientState::STARTING)
  719. boost::this_thread::sleep(boost::posix_time::milliseconds(10));
  720. CPack * pack = c->retrievePack();
  721. if(state == EClientState::DISCONNECTING)
  722. {
  723. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  724. // Though currently they'll be delivered and might cause crash.
  725. vstd::clear_pointer(pack);
  726. }
  727. else
  728. {
  729. ServerHandlerCPackVisitor visitor(*this);
  730. pack->visit(visitor);
  731. }
  732. }
  733. }
  734. //catch only asio exceptions
  735. catch(const boost::system::system_error & e)
  736. {
  737. if(state == EClientState::DISCONNECTING)
  738. {
  739. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  740. }
  741. else
  742. {
  743. if (e.code() == boost::asio::error::eof)
  744. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  745. else
  746. logNetwork->error("Lost connection to server, ending listening thread! Reason: %s", e.what());
  747. if(client)
  748. {
  749. state = EClientState::DISCONNECTING;
  750. GH.dispatchMainThread([]()
  751. {
  752. CSH->endGameplay();
  753. GH.defActionsDef = 63;
  754. CMM->menu->switchToTab("main");
  755. });
  756. }
  757. else
  758. {
  759. auto lcd = new LobbyClientDisconnected();
  760. lcd->clientId = c->connectionID;
  761. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  762. packsForLobbyScreen.push_back(lcd);
  763. }
  764. }
  765. }
  766. }
  767. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  768. {
  769. if(applier->getApplier(typeList.getTypeID(&lobbyPack))->applyOnLobbyHandler(this, &lobbyPack))
  770. {
  771. if(!settings["session"]["headless"].Bool())
  772. {
  773. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  774. packsForLobbyScreen.push_back(&lobbyPack);
  775. }
  776. }
  777. }
  778. void CServerHandler::visitForClient(CPackForClient & clientPack)
  779. {
  780. client->handlePack(&clientPack);
  781. }
  782. void CServerHandler::threadRunServer()
  783. {
  784. #if !defined(VCMI_MOBILE)
  785. setThreadName("CServerHandler::threadRunServer");
  786. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  787. std::string comm = VCMIDirs::get().serverPath().string()
  788. + " --port=" + std::to_string(getHostPort())
  789. + " --run-by-client"
  790. + " --uuid=" + uuid;
  791. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  792. {
  793. comm += " --lobby=" + settings["session"]["address"].String();
  794. comm += " --connections=" + settings["session"]["hostConnections"].String();
  795. comm += " --lobby-port=" + std::to_string(settings["session"]["port"].Integer());
  796. comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
  797. }
  798. comm += " > \"" + logName + '\"';
  799. logGlobal->info("Server command line: %s", comm);
  800. #ifdef VCMI_WINDOWS
  801. int result = -1;
  802. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  803. if(bufSize > 0)
  804. {
  805. std::wstring wComm(bufSize, {});
  806. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  807. if(convertResult > 0)
  808. result = ::_wsystem(wComm.c_str());
  809. else
  810. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  811. }
  812. else
  813. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  814. #else
  815. int result = std::system(comm.c_str());
  816. #endif
  817. if (result == 0)
  818. {
  819. logNetwork->info("Server closed correctly");
  820. }
  821. else
  822. {
  823. logNetwork->error("Error: server failed to close correctly or crashed!");
  824. logNetwork->error("Check %s for more info", logName);
  825. }
  826. onServerFinished();
  827. #endif
  828. }
  829. void CServerHandler::onServerFinished()
  830. {
  831. threadRunLocalServer.reset();
  832. CSH->campaignServerRestartLock.setn(false);
  833. }
  834. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  835. {
  836. if(state != EClientState::STARTING)
  837. c->sendPack(&pack);
  838. }