CVCMIServer.cpp 17 KB

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