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/serializer/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. #include "../lib/rmg/CMapGenOptions.h"
  20. #ifdef VCMI_ANDROID
  21. #include "lib/CAndroidVMHelper.h"
  22. #else
  23. #include "../lib/Interprocess.h"
  24. #endif
  25. #include "../lib/VCMI_Lib.h"
  26. #include "../lib/VCMIDirs.h"
  27. #include "CGameHandler.h"
  28. #include "../lib/mapping/CMapInfo.h"
  29. #include "../lib/GameConstants.h"
  30. #include "../lib/logging/CBasicLogConfigurator.h"
  31. #include "../lib/CConfigHandler.h"
  32. #include "../lib/ScopeGuard.h"
  33. #include "../lib/UnlockGuard.h"
  34. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  35. #include <execinfo.h>
  36. #endif
  37. std::string NAME_AFFIX = "server";
  38. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  39. #ifndef VCMI_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(boost::asio::ip::tcp::acceptor *ac, boost::asio::ip::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_ptr_cast<QuitMenuWithoutStarting>(cpfs),
  76. startingGame = dynamic_ptr_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->error("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->info("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->info("Thread handling connections ended");
  152. if(state == ENDING_AND_STARTING_GAME)
  153. {
  154. logNetwork->info("Waiting for listening thread to finish...");
  155. while(listeningThreads) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  156. logNetwork->info("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->info("Something wrong during accepting: %s", ec.message());
  173. return;
  174. }
  175. logNetwork->info("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->info("%s says: %s", playerName, 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_ptr_cast<QuitMenuWithoutStarting>(&pack))
  217. {
  218. pc->sendStop = true;
  219. }
  220. else if(dynamic_ptr_cast<StartWithCurrentSettings>(&pack))
  221. {
  222. pc->sendStop = true;
  223. }
  224. }
  225. void CPregameServer::processPack(CPackForSelectionScreen * pack)
  226. {
  227. if(dynamic_ptr_cast<CPregamePackToHost>(pack))
  228. {
  229. sendPack(host, *pack);
  230. }
  231. else if(SelectMap *sm = dynamic_ptr_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_ptr_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_ptr_cast<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->info("Pregame connection with player %s established!", c->name);
  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, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))), firstConnection(nullptr)
  268. {
  269. logNetwork->trace("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 VCMI_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->info("Listening for connections at port %d", acceptor->local_endpoint().port());
  351. auto s = new boost::asio::ip::tcp::socket(acceptor->get_io_service());
  352. boost::thread acc(std::bind(vaccept,acceptor,s,&error));
  353. #ifndef VCMI_ANDROID
  354. sr->setToTrueAndNotify();
  355. delete mr;
  356. #else
  357. { // in block to clean-up vm helper after use, because we don't need to keep this thread attached to vm
  358. CAndroidVMHelper envHelper;
  359. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "onServerReady");
  360. logNetwork->info("Sending server ready message to client");
  361. }
  362. #endif
  363. acc.join();
  364. if (error)
  365. {
  366. logNetwork->warnStream() << "Got connection but there is an error " << error;
  367. return;
  368. }
  369. logNetwork->info("We've accepted someone... ");
  370. firstConnection = new CConnection(s, NAME);
  371. logNetwork->info("Got connection!");
  372. while (!end2)
  373. {
  374. ui8 mode;
  375. *firstConnection >> mode;
  376. switch (mode)
  377. {
  378. case 0:
  379. firstConnection->close();
  380. exit(0);
  381. case 1:
  382. firstConnection->close();
  383. return;
  384. case 2:
  385. newGame();
  386. break;
  387. case 3:
  388. loadGame();
  389. break;
  390. case 4:
  391. newPregame();
  392. break;
  393. }
  394. }
  395. }
  396. void CVCMIServer::loadGame()
  397. {
  398. CConnection &c = *firstConnection;
  399. std::string fname;
  400. CGameHandler gh;
  401. boost::system::error_code error;
  402. ui8 clients;
  403. c >> clients >> fname; //how many clients should be connected
  404. {
  405. CLoadFile lf(*CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  406. gh.loadCommonState(lf);
  407. lf >> gh;
  408. }
  409. c << ui8(0);
  410. gh.conns.insert(firstConnection);
  411. for(int i=1; i<clients; i++)
  412. {
  413. auto s = make_unique<boost::asio::ip::tcp::socket>(acceptor->get_io_service());
  414. acceptor->accept(*s,error);
  415. if(error) //retry
  416. {
  417. logNetwork->warn("Cannot establish connection - retrying...");
  418. i--;
  419. continue;
  420. }
  421. gh.conns.insert(new CConnection(s.release(),NAME));
  422. }
  423. gh.run(true);
  424. }
  425. static void handleCommandOptions(int argc, char *argv[])
  426. {
  427. namespace po = boost::program_options;
  428. po::options_description opts("Allowed options");
  429. opts.add_options()
  430. ("help,h", "display help and exit")
  431. ("version,v", "display version information and exit")
  432. ("port", po::value<int>()->default_value(3030), "port at which server will listen to connections from client")
  433. ("resultsFile", po::value<std::string>()->default_value("./results.txt"), "file to which the battle result will be appended. Used only in the DUEL mode.");
  434. if(argc > 1)
  435. {
  436. try
  437. {
  438. po::store(po::parse_command_line(argc, argv, opts), cmdLineOptions);
  439. }
  440. catch(std::exception &e)
  441. {
  442. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  443. }
  444. }
  445. po::notify(cmdLineOptions);
  446. if (cmdLineOptions.count("help"))
  447. {
  448. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  449. printf("Copyright (C) 2007-2014 VCMI dev team - see AUTHORS file\n");
  450. printf("This is free software; see the source for copying conditions. There is NO\n");
  451. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  452. printf("\n");
  453. printf("Usage:\n");
  454. std::cout << opts;
  455. exit(0);
  456. }
  457. if (cmdLineOptions.count("version"))
  458. {
  459. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  460. std::cout << VCMIDirs::get().genHelpString();
  461. exit(0);
  462. }
  463. }
  464. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  465. void handleLinuxSignal(int sig)
  466. {
  467. const int STACKTRACE_SIZE = 100;
  468. void * buffer[STACKTRACE_SIZE];
  469. int ptrCount = backtrace(buffer, STACKTRACE_SIZE);
  470. char ** strings;
  471. logGlobal->error("Error: signal %d :", sig);
  472. strings = backtrace_symbols(buffer, ptrCount);
  473. if(strings == nullptr)
  474. {
  475. logGlobal->error("There are no symbols.");
  476. }
  477. else
  478. {
  479. for(int i = 0; i < ptrCount; ++i)
  480. {
  481. logGlobal->error(strings[i]);
  482. }
  483. free(strings);
  484. }
  485. _exit(EXIT_FAILURE);
  486. }
  487. #endif
  488. int main(int argc, char** argv)
  489. {
  490. // Installs a sig sev segmentation violation handler
  491. // to log stacktrace
  492. #if defined(__GNUC__) && !defined (__MINGW32__) && !defined(VCMI_ANDROID)
  493. signal(SIGSEGV, handleLinuxSignal);
  494. #endif
  495. console = new CConsoleHandler;
  496. CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() / "VCMI_Server_log.txt", console);
  497. logConfig.configureDefault();
  498. logGlobal->info(NAME);
  499. handleCommandOptions(argc, argv);
  500. if (cmdLineOptions.count("port"))
  501. port = cmdLineOptions["port"].as<int>();
  502. logNetwork->info("Port %d will be used.", port);
  503. preinitDLL(console);
  504. settings.init();
  505. logConfig.configure();
  506. loadDLLClasses();
  507. srand ( (ui32)time(nullptr) );
  508. try
  509. {
  510. boost::asio::io_service io_service;
  511. CVCMIServer server;
  512. try
  513. {
  514. while (!end2)
  515. {
  516. server.start();
  517. }
  518. io_service.run();
  519. }
  520. catch (boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  521. {
  522. logNetwork->error(e.what());
  523. end2 = true;
  524. }
  525. catch (...)
  526. {
  527. handleException();
  528. }
  529. }
  530. catch(boost::system::system_error &e)
  531. {
  532. logNetwork->error(e.what());
  533. //catch any startup errors (e.g. can't access port) errors
  534. //and return non-zero status so client can detect error
  535. throw;
  536. }
  537. #ifdef VCMI_ANDROID
  538. CAndroidVMHelper envHelper;
  539. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "killServer");
  540. #endif
  541. delete VLC;
  542. VLC = nullptr;
  543. CResourceHandler::clear();
  544. return 0;
  545. }
  546. #ifdef VCMI_ANDROID
  547. void CVCMIServer::create()
  548. {
  549. const char * foo[1] = {"android-server"};
  550. main(1, const_cast<char **>(foo));
  551. }
  552. #endif