CServerHandler.cpp 24 KB

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