CVCMIServer.cpp 16 KB

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