CVCMIServer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. #include "StdInc.h"
  2. #include <boost/asio.hpp>
  3. #include <boost/interprocess/mapped_region.hpp>
  4. #include <boost/interprocess/shared_memory_object.hpp>
  5. #include "../lib/filesystem/CResourceLoader.h"
  6. #include "../lib/mapping/CCampaignHandler.h"
  7. #include "../lib/CThreadHelper.h"
  8. #include "../lib/Connection.h"
  9. #include "../lib/CModHandler.h"
  10. #include "../lib/CArtHandler.h"
  11. #include "../lib/CDefObjInfoHandler.h"
  12. #include "../lib/CGeneralTextHandler.h"
  13. #include "../lib/CHeroHandler.h"
  14. #include "../lib/CTownHandler.h"
  15. #include "../lib/CBuildingHandler.h"
  16. #include "../lib/CSpellHandler.h"
  17. #include "../lib/CCreatureHandler.h"
  18. #include "zlib.h"
  19. #include "CVCMIServer.h"
  20. #include "../lib/StartInfo.h"
  21. #include "../lib/mapping/CMap.h"
  22. #include "../lib/Interprocess.h"
  23. #include "../lib/VCMI_Lib.h"
  24. #include "../lib/VCMIDirs.h"
  25. #include "CGameHandler.h"
  26. #include "../lib/mapping/CMapInfo.h"
  27. #include "../lib/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. std::string NAME_AFFIX = "server";
  34. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  35. using namespace boost;
  36. using namespace boost::asio;
  37. using namespace boost::asio::ip;
  38. namespace intpr = boost::interprocess;
  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(tcp::acceptor *ac, tcp::socket *s, boost::system::error_code *error)
  52. {
  53. ac->accept(*s,*error);
  54. }
  55. CPregameServer::CPregameServer(CConnection *Host, TAcceptor *Acceptor /*= NULL*/)
  56. : host(Host), listeningThreads(0), acceptor(Acceptor), upcomingConnection(NULL),
  57. curmap(NULL), curStartInfo(NULL), 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 = NULL;
  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_cast<QuitMenuWithoutStarting*>(cpfs),
  73. startingGame = dynamic_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. PlayerLeft *pl = new PlayerLeft();
  103. pl->playerID = cpc->connectionID;
  104. announceTxt(cpc->name + " left the game");
  105. toAnnounce.push_back(pl);
  106. if(!connections.size())
  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.size())
  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. // BOOST_FOREACH(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. BOOST_FOREACH(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 = NULL;
  176. *pc << (ui8)pc->connectionID << curmap;
  177. startListeningThread(pc);
  178. announceTxt(pc->name + " joins the game");
  179. PlayerJoined *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, boost::bind(&CPregameServer::connectionAccepted, this, boost::asio::placeholders::error));
  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. BOOST_FOREACH(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_cast<const QuitMenuWithoutStarting*>(&pack))
  214. {
  215. pc->sendStop = true;
  216. }
  217. else if(dynamic_cast<const StartWithCurrentSettings*>(&pack))
  218. {
  219. pc->sendStop = true;
  220. }
  221. }
  222. void CPregameServer::processPack(CPackForSelectionScreen * pack)
  223. {
  224. if(dynamic_cast<CPregamePackToHost*>(pack))
  225. {
  226. sendPack(host, *pack);
  227. }
  228. else if(SelectMap *sm = dynamic_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_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_cast<const 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, tcp::endpoint(tcp::v4(), port))), firstConnection(NULL)
  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. CGameHandler *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. CPregameServer *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. BOOST_FOREACH(CConnection *c, gh.conns)
  322. c->addStdVecItems(gh.gs);
  323. gh.run(false);
  324. }
  325. }
  326. void CVCMIServer::start()
  327. {
  328. ServerReady *sr = NULL;
  329. intpr::mapped_region *mr;
  330. try
  331. {
  332. intpr::shared_memory_object smo(intpr::open_only,"vcmi_memory",intpr::read_write);
  333. smo.truncate(sizeof(ServerReady));
  334. mr = new intpr::mapped_region(smo,intpr::read_write);
  335. sr = reinterpret_cast<ServerReady*>(mr->get_address());
  336. }
  337. catch(...)
  338. {
  339. intpr::shared_memory_object smo(intpr::create_only,"vcmi_memory",intpr::read_write);
  340. smo.truncate(sizeof(ServerReady));
  341. mr = new intpr::mapped_region(smo,intpr::read_write);
  342. sr = new(mr->get_address())ServerReady();
  343. }
  344. boost::system::error_code error;
  345. logNetwork->infoStream()<<"Listening for connections at port " << acceptor->local_endpoint().port();
  346. tcp::socket * s = new tcp::socket(acceptor->get_io_service());
  347. boost::thread acc(boost::bind(vaccept,acceptor,s,&error));
  348. sr->setToTrueAndNotify();
  349. delete mr;
  350. acc.join();
  351. if (error)
  352. {
  353. logNetwork->warnStream()<<"Got connection but there is an error " << error;
  354. return;
  355. }
  356. logNetwork->infoStream()<<"We've accepted someone... ";
  357. firstConnection = new CConnection(s,NAME);
  358. logNetwork->infoStream()<<"Got connection!";
  359. while(!end2)
  360. {
  361. ui8 mode;
  362. *firstConnection >> mode;
  363. switch (mode)
  364. {
  365. case 0:
  366. firstConnection->close();
  367. exit(0);
  368. break;
  369. case 1:
  370. firstConnection->close();
  371. return;
  372. break;
  373. case 2:
  374. newGame();
  375. break;
  376. case 3:
  377. loadGame();
  378. break;
  379. case 4:
  380. newPregame();
  381. break;
  382. }
  383. }
  384. }
  385. void CVCMIServer::loadGame()
  386. {
  387. CConnection &c = *firstConnection;
  388. std::string fname;
  389. CGameHandler gh;
  390. boost::system::error_code error;
  391. ui8 clients;
  392. c >> clients >> fname; //how many clients should be connected - TODO: support more than one
  393. // {
  394. // char sig[8];
  395. // CMapHeader dum;
  396. // StartInfo *si;
  397. //
  398. // CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::LIB_SAVEGAME)));
  399. // lf >> sig >> dum >> si;
  400. // logNetwork->infoStream() <<"Reading save signature";
  401. //
  402. // lf >> *VLC;
  403. // logNetwork->infoStream() <<"Reading handlers";
  404. //
  405. // lf >> (gh.gs);
  406. // c.addStdVecItems(gh.gs);
  407. // logNetwork->infoStream() <<"Reading gamestate";
  408. // }
  409. {
  410. CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME)));
  411. gh.loadCommonState(lf);
  412. lf >> gh;
  413. }
  414. c << ui8(0);
  415. CConnection* cc; //tcp::socket * ss;
  416. for(int i=0; i<clients; i++)
  417. {
  418. if(!i)
  419. {
  420. cc = &c;
  421. }
  422. else
  423. {
  424. tcp::socket * s = new tcp::socket(acceptor->get_io_service());
  425. acceptor->accept(*s,error);
  426. if(error) //retry
  427. {
  428. logNetwork->warnStream()<<"Cannot establish connection - retrying...";
  429. i--;
  430. continue;
  431. }
  432. cc = new CConnection(s,NAME);
  433. cc->addStdVecItems(gh.gs);
  434. }
  435. gh.conns.insert(cc);
  436. }
  437. gh.run(true);
  438. }
  439. static void handleCommandOptions(int argc, char *argv[])
  440. {
  441. namespace po = boost::program_options;
  442. po::options_description opts("Allowed options");
  443. opts.add_options()
  444. ("help,h", "display help and exit")
  445. ("version,v", "display version information and exit")
  446. ("port", po::value<int>()->default_value(3030), "port at which server will listen to connections from client")
  447. ("resultsFile", po::value<std::string>()->default_value("./results.txt"), "file to which the battle result will be appended. Used only in the DUEL mode.");
  448. if(argc > 1)
  449. {
  450. try
  451. {
  452. po::store(po::parse_command_line(argc, argv, opts), cmdLineOptions);
  453. }
  454. catch(std::exception &e)
  455. {
  456. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  457. }
  458. }
  459. po::notify(cmdLineOptions);
  460. }
  461. int main(int argc, char** argv)
  462. {
  463. console = new CConsoleHandler;
  464. CBasicLogConfigurator logConfig(VCMIDirs::get().localPath() + "/VCMI_Server_log.txt", console);
  465. logConfig.configureDefault();
  466. preinitDLL(console);
  467. settings.init();
  468. logConfig.configure();
  469. handleCommandOptions(argc, argv);
  470. port = cmdLineOptions["port"].as<int>();
  471. logNetwork->infoStream() << "Port " << port << " will be used.";
  472. loadDLLClasses();
  473. srand ( (ui32)time(NULL) );
  474. try
  475. {
  476. io_service io_service;
  477. CVCMIServer server;
  478. try
  479. {
  480. while(!end2)
  481. {
  482. server.start();
  483. }
  484. io_service.run();
  485. }
  486. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  487. {
  488. logNetwork->errorStream() << e.what();
  489. end2 = true;
  490. }HANDLE_EXCEPTION
  491. }
  492. catch(boost::system::system_error &e)
  493. {
  494. logNetwork->errorStream() << e.what();
  495. //catch any startup errors (e.g. can't access port) errors
  496. //and return non-zero status so client can detect error
  497. throw;
  498. }
  499. //delete VLC; //can't be re-enabled due to access to already freed memory in bonus system
  500. CResourceHandler::clear();
  501. return 0;
  502. }