CServerHandler.cpp 22 KB

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