CServerHandler.cpp 24 KB

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