CServerHandler.cpp 24 KB

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