CServerHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  468. LobbyStartGame lsg;
  469. if(client)
  470. {
  471. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  472. lsg.initializedStartInfo->mode = StartInfo::NEW_GAME;
  473. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  474. * si = * lsg.initializedStartInfo;
  475. }
  476. sendLobbyPack(lsg);
  477. c->enterLobbyConnectionMode();
  478. c->disableStackSendingByID();
  479. }
  480. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  481. {
  482. if(CMM)
  483. CMM->disable();
  484. client = new CClient();
  485. switch(si->mode)
  486. {
  487. case StartInfo::NEW_GAME:
  488. client->newGame(gameState);
  489. break;
  490. case StartInfo::CAMPAIGN:
  491. client->newGame(gameState);
  492. break;
  493. case StartInfo::LOAD_GAME:
  494. client->loadGame(gameState);
  495. break;
  496. default:
  497. throw std::runtime_error("Invalid mode");
  498. }
  499. // After everything initialized we can accept CPackToClient netpacks
  500. c->enterGameplayConnectionMode(client->gameState());
  501. state = EClientState::GAMEPLAY;
  502. //store settings to continue game
  503. if(!isServerLocal() && isGuest())
  504. {
  505. Settings saveSession = settings.write["server"]["reconnect"];
  506. saveSession->Bool() = true;
  507. Settings saveUuid = settings.write["server"]["uuid"];
  508. saveUuid->String() = uuid;
  509. Settings saveNames = settings.write["server"]["names"];
  510. saveNames->Vector().clear();
  511. for(auto & name : myNames)
  512. {
  513. JsonNode jsonName;
  514. jsonName.String() = name;
  515. saveNames->Vector().push_back(jsonName);
  516. }
  517. }
  518. }
  519. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  520. {
  521. client->endGame();
  522. vstd::clear_pointer(client);
  523. if(closeConnection)
  524. {
  525. // Game is ending
  526. // Tell the network thread to reach a stable state
  527. CSH->sendClientDisconnecting();
  528. logNetwork->info("Closed connection.");
  529. }
  530. if(!restart)
  531. {
  532. if(CMM)
  533. {
  534. GH.terminate_cond->setn(false);
  535. GH.curInt = CMM.get();
  536. CMM->enable();
  537. }
  538. else
  539. {
  540. GH.curInt = CMainMenu::create().get();
  541. }
  542. }
  543. c->enterLobbyConnectionMode();
  544. c->disableStackSendingByID();
  545. //reset settings
  546. Settings saveSession = settings.write["server"]["reconnect"];
  547. saveSession->Bool() = false;
  548. }
  549. void CServerHandler::startCampaignScenario(std::shared_ptr<CampaignState> cs)
  550. {
  551. std::shared_ptr<CampaignState> ourCampaign = cs;
  552. if (!cs)
  553. ourCampaign = si->campState;
  554. GH.dispatchMainThread([ourCampaign]()
  555. {
  556. CSH->campaignServerRestartLock.set(true);
  557. CSH->endGameplay();
  558. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  559. auto finisher = [=]()
  560. {
  561. if(!ourCampaign->isCampaignFinished())
  562. {
  563. GH.windows().pushWindow(CMM);
  564. GH.windows().pushWindow(CMM->menu);
  565. CMM->openCampaignLobby(ourCampaign);
  566. }
  567. };
  568. if(epilogue.hasPrologEpilog)
  569. {
  570. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  571. }
  572. else
  573. {
  574. CSH->campaignServerRestartLock.waitUntil(false);
  575. finisher();
  576. }
  577. });
  578. }
  579. void CServerHandler::showServerError(std::string txt)
  580. {
  581. CInfoWindow::showInfoDialog(txt, {});
  582. }
  583. int CServerHandler::howManyPlayerInterfaces()
  584. {
  585. int playerInts = 0;
  586. for(auto pint : client->playerint)
  587. {
  588. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  589. playerInts++;
  590. }
  591. return playerInts;
  592. }
  593. ui8 CServerHandler::getLoadMode()
  594. {
  595. if(state == EClientState::GAMEPLAY)
  596. {
  597. if(si->campState)
  598. return ELoadMode::CAMPAIGN;
  599. for(auto pn : playerNames)
  600. {
  601. if(pn.second.connection != c->connectionID)
  602. return ELoadMode::MULTI;
  603. }
  604. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  605. return ELoadMode::MULTI;
  606. return ELoadMode::SINGLE;
  607. }
  608. return loadMode;
  609. }
  610. void CServerHandler::restoreLastSession()
  611. {
  612. auto loadSession = [this]()
  613. {
  614. uuid = settings["server"]["uuid"].String();
  615. for(auto & name : settings["server"]["names"].Vector())
  616. myNames.push_back(name.String());
  617. resetStateForLobby(StartInfo::LOAD_GAME, &myNames);
  618. screenType = ESelectionScreen::loadGame;
  619. justConnectToServer(settings["server"]["server"].String(), settings["server"]["port"].Integer());
  620. };
  621. auto cleanUpSession = []()
  622. {
  623. //reset settings
  624. Settings saveSession = settings.write["server"]["reconnect"];
  625. saveSession->Bool() = false;
  626. };
  627. CInfoWindow::showYesNoDialog(VLC->generaltexth->translate("vcmi.server.confirmReconnect"), {}, loadSession, cleanUpSession);
  628. }
  629. void CServerHandler::debugStartTest(std::string filename, bool save)
  630. {
  631. logGlobal->info("Starting debug test with file: %s", filename);
  632. auto mapInfo = std::make_shared<CMapInfo>();
  633. if(save)
  634. {
  635. resetStateForLobby(StartInfo::LOAD_GAME);
  636. mapInfo->saveInit(ResourceID(filename, EResType::SAVEGAME));
  637. screenType = ESelectionScreen::loadGame;
  638. }
  639. else
  640. {
  641. resetStateForLobby(StartInfo::NEW_GAME);
  642. mapInfo->mapInit(filename);
  643. screenType = ESelectionScreen::newGame;
  644. }
  645. if(settings["session"]["donotstartserver"].Bool())
  646. justConnectToServer(localhostAddress, 3030);
  647. else
  648. startLocalServerAndConnect();
  649. boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  650. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  651. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  652. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  653. {
  654. setMapInfo(mapInfo);
  655. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  656. }
  657. // "Click" on color to remove us from it
  658. setPlayer(myFirstColor());
  659. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  660. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  661. while(true)
  662. {
  663. try
  664. {
  665. sendStartGame();
  666. break;
  667. }
  668. catch(...)
  669. {
  670. }
  671. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  672. }
  673. }
  674. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  675. {
  676. private:
  677. CServerHandler & handler;
  678. public:
  679. ServerHandlerCPackVisitor(CServerHandler & handler)
  680. :handler(handler)
  681. {
  682. }
  683. virtual bool callTyped() override { return false; }
  684. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  685. {
  686. handler.visitForLobby(lobbyPack);
  687. }
  688. virtual void visitForClient(CPackForClient & clientPack) override
  689. {
  690. handler.visitForClient(clientPack);
  691. }
  692. };
  693. void CServerHandler::threadHandleConnection()
  694. {
  695. setThreadName("CServerHandler::threadHandleConnection");
  696. c->enterLobbyConnectionMode();
  697. try
  698. {
  699. sendClientConnecting();
  700. while(c->connected)
  701. {
  702. while(state == EClientState::STARTING)
  703. boost::this_thread::sleep(boost::posix_time::milliseconds(10));
  704. CPack * pack = c->retrievePack();
  705. if(state == EClientState::DISCONNECTING)
  706. {
  707. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  708. // Though currently they'll be delivered and might cause crash.
  709. vstd::clear_pointer(pack);
  710. }
  711. else
  712. {
  713. ServerHandlerCPackVisitor visitor(*this);
  714. pack->visit(visitor);
  715. }
  716. }
  717. }
  718. //catch only asio exceptions
  719. catch(const boost::system::system_error & e)
  720. {
  721. if(state == EClientState::DISCONNECTING)
  722. {
  723. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  724. }
  725. else
  726. {
  727. if (e.code() == boost::asio::error::eof)
  728. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  729. else
  730. logNetwork->error("Lost connection to server, ending listening thread! Reason: %s", e.what());
  731. if(client)
  732. {
  733. state = EClientState::DISCONNECTING;
  734. GH.dispatchMainThread([]()
  735. {
  736. CSH->endGameplay();
  737. GH.defActionsDef = 63;
  738. CMM->menu->switchToTab("main");
  739. });
  740. }
  741. else
  742. {
  743. auto lcd = new LobbyClientDisconnected();
  744. lcd->clientId = c->connectionID;
  745. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  746. packsForLobbyScreen.push_back(lcd);
  747. }
  748. }
  749. }
  750. }
  751. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  752. {
  753. if(applier->getApplier(typeList.getTypeID(&lobbyPack))->applyOnLobbyHandler(this, &lobbyPack))
  754. {
  755. if(!settings["session"]["headless"].Bool())
  756. {
  757. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  758. packsForLobbyScreen.push_back(&lobbyPack);
  759. }
  760. }
  761. }
  762. void CServerHandler::visitForClient(CPackForClient & clientPack)
  763. {
  764. client->handlePack(&clientPack);
  765. }
  766. void CServerHandler::threadRunServer()
  767. {
  768. #if !defined(VCMI_MOBILE)
  769. setThreadName("CServerHandler::threadRunServer");
  770. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  771. std::string comm = VCMIDirs::get().serverPath().string()
  772. + " --port=" + std::to_string(getHostPort())
  773. + " --run-by-client"
  774. + " --uuid=" + uuid;
  775. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  776. {
  777. comm += " --lobby=" + settings["session"]["address"].String();
  778. comm += " --connections=" + settings["session"]["hostConnections"].String();
  779. comm += " --lobby-port=" + std::to_string(settings["session"]["port"].Integer());
  780. comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
  781. }
  782. comm += " > \"" + logName + '\"';
  783. logGlobal->info("Server command line: %s", comm);
  784. #ifdef VCMI_WINDOWS
  785. int result = -1;
  786. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  787. if(bufSize > 0)
  788. {
  789. std::wstring wComm(bufSize, {});
  790. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  791. if(convertResult > 0)
  792. result = ::_wsystem(wComm.c_str());
  793. else
  794. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  795. }
  796. else
  797. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  798. #else
  799. int result = std::system(comm.c_str());
  800. #endif
  801. if (result == 0)
  802. {
  803. logNetwork->info("Server closed correctly");
  804. }
  805. else
  806. {
  807. logNetwork->error("Error: server failed to close correctly or crashed!");
  808. logNetwork->error("Check %s for more info", logName);
  809. }
  810. onServerFinished();
  811. #endif
  812. }
  813. void CServerHandler::onServerFinished()
  814. {
  815. threadRunLocalServer.reset();
  816. CSH->campaignServerRestartLock.setn(false);
  817. }
  818. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  819. {
  820. if(state != EClientState::STARTING)
  821. c->sendPack(&pack);
  822. }