CVCMIServer.cpp 16 KB

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