CServerHandler.cpp 24 KB

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