CServerHandler.cpp 25 KB

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