CVCMIServer.cpp 17 KB

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