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