CVCMIServer.cpp 16 KB

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