CVCMIServer.cpp 15 KB

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