CServerHandler.cpp 25 KB

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