CVCMIServer.cpp 15 KB

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