CVCMIServer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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/CDefObjInfoHandler.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. #include "../lib/Interprocess.h"
  21. #include "../lib/VCMI_Lib.h"
  22. #include "../lib/VCMIDirs.h"
  23. #include "CGameHandler.h"
  24. #include "../lib/mapping/CMapInfo.h"
  25. #include "../lib/CObjectHandler.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. #ifdef __GNUC__
  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. namespace intpr = boost::interprocess;
  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(tcp::acceptor *ac, 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_cast<QuitMenuWithoutStarting*>(cpfs),
  74. startingGame = dynamic_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->errorStream() << "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->infoStream() << "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->infoStream() << "Thread handling connections ended";
  150. if(state == ENDING_AND_STARTING_GAME)
  151. {
  152. logNetwork->infoStream() << "Waiting for listening thread to finish...";
  153. while(listeningThreads) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  154. logNetwork->infoStream() << "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->infoStream() << "Something wrong during accepting: " << ec.message();
  171. return;
  172. }
  173. logNetwork->infoStream() << "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, boost::bind(&CPregameServer::connectionAccepted, this, _1));
  192. }
  193. void CPregameServer::announceTxt(const std::string &txt, const std::string &playerName /*= "system"*/)
  194. {
  195. logNetwork->infoStream() << playerName << " says: " << 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_cast<const QuitMenuWithoutStarting*>(&pack))
  215. {
  216. pc->sendStop = true;
  217. }
  218. else if(dynamic_cast<const StartWithCurrentSettings*>(&pack))
  219. {
  220. pc->sendStop = true;
  221. }
  222. }
  223. void CPregameServer::processPack(CPackForSelectionScreen * pack)
  224. {
  225. if(dynamic_cast<CPregamePackToHost*>(pack))
  226. {
  227. sendPack(host, *pack);
  228. }
  229. else if(SelectMap *sm = dynamic_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_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_cast<const 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->infoStream() << "Pregame connection with player " << c->name << " established!";
  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, tcp::endpoint(tcp::v4(), port))), firstConnection(nullptr)
  266. {
  267. logNetwork->debugStream() << "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. ServerReady *sr = nullptr;
  330. intpr::mapped_region *mr;
  331. try
  332. {
  333. intpr::shared_memory_object smo(intpr::open_only,"vcmi_memory",intpr::read_write);
  334. smo.truncate(sizeof(ServerReady));
  335. mr = new intpr::mapped_region(smo,intpr::read_write);
  336. sr = reinterpret_cast<ServerReady*>(mr->get_address());
  337. }
  338. catch(...)
  339. {
  340. intpr::shared_memory_object smo(intpr::create_only,"vcmi_memory",intpr::read_write);
  341. smo.truncate(sizeof(ServerReady));
  342. mr = new intpr::mapped_region(smo,intpr::read_write);
  343. sr = new(mr->get_address())ServerReady();
  344. }
  345. boost::system::error_code error;
  346. logNetwork->infoStream()<<"Listening for connections at port " << acceptor->local_endpoint().port();
  347. auto s = new tcp::socket(acceptor->get_io_service());
  348. boost::thread acc(boost::bind(vaccept,acceptor,s,&error));
  349. sr->setToTrueAndNotify();
  350. delete mr;
  351. acc.join();
  352. if (error)
  353. {
  354. logNetwork->warnStream()<<"Got connection but there is an error " << error;
  355. return;
  356. }
  357. logNetwork->infoStream()<<"We've accepted someone... ";
  358. firstConnection = new CConnection(s,NAME);
  359. logNetwork->infoStream()<<"Got connection!";
  360. while(!end2)
  361. {
  362. ui8 mode;
  363. *firstConnection >> mode;
  364. switch (mode)
  365. {
  366. case 0:
  367. firstConnection->close();
  368. exit(0);
  369. case 1:
  370. firstConnection->close();
  371. return;
  372. case 2:
  373. newGame();
  374. break;
  375. case 3:
  376. loadGame();
  377. break;
  378. case 4:
  379. newPregame();
  380. break;
  381. }
  382. }
  383. }
  384. void CVCMIServer::loadGame()
  385. {
  386. CConnection &c = *firstConnection;
  387. std::string fname;
  388. CGameHandler gh;
  389. boost::system::error_code error;
  390. ui8 clients;
  391. c >> clients >> fname; //how many clients should be connected - TODO: support more than one
  392. // {
  393. // char sig[8];
  394. // CMapHeader dum;
  395. // StartInfo *si;
  396. //
  397. // CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::LIB_SAVEGAME)));
  398. // lf >> sig >> dum >> si;
  399. // logNetwork->infoStream() <<"Reading save signature";
  400. //
  401. // lf >> *VLC;
  402. // logNetwork->infoStream() <<"Reading handlers";
  403. //
  404. // lf >> (gh.gs);
  405. // c.addStdVecItems(gh.gs);
  406. // logNetwork->infoStream() <<"Reading gamestate";
  407. // }
  408. {
  409. CLoadFile lf(*CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME)));
  410. gh.loadCommonState(lf);
  411. lf >> gh;
  412. }
  413. c << ui8(0);
  414. CConnection* cc; //tcp::socket * ss;
  415. for(int i=0; i<clients; i++)
  416. {
  417. if(!i)
  418. {
  419. cc = &c;
  420. }
  421. else
  422. {
  423. auto s = new tcp::socket(acceptor->get_io_service());
  424. acceptor->accept(*s,error);
  425. if(error) //retry
  426. {
  427. logNetwork->warnStream()<<"Cannot establish connection - retrying...";
  428. i--;
  429. continue;
  430. }
  431. cc = new CConnection(s,NAME);
  432. cc->addStdVecItems(gh.gs);
  433. }
  434. gh.conns.insert(cc);
  435. }
  436. gh.run(true);
  437. }
  438. static void handleCommandOptions(int argc, char *argv[])
  439. {
  440. namespace po = boost::program_options;
  441. po::options_description opts("Allowed options");
  442. opts.add_options()
  443. ("help,h", "display help and exit")
  444. ("version,v", "display version information and exit")
  445. ("port", po::value<int>()->default_value(3030), "port at which server will listen to connections from client")
  446. ("resultsFile", po::value<std::string>()->default_value("./results.txt"), "file to which the battle result will be appended. Used only in the DUEL mode.");
  447. if(argc > 1)
  448. {
  449. try
  450. {
  451. po::store(po::parse_command_line(argc, argv, opts), cmdLineOptions);
  452. }
  453. catch(std::exception &e)
  454. {
  455. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  456. }
  457. }
  458. po::notify(cmdLineOptions);
  459. }
  460. #ifdef __GNUC__
  461. void handleLinuxSignal(int sig)
  462. {
  463. const int STACKTRACE_SIZE = 100;
  464. void * buffer[STACKTRACE_SIZE];
  465. int ptrCount = backtrace(buffer, STACKTRACE_SIZE);
  466. char ** strings;
  467. logGlobal->errorStream() << "Error: signal " << sig << ":";
  468. strings = backtrace_symbols(buffer, ptrCount);
  469. if(strings == nullptr)
  470. {
  471. logGlobal->errorStream() << "There are no symbols.";
  472. }
  473. else
  474. {
  475. for(int i = 0; i < ptrCount; ++i)
  476. {
  477. logGlobal->errorStream() << strings[i];
  478. }
  479. free(strings);
  480. }
  481. _exit(EXIT_FAILURE);
  482. }
  483. #endif
  484. int main(int argc, char** argv)
  485. {
  486. // Installs a sig sev segmentation violation handler
  487. // to log stacktrace
  488. #ifdef __GNUC__
  489. signal(SIGSEGV, handleLinuxSignal);
  490. #endif
  491. console = new CConsoleHandler;
  492. CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() + "/VCMI_Server_log.txt", console);
  493. logConfig.configureDefault();
  494. preinitDLL(console);
  495. settings.init();
  496. logConfig.configure();
  497. handleCommandOptions(argc, argv);
  498. port = cmdLineOptions["port"].as<int>();
  499. logNetwork->infoStream() << "Port " << port << " will be used.";
  500. loadDLLClasses();
  501. srand ( (ui32)time(nullptr) );
  502. try
  503. {
  504. io_service io_service;
  505. CVCMIServer server;
  506. try
  507. {
  508. while(!end2)
  509. {
  510. server.start();
  511. }
  512. io_service.run();
  513. }
  514. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  515. {
  516. logNetwork->errorStream() << e.what();
  517. end2 = true;
  518. }
  519. catch(...)
  520. {
  521. handleException();
  522. }
  523. }
  524. catch(boost::system::system_error &e)
  525. {
  526. logNetwork->errorStream() << e.what();
  527. //catch any startup errors (e.g. can't access port) errors
  528. //and return non-zero status so client can detect error
  529. throw;
  530. }
  531. //delete VLC; //can't be re-enabled due to access to already freed memory in bonus system
  532. CResourceHandler::clear();
  533. return 0;
  534. }