CVCMIServer.cpp 17 KB

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