CServerHandler.cpp 24 KB

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