CServerHandler.cpp 24 KB

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