2
0

CVCMIServer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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->error("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->info("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->info("Thread handling connections ended");
  149. if(state == ENDING_AND_STARTING_GAME)
  150. {
  151. logNetwork->info("Waiting for listening thread to finish...");
  152. while(listeningThreads) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  153. logNetwork->info("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->info("Something wrong during accepting: %s", ec.message());
  170. return;
  171. }
  172. logNetwork->info("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->info("%s says: %s", playerName, 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->info("Pregame connection with player %s established!", c->name);
  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->trace("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->info("Listening for connections at port %d", 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->info("We've accepted someone... ");
  361. firstConnection = new CConnection(s,NAME);
  362. logNetwork->info("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. CLoadFile lf(*CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME)), minSupportedVersion);
  397. gh.loadCommonState(lf);
  398. lf >> gh;
  399. }
  400. c << ui8(0);
  401. CConnection* cc; //tcp::socket * ss;
  402. for(int i=0; i<clients; i++)
  403. {
  404. if(!i)
  405. {
  406. cc = &c;
  407. }
  408. else
  409. {
  410. auto s = new boost::asio::ip::tcp::socket(acceptor->get_io_service());
  411. acceptor->accept(*s,error);
  412. if(error) //retry
  413. {
  414. logNetwork->warn("Cannot establish connection - retrying...");
  415. i--;
  416. continue;
  417. }
  418. cc = new CConnection(s,NAME);
  419. }
  420. gh.conns.insert(cc);
  421. }
  422. gh.run(true);
  423. }
  424. static void handleCommandOptions(int argc, char *argv[])
  425. {
  426. namespace po = boost::program_options;
  427. po::options_description opts("Allowed options");
  428. opts.add_options()
  429. ("help,h", "display help and exit")
  430. ("version,v", "display version information and exit")
  431. ("port", po::value<int>()->default_value(3030), "port at which server will listen to connections from client")
  432. ("resultsFile", po::value<std::string>()->default_value("./results.txt"), "file to which the battle result will be appended. Used only in the DUEL mode.");
  433. if(argc > 1)
  434. {
  435. try
  436. {
  437. po::store(po::parse_command_line(argc, argv, opts), cmdLineOptions);
  438. }
  439. catch(std::exception &e)
  440. {
  441. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  442. }
  443. }
  444. po::notify(cmdLineOptions);
  445. if (cmdLineOptions.count("help"))
  446. {
  447. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  448. printf("Copyright (C) 2007-2014 VCMI dev team - see AUTHORS file\n");
  449. printf("This is free software; see the source for copying conditions. There is NO\n");
  450. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  451. printf("\n");
  452. printf("Usage:\n");
  453. std::cout << opts;
  454. exit(0);
  455. }
  456. if (cmdLineOptions.count("version"))
  457. {
  458. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  459. std::cout << VCMIDirs::get().genHelpString();
  460. exit(0);
  461. }
  462. }
  463. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  464. void handleLinuxSignal(int sig)
  465. {
  466. const int STACKTRACE_SIZE = 100;
  467. void * buffer[STACKTRACE_SIZE];
  468. int ptrCount = backtrace(buffer, STACKTRACE_SIZE);
  469. char ** strings;
  470. logGlobal->error("Error: signal %d :", sig);
  471. strings = backtrace_symbols(buffer, ptrCount);
  472. if(strings == nullptr)
  473. {
  474. logGlobal->error("There are no symbols.");
  475. }
  476. else
  477. {
  478. for(int i = 0; i < ptrCount; ++i)
  479. {
  480. logGlobal->error(strings[i]);
  481. }
  482. free(strings);
  483. }
  484. _exit(EXIT_FAILURE);
  485. }
  486. #endif
  487. int main(int argc, char** argv)
  488. {
  489. // Installs a sig sev segmentation violation handler
  490. // to log stacktrace
  491. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  492. signal(SIGSEGV, handleLinuxSignal);
  493. #endif
  494. console = new CConsoleHandler;
  495. CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() / "VCMI_Server_log.txt", console);
  496. logConfig.configureDefault();
  497. handleCommandOptions(argc, argv);
  498. if(cmdLineOptions.count("port"))
  499. port = cmdLineOptions["port"].as<int>();
  500. logNetwork->info("Port %d will be used.", port);
  501. preinitDLL(console);
  502. settings.init();
  503. logConfig.configure();
  504. loadDLLClasses();
  505. srand ( (ui32)time(nullptr) );
  506. try
  507. {
  508. boost::asio::io_service io_service;
  509. CVCMIServer server;
  510. try
  511. {
  512. while(!end2)
  513. {
  514. server.start();
  515. }
  516. io_service.run();
  517. }
  518. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  519. {
  520. logNetwork->error(e.what());
  521. end2 = true;
  522. }
  523. catch(...)
  524. {
  525. handleException();
  526. }
  527. }
  528. catch(boost::system::system_error &e)
  529. {
  530. logNetwork->error(e.what());
  531. //catch any startup errors (e.g. can't access port) errors
  532. //and return non-zero status so client can detect error
  533. throw;
  534. }
  535. delete VLC;
  536. VLC = nullptr;
  537. CResourceHandler::clear();
  538. return 0;
  539. }