CVCMIServer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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->infoStream() << "Got package to announce " << typeid(*cpfs).name() << " from " << *cpc;
  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->errorStream() << *cpc << " dies... \nWhat happened: " << 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->infoStream() << "Thread listening for " << *cpc << " ended";
  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->infoStream() << "\tSending pack of type " << typeid(pack).name() << " to " << *pc;
  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. CGameHandler * CVCMIServer::initGhFromHostingConnection(CConnection &c)
  306. {
  307. auto gh = new 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. return nullptr;
  318. }
  319. }
  320. c << ui8(0); //OK!
  321. gh->init(&si);
  322. gh->conns.insert(&c);
  323. return gh;
  324. }
  325. void CVCMIServer::newGame()
  326. {
  327. CConnection &c = *firstConnection;
  328. ui8 clients;
  329. c >> clients; //how many clients should be connected
  330. assert(clients == 1); //multi goes now by newPregame, TODO: custom lobbies
  331. CGameHandler *gh = initGhFromHostingConnection(c);
  332. auto onExit = vstd::makeScopeGuard([&]()
  333. {
  334. vstd::clear_pointer(gh);
  335. });
  336. gh->run(false);
  337. }
  338. void CVCMIServer::newPregame()
  339. {
  340. auto cps = new CPregameServer(firstConnection, acceptor);
  341. cps->run();
  342. if(cps->state == CPregameServer::ENDING_WITHOUT_START)
  343. {
  344. delete cps;
  345. return;
  346. }
  347. if(cps->state == CPregameServer::ENDING_AND_STARTING_GAME)
  348. {
  349. CGameHandler gh;
  350. gh.conns = cps->connections;
  351. gh.init(cps->curStartInfo);
  352. for(CConnection *c : gh.conns)
  353. c->addStdVecItems(gh.gs);
  354. gh.run(false);
  355. }
  356. }
  357. void CVCMIServer::start()
  358. {
  359. #ifndef VCMI_ANDROID
  360. if(cmdLineOptions.count("enable-shm"))
  361. {
  362. std::string sharedMemoryName = "vcmi_memory";
  363. if(cmdLineOptions.count("enable-shm-uuid") && cmdLineOptions.count("uuid"))
  364. {
  365. sharedMemoryName += "_" + cmdLineOptions["uuid"].as<std::string>();
  366. }
  367. shared = new SharedMemory(sharedMemoryName);
  368. }
  369. #endif
  370. boost::system::error_code error;
  371. for (;;)
  372. {
  373. try
  374. {
  375. auto s = new boost::asio::ip::tcp::socket(acceptor->get_io_service());
  376. boost::thread acc(std::bind(vaccept,acceptor,s,&error));
  377. #ifdef VCMI_ANDROID
  378. { // in block to clean-up vm helper after use, because we don't need to keep this thread attached to vm
  379. CAndroidVMHelper envHelper;
  380. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "onServerReady");
  381. logNetwork->info("Sending server ready message to client");
  382. }
  383. #else
  384. if(shared)
  385. {
  386. shared->sr->setToReadyAndNotify(port);
  387. }
  388. #endif
  389. acc.join();
  390. if (error)
  391. {
  392. logNetwork->warnStream()<<"Got connection but there is an error " << error;
  393. return;
  394. }
  395. logNetwork->info("We've accepted someone... ");
  396. std::string name = NAME;
  397. firstConnection = new CConnection(s, name.append(" STATE_WAITING"));
  398. logNetwork->info("Got connection!");
  399. while(!serverShuttingDown)
  400. {
  401. ui8 mode;
  402. *firstConnection >> mode;
  403. switch (mode)
  404. {
  405. case 0:
  406. firstConnection->close();
  407. exit(0);
  408. case 1:
  409. firstConnection->close();
  410. return;
  411. case 2:
  412. newGame();
  413. break;
  414. case 3:
  415. loadGame();
  416. break;
  417. case 4:
  418. newPregame();
  419. break;
  420. }
  421. }
  422. break;
  423. }
  424. catch(std::exception& e)
  425. {
  426. vstd::clear_pointer(firstConnection);
  427. logNetwork->info("I guess it was just my imagination!");
  428. }
  429. }
  430. }
  431. void CVCMIServer::loadGame()
  432. {
  433. CConnection &c = *firstConnection;
  434. std::string fname;
  435. CGameHandler gh;
  436. boost::system::error_code error;
  437. ui8 clients;
  438. c >> clients >> fname; //how many clients should be connected
  439. {
  440. CLoadFile lf(*CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  441. gh.loadCommonState(lf);
  442. lf >> gh;
  443. }
  444. c << ui8(0);
  445. gh.conns.insert(firstConnection);
  446. for(int i=1; i<clients; i++)
  447. {
  448. auto s = make_unique<boost::asio::ip::tcp::socket>(acceptor->get_io_service());
  449. acceptor->accept(*s,error);
  450. if(error) //retry
  451. {
  452. logNetwork->warn("Cannot establish connection - retrying...");
  453. i--;
  454. continue;
  455. }
  456. gh.conns.insert(new CConnection(s.release(),NAME));
  457. }
  458. gh.run(true);
  459. }
  460. static void handleCommandOptions(int argc, char *argv[])
  461. {
  462. namespace po = boost::program_options;
  463. po::options_description opts("Allowed options");
  464. opts.add_options()
  465. ("help,h", "display help and exit")
  466. ("version,v", "display version information and exit")
  467. ("run-by-client", "indicate that server launched by client on same machine")
  468. ("uuid", po::value<std::string>(), "")
  469. ("enable-shm-uuid", "use UUID for shared memory identifier")
  470. ("enable-shm", "enable usage of shared memory")
  471. ("port", po::value<ui16>(), "port at which server will listen to connections from client");
  472. if(argc > 1)
  473. {
  474. try
  475. {
  476. po::store(po::parse_command_line(argc, argv, opts), cmdLineOptions);
  477. }
  478. catch(std::exception &e)
  479. {
  480. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  481. }
  482. }
  483. po::notify(cmdLineOptions);
  484. if (cmdLineOptions.count("help"))
  485. {
  486. auto time = std::time(0);
  487. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  488. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  489. printf("This is free software; see the source for copying conditions. There is NO\n");
  490. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  491. printf("\n");
  492. std::cout << opts;
  493. exit(0);
  494. }
  495. if (cmdLineOptions.count("version"))
  496. {
  497. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  498. std::cout << VCMIDirs::get().genHelpString();
  499. exit(0);
  500. }
  501. }
  502. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  503. void handleLinuxSignal(int sig)
  504. {
  505. const int STACKTRACE_SIZE = 100;
  506. void * buffer[STACKTRACE_SIZE];
  507. int ptrCount = backtrace(buffer, STACKTRACE_SIZE);
  508. char ** strings;
  509. logGlobal->error("Error: signal %d :", sig);
  510. strings = backtrace_symbols(buffer, ptrCount);
  511. if(strings == nullptr)
  512. {
  513. logGlobal->error("There are no symbols.");
  514. }
  515. else
  516. {
  517. for(int i = 0; i < ptrCount; ++i)
  518. {
  519. logGlobal->error(strings[i]);
  520. }
  521. free(strings);
  522. }
  523. _exit(EXIT_FAILURE);
  524. }
  525. #endif
  526. int main(int argc, char** argv)
  527. {
  528. // Installs a sig sev segmentation violation handler
  529. // to log stacktrace
  530. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  531. signal(SIGSEGV, handleLinuxSignal);
  532. #endif
  533. console = new CConsoleHandler();
  534. CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() / "VCMI_Server_log.txt", console);
  535. logConfig.configureDefault();
  536. logGlobal->info(NAME);
  537. handleCommandOptions(argc, argv);
  538. preinitDLL(console);
  539. settings.init();
  540. logConfig.configure();
  541. loadDLLClasses();
  542. srand ( (ui32)time(nullptr) );
  543. try
  544. {
  545. boost::asio::io_service io_service;
  546. CVCMIServer server;
  547. try
  548. {
  549. while(!serverShuttingDown)
  550. {
  551. server.start();
  552. }
  553. io_service.run();
  554. }
  555. catch (boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  556. {
  557. logNetwork->error(e.what());
  558. serverShuttingDown = true;
  559. }
  560. catch (...)
  561. {
  562. handleException();
  563. }
  564. }
  565. catch(boost::system::system_error &e)
  566. {
  567. logNetwork->error(e.what());
  568. //catch any startup errors (e.g. can't access port) errors
  569. //and return non-zero status so client can detect error
  570. throw;
  571. }
  572. #ifdef VCMI_ANDROID
  573. CAndroidVMHelper envHelper;
  574. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "killServer");
  575. #endif
  576. vstd::clear_pointer(VLC);
  577. CResourceHandler::clear();
  578. return 0;
  579. }
  580. #ifdef VCMI_ANDROID
  581. void CVCMIServer::create()
  582. {
  583. const char * foo[1] = {"android-server"};
  584. main(1, const_cast<char **>(foo));
  585. }
  586. #endif