CServerHandler.cpp 24 KB

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