CVCMIServer.cpp 14 KB

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