CServerHandler.cpp 24 KB

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