CServerHandler.cpp 25 KB

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