CServerHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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/NetPacks.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 <vcmi/events/EventBus.h>
  50. #ifdef VCMI_WINDOWS
  51. #include <windows.h>
  52. #endif
  53. template<typename T> class CApplyOnLobby;
  54. const std::string CServerHandler::localhostAddress{"127.0.0.1"};
  55. #ifdef VCMI_ANDROID
  56. extern std::atomic_bool androidTestServerReadyFlag;
  57. #endif
  58. class CBaseForLobbyApply
  59. {
  60. public:
  61. virtual bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const = 0;
  62. virtual void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const = 0;
  63. virtual ~CBaseForLobbyApply(){};
  64. template<typename U> static CBaseForLobbyApply * getApplier(const U * t = nullptr)
  65. {
  66. return new CApplyOnLobby<U>();
  67. }
  68. };
  69. template<typename T> class CApplyOnLobby : public CBaseForLobbyApply
  70. {
  71. public:
  72. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  73. {
  74. T * ptr = static_cast<T *>(pack);
  75. logNetwork->trace("\tImmediately apply on lobby: %s", typeList.getTypeInfo(ptr)->name());
  76. return ptr->applyOnLobbyHandler(handler);
  77. }
  78. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  79. {
  80. T * ptr = static_cast<T *>(pack);
  81. logNetwork->trace("\tApply on lobby from queue: %s", typeList.getTypeInfo(ptr)->name());
  82. ptr->applyOnLobbyScreen(lobby, handler);
  83. }
  84. };
  85. template<> class CApplyOnLobby<CPack>: public CBaseForLobbyApply
  86. {
  87. public:
  88. bool applyOnLobbyHandler(CServerHandler * handler, void * pack) const override
  89. {
  90. logGlobal->error("Cannot apply plain CPack!");
  91. assert(0);
  92. return false;
  93. }
  94. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, void * pack) const override
  95. {
  96. logGlobal->error("Cannot apply plain CPack!");
  97. assert(0);
  98. }
  99. };
  100. extern std::string NAME;
  101. CServerHandler::CServerHandler()
  102. : state(EClientState::NONE), mx(std::make_shared<boost::recursive_mutex>()), client(nullptr), loadMode(0), campaignStateToSend(nullptr), campaignServerRestartLock(false)
  103. {
  104. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  105. //read from file to restore last session
  106. if(!settings["server"]["uuid"].isNull() && !settings["server"]["uuid"].String().empty())
  107. uuid = settings["server"]["uuid"].String();
  108. applier = std::make_shared<CApplier<CBaseForLobbyApply>>();
  109. registerTypesLobbyPacks(*applier);
  110. }
  111. CServerHandler::~CServerHandler()
  112. {
  113. }
  114. void CServerHandler::handleConnection(std::shared_ptr<EnetConnection> _c)
  115. {
  116. c = std::make_shared<CConnection>(_c, NAME, uuid);
  117. c->handler = std::make_shared<boost::thread>(&CServerHandler::threadHandleConnection, this);
  118. }
  119. void CServerHandler::handleDisconnection(std::shared_ptr<EnetConnection> _c)
  120. {
  121. state = EClientState::DISCONNECTING;
  122. }
  123. void CServerHandler::resetStateForLobby(const StartInfo::EMode mode, const std::vector<std::string> * names)
  124. {
  125. hostClientId = -1;
  126. state = EClientState::NONE;
  127. th = std::make_unique<CStopWatch>();
  128. packsForLobbyScreen.clear();
  129. c.reset();
  130. si = std::make_shared<StartInfo>();
  131. playerNames.clear();
  132. si->difficulty = 1;
  133. si->mode = mode;
  134. myNames.clear();
  135. if(names && !names->empty()) //if have custom set of player names - use it
  136. myNames = *names;
  137. else
  138. myNames.push_back(settings["general"]["playerName"].String());
  139. #if !defined(VCMI_ANDROID) && !defined(SINGLE_PROCESS_APP)
  140. shm.reset();
  141. if(!settings["session"]["disable-shm"].Bool())
  142. {
  143. std::string sharedMemoryName = "vcmi_memory";
  144. if(settings["session"]["enable-shm-uuid"].Bool())
  145. {
  146. //used or automated testing when multiple clients start simultaneously
  147. sharedMemoryName += "_" + uuid;
  148. }
  149. try
  150. {
  151. shm = std::make_shared<SharedMemory>(sharedMemoryName, true);
  152. }
  153. catch(...)
  154. {
  155. shm.reset();
  156. logNetwork->error("Cannot open interprocess memory. Continue without it...");
  157. }
  158. }
  159. #endif
  160. }
  161. void CServerHandler::startLocalServerAndConnect()
  162. {
  163. /*auto errorMsg = CGI->generaltexth->localizedTexts["server"]["errors"]["existingProcess"].String();
  164. try
  165. {
  166. CConnection testConnection(enetClient, localhostAddress, getDefaultPort(), NAME, uuid);
  167. logNetwork->error("Port is busy, check if another instance of vcmiserver is working");
  168. CInfoWindow::showInfoDialog(errorMsg, {});
  169. return;
  170. }
  171. catch(...)
  172. {
  173. //no connection means that port is not busy and we can start local server
  174. }*/
  175. if(threadRunLocalServer)
  176. threadRunLocalServer->join();
  177. th->update();
  178. #ifdef VCMI_ANDROID
  179. {
  180. CAndroidVMHelper envHelper;
  181. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "startServer", true);
  182. }
  183. #elif defined(SINGLE_PROCESS_APP)
  184. boost::condition_variable cond;
  185. std::vector<std::string> args{"--uuid=" + uuid, "--port=" + boost::lexical_cast<std::string>(getHostPort())};
  186. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  187. {
  188. args.push_back("--lobby=" + settings["session"]["address"].String());
  189. args.push_back("--connections=" + settings["session"]["hostConnections"].String());
  190. args.push_back("--lobby-port=" + boost::lexical_cast<std::string>(settings["session"]["port"].Integer()));
  191. args.push_back("--lobby-uuid=" + settings["session"]["hostUuid"].String());
  192. }
  193. threadRunLocalServer = std::make_shared<boost::thread>([&cond, args, this] {
  194. setThreadName("CVCMIServer");
  195. CVCMIServer::create(&cond, args);
  196. onServerFinished();
  197. });
  198. threadRunLocalServer->detach();
  199. #else
  200. threadRunLocalServer = std::make_shared<boost::thread>(&CServerHandler::threadRunServer, this); //runs server executable;
  201. #endif
  202. logNetwork->trace("Setting up thread calling server: %d ms", th->getDiff());
  203. th->update();
  204. #ifdef VCMI_ANDROID
  205. logNetwork->info("waiting for server");
  206. while(!androidTestServerReadyFlag.load())
  207. {
  208. logNetwork->info("still waiting...");
  209. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  210. }
  211. logNetwork->info("waiting for server finished...");
  212. androidTestServerReadyFlag = false;
  213. #elif defined(SINGLE_PROCESS_APP)
  214. {
  215. #ifdef VCMI_IOS
  216. dispatch_sync(dispatch_get_main_queue(), ^{
  217. iOS_utils::showLoadingIndicator();
  218. });
  219. #endif
  220. boost::mutex m;
  221. boost::unique_lock<boost::mutex> lock{m};
  222. logNetwork->info("waiting for server");
  223. cond.wait(lock);
  224. logNetwork->info("server is ready");
  225. #ifdef VCMI_IOS
  226. dispatch_sync(dispatch_get_main_queue(), ^{
  227. iOS_utils::hideLoadingIndicator();
  228. });
  229. #endif
  230. }
  231. #else
  232. if(shm)
  233. shm->sr->waitTillReady();
  234. #endif
  235. logNetwork->trace("Waiting for server: %d ms", th->getDiff());
  236. th->update(); //put breakpoint here to attach to server before it does something stupid
  237. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  238. const ui16 port = shm ? shm->sr->port : 0;
  239. #else
  240. const ui16 port = 0;
  241. #endif
  242. justConnectToServer(localhostAddress, port);
  243. logNetwork->trace("\tConnecting to the server: %d ms", th->getDiff());
  244. }
  245. void CServerHandler::justConnectToServer(const std::string & addr, const ui16 port)
  246. {
  247. while(!valid() && state != EClientState::CONNECTION_CANCELLED)
  248. {
  249. logNetwork->info("Establishing connection...");
  250. init(port ? port : getHostPort(), addr.size() ? addr : getHostAddress());
  251. boost::this_thread::sleep(boost::posix_time::seconds(1));
  252. }
  253. while(state != EClientState::CONNECTING)
  254. {
  255. if(state == EClientState::CONNECTION_CANCELLED)
  256. {
  257. logNetwork->info("Connection aborted by player!");
  258. return;
  259. }
  260. boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  261. }
  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(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. SDL_Event event;
  579. event.type = SDL_USEREVENT;
  580. event.user.code = EUserEvent::CAMPAIGN_START_SCENARIO;
  581. if(cs)
  582. event.user.data1 = CMemorySerializer::deepCopy(*cs.get()).release();
  583. else
  584. event.user.data1 = CMemorySerializer::deepCopy(*si->campState.get()).release();
  585. SDL_PushEvent(&event);
  586. }
  587. void CServerHandler::showServerError(std::string txt)
  588. {
  589. CInfoWindow::showInfoDialog(txt, {});
  590. }
  591. int CServerHandler::howManyPlayerInterfaces()
  592. {
  593. int playerInts = 0;
  594. for(auto pint : client->playerint)
  595. {
  596. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  597. playerInts++;
  598. }
  599. return playerInts;
  600. }
  601. ui8 CServerHandler::getLoadMode()
  602. {
  603. if(state == EClientState::GAMEPLAY)
  604. {
  605. if(si->campState)
  606. return ELoadMode::CAMPAIGN;
  607. for(auto pn : playerNames)
  608. {
  609. if(pn.second.connection != c->connectionID)
  610. return ELoadMode::MULTI;
  611. }
  612. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  613. return ELoadMode::MULTI;
  614. return ELoadMode::SINGLE;
  615. }
  616. return loadMode;
  617. }
  618. void CServerHandler::restoreLastSession()
  619. {
  620. auto loadSession = [this]()
  621. {
  622. uuid = settings["server"]["uuid"].String();
  623. for(auto & name : settings["server"]["names"].Vector())
  624. myNames.push_back(name.String());
  625. resetStateForLobby(StartInfo::LOAD_GAME, &myNames);
  626. screenType = ESelectionScreen::loadGame;
  627. justConnectToServer(settings["server"]["server"].String(), settings["server"]["port"].Integer());
  628. };
  629. auto cleanUpSession = []()
  630. {
  631. //reset settings
  632. Settings saveSession = settings.write["server"]["reconnect"];
  633. saveSession->Bool() = false;
  634. };
  635. CInfoWindow::showYesNoDialog(VLC->generaltexth->translate("vcmi.server.confirmReconnect"), {}, loadSession, cleanUpSession);
  636. }
  637. void CServerHandler::debugStartTest(std::string filename, bool save)
  638. {
  639. logGlobal->info("Starting debug test with file: %s", filename);
  640. auto mapInfo = std::make_shared<CMapInfo>();
  641. if(save)
  642. {
  643. resetStateForLobby(StartInfo::LOAD_GAME);
  644. mapInfo->saveInit(ResourceID(filename, EResType::CLIENT_SAVEGAME));
  645. screenType = ESelectionScreen::loadGame;
  646. }
  647. else
  648. {
  649. resetStateForLobby(StartInfo::NEW_GAME);
  650. mapInfo->mapInit(filename);
  651. screenType = ESelectionScreen::newGame;
  652. }
  653. if(settings["session"]["donotstartserver"].Bool())
  654. justConnectToServer(localhostAddress, 3030);
  655. else
  656. startLocalServerAndConnect();
  657. boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  658. while(!settings["session"]["headless"].Bool() && !dynamic_cast<CLobbyScreen *>(GH.topInt().get()))
  659. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  660. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  661. {
  662. setMapInfo(mapInfo);
  663. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  664. }
  665. // "Click" on color to remove us from it
  666. setPlayer(myFirstColor());
  667. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  668. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  669. while(true)
  670. {
  671. try
  672. {
  673. sendStartGame();
  674. break;
  675. }
  676. catch(...)
  677. {
  678. }
  679. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  680. }
  681. }
  682. void CServerHandler::threadHandleConnection()
  683. {
  684. setThreadName("CServerHandler::threadHandleConnection");
  685. try
  686. {
  687. while(!c->isOpen())
  688. boost::this_thread::sleep(boost::posix_time::milliseconds(10));
  689. c->enterLobbyConnectionMode();
  690. sendClientConnecting();
  691. while(c->isOpen())
  692. {
  693. while(state == EClientState::STARTING)
  694. boost::this_thread::sleep(boost::posix_time::milliseconds(10));
  695. CPack * pack = c->retrievePack();
  696. if(state == EClientState::DISCONNECTING)
  697. {
  698. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  699. // Though currently they'll be delivered and might cause crash.
  700. vstd::clear_pointer(pack);
  701. }
  702. else if(auto lobbyPack = dynamic_ptr_cast<CPackForLobby>(pack))
  703. {
  704. if(applier->getApplier(typeList.getTypeID(pack))->applyOnLobbyHandler(this, pack))
  705. {
  706. if(!settings["session"]["headless"].Bool())
  707. {
  708. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  709. packsForLobbyScreen.push_back(lobbyPack);
  710. }
  711. }
  712. }
  713. else if(auto clientPack = dynamic_ptr_cast<CPackForClient>(pack))
  714. {
  715. client->handlePack(clientPack);
  716. }
  717. }
  718. }
  719. //catch only asio exceptions
  720. catch(const boost::system::system_error & e)
  721. {
  722. if(state == EClientState::DISCONNECTING)
  723. {
  724. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  725. }
  726. else
  727. {
  728. logNetwork->error("Lost connection to server, ending listening thread!");
  729. logNetwork->error(e.what());
  730. if(client)
  731. {
  732. state = EClientState::DISCONNECTING;
  733. CGuiHandler::pushSDLEvent(SDL_USEREVENT, EUserEvent::RETURN_TO_MAIN_MENU);
  734. }
  735. else
  736. {
  737. auto lcd = new LobbyClientDisconnected();
  738. lcd->clientId = c->connectionID;
  739. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  740. packsForLobbyScreen.push_back(lcd);
  741. }
  742. }
  743. }
  744. catch(...)
  745. {
  746. handleException();
  747. throw;
  748. }
  749. }
  750. void CServerHandler::threadRunServer()
  751. {
  752. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  753. setThreadName("CServerHandler::threadRunServer");
  754. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  755. std::string comm = VCMIDirs::get().serverPath().string()
  756. + " --port=" + boost::lexical_cast<std::string>(getHostPort())
  757. + " --run-by-client"
  758. + " --uuid=" + uuid;
  759. if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
  760. {
  761. comm += " --lobby=" + settings["session"]["address"].String();
  762. comm += " --connections=" + settings["session"]["hostConnections"].String();
  763. comm += " --lobby-port=" + boost::lexical_cast<std::string>(settings["session"]["port"].Integer());
  764. comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
  765. }
  766. if(shm)
  767. {
  768. comm += " --enable-shm";
  769. if(settings["session"]["enable-shm-uuid"].Bool())
  770. comm += " --enable-shm-uuid";
  771. }
  772. comm += " > \"" + logName + '\"';
  773. logGlobal->info("Server command line: %s", comm);
  774. #ifdef VCMI_WINDOWS
  775. int result = -1;
  776. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  777. if(bufSize > 0)
  778. {
  779. std::wstring wComm(bufSize, {});
  780. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  781. if(convertResult > 0)
  782. result = ::_wsystem(wComm.c_str());
  783. else
  784. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  785. }
  786. else
  787. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  788. #else
  789. int result = std::system(comm.c_str());
  790. #endif
  791. if (result == 0)
  792. {
  793. logNetwork->info("Server closed correctly");
  794. }
  795. else
  796. {
  797. logNetwork->error("Error: server failed to close correctly or crashed!");
  798. logNetwork->error("Check %s for more info", logName);
  799. }
  800. onServerFinished();
  801. #endif
  802. }
  803. void CServerHandler::onServerFinished()
  804. {
  805. threadRunLocalServer.reset();
  806. CSH->campaignServerRestartLock.setn(false);
  807. }
  808. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  809. {
  810. boost::unique_lock<boost::recursive_mutex> lock(*mx);
  811. if(state != EClientState::STARTING)
  812. c->sendPack(&pack);
  813. }