CServerHandler.cpp 22 KB

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