CServerHandler.cpp 22 KB

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