CVCMIServer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /*
  2. * CVCMIServer.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 <boost/asio.hpp>
  12. #include "../lib/filesystem/Filesystem.h"
  13. #include "../lib/mapping/CCampaignHandler.h"
  14. #include "../lib/CThreadHelper.h"
  15. #include "../lib/serializer/Connection.h"
  16. #include "../lib/CModHandler.h"
  17. #include "../lib/CArtHandler.h"
  18. #include "../lib/CGeneralTextHandler.h"
  19. #include "../lib/CHeroHandler.h"
  20. #include "../lib/CTownHandler.h"
  21. #include "../lib/CBuildingHandler.h"
  22. #include "../lib/spells/CSpellHandler.h"
  23. #include "../lib/CCreatureHandler.h"
  24. #include "zlib.h"
  25. #include "CVCMIServer.h"
  26. #include "../lib/StartInfo.h"
  27. #include "../lib/mapping/CMap.h"
  28. #include "../lib/rmg/CMapGenOptions.h"
  29. #ifdef VCMI_ANDROID
  30. #include "lib/CAndroidVMHelper.h"
  31. #else
  32. #include "../lib/Interprocess.h"
  33. #endif
  34. #include "../lib/VCMI_Lib.h"
  35. #include "../lib/VCMIDirs.h"
  36. #include "CGameHandler.h"
  37. #include "../lib/mapping/CMapInfo.h"
  38. #include "../lib/GameConstants.h"
  39. #include "../lib/logging/CBasicLogConfigurator.h"
  40. #include "../lib/CConfigHandler.h"
  41. #include "../lib/ScopeGuard.h"
  42. #include "../lib/UnlockGuard.h"
  43. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  44. #include <execinfo.h>
  45. #endif
  46. std::string NAME_AFFIX = "server";
  47. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  48. std::atomic<bool> serverShuttingDown(false);
  49. boost::program_options::variables_map cmdLineOptions;
  50. static void vaccept(boost::asio::ip::tcp::acceptor *ac, boost::asio::ip::tcp::socket *s, boost::system::error_code *error)
  51. {
  52. ac->accept(*s,*error);
  53. }
  54. CPregameServer::CPregameServer(CConnection * Host, TAcceptor * Acceptor)
  55. : host(Host), listeningThreads(0), acceptor(Acceptor), upcomingConnection(nullptr),
  56. curmap(nullptr), curStartInfo(nullptr), state(RUNNING)
  57. {
  58. initConnection(host);
  59. }
  60. void CPregameServer::handleConnection(CConnection *cpc)
  61. {
  62. setThreadName("CPregameServer::handleConnection");
  63. try
  64. {
  65. while(!cpc->receivedStop)
  66. {
  67. CPackForSelectionScreen *cpfs = nullptr;
  68. *cpc >> cpfs;
  69. logNetwork->info("Got package to announce %s from %s", typeid(*cpfs).name(), cpc->toString());
  70. boost::unique_lock<boost::recursive_mutex> queueLock(mx);
  71. bool quitting = dynamic_ptr_cast<QuitMenuWithoutStarting>(cpfs),
  72. startingGame = dynamic_ptr_cast<StartWithCurrentSettings>(cpfs);
  73. if(quitting || startingGame) //host leaves main menu or wants to start game -> we end
  74. {
  75. cpc->receivedStop = true;
  76. if(!cpc->sendStop)
  77. sendPack(cpc, *cpfs);
  78. if(cpc == host)
  79. toAnnounce.push_back(cpfs);
  80. }
  81. else
  82. toAnnounce.push_back(cpfs);
  83. if(startingGame)
  84. {
  85. //wait for sending thread to announce start
  86. auto unlock = vstd::makeUnlockGuard(mx);
  87. while(state == RUNNING) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  88. }
  89. else if(quitting) // Server must be stopped if host is leaving from lobby to avoid crash
  90. {
  91. serverShuttingDown = true;
  92. }
  93. }
  94. }
  95. catch (const std::exception& e)
  96. {
  97. boost::unique_lock<boost::recursive_mutex> queueLock(mx);
  98. logNetwork->error("%s dies... \nWhat happened: %s", cpc->toString(), e.what());
  99. }
  100. boost::unique_lock<boost::recursive_mutex> queueLock(mx);
  101. if(state != ENDING_AND_STARTING_GAME)
  102. {
  103. connections -= cpc;
  104. //notify other players about leaving
  105. auto pl = new PlayerLeft();
  106. pl->playerID = cpc->connectionID;
  107. announceTxt(cpc->name + " left the game");
  108. toAnnounce.push_back(pl);
  109. if(connections.empty())
  110. {
  111. logNetwork->error("Last connection lost, server will close itself...");
  112. boost::this_thread::sleep(boost::posix_time::seconds(2)); //we should never be hasty when networking
  113. state = ENDING_WITHOUT_START;
  114. }
  115. }
  116. logNetwork->info("Thread listening for %s ended", cpc->toString());
  117. listeningThreads--;
  118. vstd::clear_pointer(cpc->handler);
  119. }
  120. void CPregameServer::run()
  121. {
  122. startListeningThread(host);
  123. start_async_accept();
  124. while(state == RUNNING)
  125. {
  126. {
  127. boost::unique_lock<boost::recursive_mutex> myLock(mx);
  128. while(!toAnnounce.empty())
  129. {
  130. processPack(toAnnounce.front());
  131. toAnnounce.pop_front();
  132. }
  133. // //we end sending thread if we ordered all our connections to stop
  134. // ending = true;
  135. // for(CPregameConnection *pc : connections)
  136. // if(!pc->sendStop)
  137. // ending = false;
  138. if(state != RUNNING)
  139. {
  140. logNetwork->info("Stopping listening for connections...");
  141. acceptor->close();
  142. }
  143. if(acceptor)
  144. {
  145. acceptor->get_io_service().reset();
  146. acceptor->get_io_service().poll();
  147. }
  148. } //frees lock
  149. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  150. }
  151. logNetwork->info("Thread handling connections ended");
  152. if(state == ENDING_AND_STARTING_GAME)
  153. {
  154. logNetwork->info("Waiting for listening thread to finish...");
  155. while(listeningThreads) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  156. logNetwork->info("Preparing new game");
  157. }
  158. }
  159. CPregameServer::~CPregameServer()
  160. {
  161. delete acceptor;
  162. delete upcomingConnection;
  163. for(CPackForSelectionScreen *pack : toAnnounce)
  164. delete pack;
  165. toAnnounce.clear();
  166. //TODO pregameconnections
  167. }
  168. void CPregameServer::connectionAccepted(const boost::system::error_code& ec)
  169. {
  170. if(ec)
  171. {
  172. logNetwork->info("Something wrong during accepting: %s", ec.message());
  173. return;
  174. }
  175. try
  176. {
  177. logNetwork->info("We got a new connection! :)");
  178. std::string name = NAME;
  179. CConnection *pc = new CConnection(upcomingConnection, name.append(" STATE_PREGAME"));
  180. initConnection(pc);
  181. upcomingConnection = nullptr;
  182. startListeningThread(pc);
  183. *pc << (ui8)pc->connectionID << curmap;
  184. announceTxt(pc->name + " joins the game");
  185. auto pj = new PlayerJoined();
  186. pj->playerName = pc->name;
  187. pj->connectionID = pc->connectionID;
  188. toAnnounce.push_back(pj);
  189. }
  190. catch(std::exception& e)
  191. {
  192. upcomingConnection = nullptr;
  193. logNetwork->info("I guess it was just my imagination!");
  194. }
  195. start_async_accept();
  196. }
  197. void CPregameServer::start_async_accept()
  198. {
  199. assert(!upcomingConnection);
  200. assert(acceptor);
  201. upcomingConnection = new TSocket(acceptor->get_io_service());
  202. acceptor->async_accept(*upcomingConnection, std::bind(&CPregameServer::connectionAccepted, this, _1));
  203. }
  204. void CPregameServer::announceTxt(const std::string &txt, const std::string &playerName)
  205. {
  206. logNetwork->info("%s says: %s", playerName, txt);
  207. ChatMessage cm;
  208. cm.playerName = playerName;
  209. cm.message = txt;
  210. boost::unique_lock<boost::recursive_mutex> queueLock(mx);
  211. toAnnounce.push_front(new ChatMessage(cm));
  212. }
  213. void CPregameServer::announcePack(const CPackForSelectionScreen &pack)
  214. {
  215. for(CConnection *pc : connections)
  216. sendPack(pc, pack);
  217. }
  218. void CPregameServer::sendPack(CConnection * pc, const CPackForSelectionScreen & pack)
  219. {
  220. if(!pc->sendStop)
  221. {
  222. logNetwork->info("\tSending pack of type %s to %s", typeid(pack).name(), pc->toString());
  223. *pc << &pack;
  224. }
  225. if(dynamic_ptr_cast<QuitMenuWithoutStarting>(&pack))
  226. {
  227. pc->sendStop = true;
  228. }
  229. else if(dynamic_ptr_cast<StartWithCurrentSettings>(&pack))
  230. {
  231. pc->sendStop = true;
  232. }
  233. }
  234. void CPregameServer::processPack(CPackForSelectionScreen * pack)
  235. {
  236. if(dynamic_ptr_cast<CPregamePackToHost>(pack))
  237. {
  238. sendPack(host, *pack);
  239. }
  240. else if(SelectMap *sm = dynamic_ptr_cast<SelectMap>(pack))
  241. {
  242. vstd::clear_pointer(curmap);
  243. curmap = sm->mapInfo;
  244. sm->free = false;
  245. announcePack(*pack);
  246. }
  247. else if(UpdateStartOptions *uso = dynamic_ptr_cast<UpdateStartOptions>(pack))
  248. {
  249. vstd::clear_pointer(curStartInfo);
  250. curStartInfo = uso->options;
  251. uso->free = false;
  252. announcePack(*pack);
  253. }
  254. else if(dynamic_ptr_cast<StartWithCurrentSettings>(pack))
  255. {
  256. state = ENDING_AND_STARTING_GAME;
  257. announcePack(*pack);
  258. }
  259. else
  260. announcePack(*pack);
  261. delete pack;
  262. }
  263. void CPregameServer::initConnection(CConnection *c)
  264. {
  265. *c >> c->name;
  266. connections.insert(c);
  267. logNetwork->info("Pregame connection with player %s established!", c->name);
  268. }
  269. void CPregameServer::startListeningThread(CConnection * pc)
  270. {
  271. listeningThreads++;
  272. pc->enterPregameConnectionMode();
  273. pc->handler = new boost::thread(&CPregameServer::handleConnection, this, pc);
  274. }
  275. CVCMIServer::CVCMIServer()
  276. : port(3030), io(new boost::asio::io_service()), firstConnection(nullptr), shared(nullptr)
  277. {
  278. logNetwork->trace("CVCMIServer created!");
  279. if(cmdLineOptions.count("port"))
  280. port = cmdLineOptions["port"].as<ui16>();
  281. logNetwork->info("Port %d will be used", port);
  282. try
  283. {
  284. acceptor = new TAcceptor(*io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port));
  285. }
  286. catch(...)
  287. {
  288. logNetwork->info("Port %d is busy, trying to use random port instead", port);
  289. if(cmdLineOptions.count("run-by-client") && !cmdLineOptions.count("enable-shm"))
  290. {
  291. logNetwork->error("Cant pass port number to client without shared memory!", port);
  292. exit(0);
  293. }
  294. acceptor = new TAcceptor(*io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0));
  295. port = acceptor->local_endpoint().port();
  296. }
  297. logNetwork->info("Listening for connections at port %d", port);
  298. }
  299. CVCMIServer::~CVCMIServer()
  300. {
  301. //delete io;
  302. //delete acceptor;
  303. //delete firstConnection;
  304. }
  305. std::shared_ptr<CGameHandler> CVCMIServer::initGhFromHostingConnection(CConnection &c)
  306. {
  307. auto gh = std::make_shared<CGameHandler>();
  308. StartInfo si;
  309. c >> si; //get start options
  310. if(!si.createRandomMap())
  311. {
  312. bool mapFound = CResourceHandler::get()->existsResource(ResourceID(si.mapname, EResType::MAP));
  313. //TODO some checking for campaigns
  314. if(!mapFound && si.mode == StartInfo::NEW_GAME)
  315. {
  316. c << ui8(1); //WRONG!
  317. gh.reset();
  318. return gh;
  319. }
  320. }
  321. c << ui8(0); //OK!
  322. gh->init(&si);
  323. gh->conns.insert(&c);
  324. return gh;
  325. }
  326. void CVCMIServer::newGame()
  327. {
  328. CConnection &c = *firstConnection;
  329. ui8 clients;
  330. c >> clients; //how many clients should be connected
  331. assert(clients == 1); //multi goes now by newPregame, TODO: custom lobbies
  332. auto gh = initGhFromHostingConnection(c);
  333. if(gh)
  334. gh->run(false);
  335. }
  336. void CVCMIServer::newPregame()
  337. {
  338. auto cps = new CPregameServer(firstConnection, acceptor);
  339. cps->run();
  340. if(cps->state == CPregameServer::ENDING_WITHOUT_START)
  341. {
  342. delete cps;
  343. return;
  344. }
  345. if(cps->state == CPregameServer::ENDING_AND_STARTING_GAME)
  346. {
  347. CGameHandler gh;
  348. gh.conns = cps->connections;
  349. gh.init(cps->curStartInfo);
  350. for(CConnection *c : gh.conns)
  351. c->addStdVecItems(gh.gs);
  352. gh.run(false);
  353. }
  354. }
  355. void CVCMIServer::start()
  356. {
  357. #ifndef VCMI_ANDROID
  358. if(cmdLineOptions.count("enable-shm"))
  359. {
  360. std::string sharedMemoryName = "vcmi_memory";
  361. if(cmdLineOptions.count("enable-shm-uuid") && cmdLineOptions.count("uuid"))
  362. {
  363. sharedMemoryName += "_" + cmdLineOptions["uuid"].as<std::string>();
  364. }
  365. shared = new SharedMemory(sharedMemoryName);
  366. }
  367. #endif
  368. boost::system::error_code error;
  369. for (;;)
  370. {
  371. try
  372. {
  373. auto s = new boost::asio::ip::tcp::socket(acceptor->get_io_service());
  374. boost::thread acc(std::bind(vaccept,acceptor,s,&error));
  375. #ifdef VCMI_ANDROID
  376. { // in block to clean-up vm helper after use, because we don't need to keep this thread attached to vm
  377. CAndroidVMHelper envHelper;
  378. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "onServerReady");
  379. logNetwork->info("Sending server ready message to client");
  380. }
  381. #else
  382. if(shared)
  383. {
  384. shared->sr->setToReadyAndNotify(port);
  385. }
  386. #endif
  387. acc.join();
  388. if (error)
  389. {
  390. logNetwork->warn("Got connection but there is an error %s", error.message());
  391. return;
  392. }
  393. logNetwork->info("We've accepted someone... ");
  394. std::string name = NAME;
  395. firstConnection = new CConnection(s, name.append(" STATE_WAITING"));
  396. logNetwork->info("Got connection!");
  397. while(!serverShuttingDown)
  398. {
  399. ui8 mode;
  400. *firstConnection >> mode;
  401. switch (mode)
  402. {
  403. case 0:
  404. firstConnection->close();
  405. exit(0);
  406. case 1:
  407. firstConnection->close();
  408. return;
  409. case 2:
  410. newGame();
  411. break;
  412. case 3:
  413. loadGame();
  414. break;
  415. case 4:
  416. newPregame();
  417. break;
  418. }
  419. }
  420. break;
  421. }
  422. catch(std::exception& e)
  423. {
  424. vstd::clear_pointer(firstConnection);
  425. logNetwork->info("I guess it was just my imagination!");
  426. }
  427. }
  428. }
  429. void CVCMIServer::loadGame()
  430. {
  431. CConnection &c = *firstConnection;
  432. std::string fname;
  433. CGameHandler gh;
  434. boost::system::error_code error;
  435. ui8 clients;
  436. c >> clients >> fname; //how many clients should be connected
  437. {
  438. CLoadFile lf(*CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  439. gh.loadCommonState(lf);
  440. lf >> gh;
  441. }
  442. c << ui8(0);
  443. gh.conns.insert(firstConnection);
  444. for(int i=1; i<clients; i++)
  445. {
  446. auto s = make_unique<boost::asio::ip::tcp::socket>(acceptor->get_io_service());
  447. acceptor->accept(*s,error);
  448. if(error) //retry
  449. {
  450. logNetwork->warn("Cannot establish connection - retrying...");
  451. i--;
  452. continue;
  453. }
  454. gh.conns.insert(new CConnection(s.release(),NAME));
  455. }
  456. gh.run(true);
  457. }
  458. static void handleCommandOptions(int argc, char *argv[])
  459. {
  460. namespace po = boost::program_options;
  461. po::options_description opts("Allowed options");
  462. opts.add_options()
  463. ("help,h", "display help and exit")
  464. ("version,v", "display version information and exit")
  465. ("run-by-client", "indicate that server launched by client on same machine")
  466. ("uuid", po::value<std::string>(), "")
  467. ("enable-shm-uuid", "use UUID for shared memory identifier")
  468. ("enable-shm", "enable usage of shared memory")
  469. ("port", po::value<ui16>(), "port at which server will listen to connections from client");
  470. if(argc > 1)
  471. {
  472. try
  473. {
  474. po::store(po::parse_command_line(argc, argv, opts), cmdLineOptions);
  475. }
  476. catch(std::exception &e)
  477. {
  478. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  479. }
  480. }
  481. po::notify(cmdLineOptions);
  482. if (cmdLineOptions.count("help"))
  483. {
  484. auto time = std::time(0);
  485. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  486. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  487. printf("This is free software; see the source for copying conditions. There is NO\n");
  488. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  489. printf("\n");
  490. std::cout << opts;
  491. exit(0);
  492. }
  493. if (cmdLineOptions.count("version"))
  494. {
  495. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  496. std::cout << VCMIDirs::get().genHelpString();
  497. exit(0);
  498. }
  499. }
  500. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  501. void handleLinuxSignal(int sig)
  502. {
  503. const int STACKTRACE_SIZE = 100;
  504. void * buffer[STACKTRACE_SIZE];
  505. int ptrCount = backtrace(buffer, STACKTRACE_SIZE);
  506. char ** strings;
  507. logGlobal->error("Error: signal %d :", sig);
  508. strings = backtrace_symbols(buffer, ptrCount);
  509. if(strings == nullptr)
  510. {
  511. logGlobal->error("There are no symbols.");
  512. }
  513. else
  514. {
  515. for(int i = 0; i < ptrCount; ++i)
  516. {
  517. logGlobal->error(strings[i]);
  518. }
  519. free(strings);
  520. }
  521. _exit(EXIT_FAILURE);
  522. }
  523. #endif
  524. int main(int argc, char * argv[])
  525. {
  526. #ifndef VCMI_ANDROID
  527. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  528. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  529. #endif
  530. // Installs a sig sev segmentation violation handler
  531. // to log stacktrace
  532. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  533. signal(SIGSEGV, handleLinuxSignal);
  534. #endif
  535. console = new CConsoleHandler();
  536. CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() / "VCMI_Server_log.txt", console);
  537. logConfig.configureDefault();
  538. logGlobal->info(NAME);
  539. handleCommandOptions(argc, argv);
  540. preinitDLL(console);
  541. settings.init();
  542. logConfig.configure();
  543. loadDLLClasses();
  544. srand ( (ui32)time(nullptr) );
  545. try
  546. {
  547. boost::asio::io_service io_service;
  548. CVCMIServer server;
  549. try
  550. {
  551. while(!serverShuttingDown)
  552. {
  553. server.start();
  554. }
  555. io_service.run();
  556. }
  557. catch (boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  558. {
  559. logNetwork->error(e.what());
  560. serverShuttingDown = true;
  561. }
  562. catch (...)
  563. {
  564. handleException();
  565. }
  566. }
  567. catch(boost::system::system_error &e)
  568. {
  569. logNetwork->error(e.what());
  570. //catch any startup errors (e.g. can't access port) errors
  571. //and return non-zero status so client can detect error
  572. throw;
  573. }
  574. #ifdef VCMI_ANDROID
  575. CAndroidVMHelper envHelper;
  576. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "killServer");
  577. #endif
  578. vstd::clear_pointer(VLC);
  579. CResourceHandler::clear();
  580. return 0;
  581. }
  582. #ifdef VCMI_ANDROID
  583. void CVCMIServer::create()
  584. {
  585. const char * foo[1] = {"android-server"};
  586. main(1, const_cast<char **>(foo));
  587. }
  588. #endif