CServerHandler.cpp 26 KB

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