CServerHandler.cpp 25 KB

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