CVCMIServer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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/UnlockGuard.h"
  32. std::string NAME_AFFIX = "server";
  33. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  34. using namespace boost;
  35. using namespace boost::asio;
  36. using namespace boost::asio::ip;
  37. namespace intpr = boost::interprocess;
  38. bool end2 = false;
  39. int port = 3030;
  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 /*= NULL*/)
  54. : host(Host), listeningThreads(0), acceptor(Acceptor), upcomingConnection(NULL),
  55. curmap(NULL), curStartInfo(NULL), 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 = NULL;
  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. PlayerLeft *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. // BOOST_FOREACH(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. BOOST_FOREACH(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 = NULL;
  174. *pc << (ui8)pc->connectionID << curmap;
  175. startListeningThread(pc);
  176. announceTxt(pc->name + " joins the game");
  177. PlayerJoined *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, boost::asio::placeholders::error));
  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. BOOST_FOREACH(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(NULL)
  263. {
  264. logNetwork->debugStream() << "CVCMIServer created!";
  265. }
  266. CVCMIServer::~CVCMIServer()
  267. {
  268. //delete io;
  269. //delete acceptor;
  270. }
  271. CGameHandler * CVCMIServer::initGhFromHostingConnection(CConnection &c)
  272. {
  273. CGameHandler *gh = new CGameHandler();
  274. StartInfo si;
  275. c >> si; //get start options
  276. if(!si.createRandomMap)
  277. {
  278. bool mapFound = CResourceHandler::get()->existsResource(ResourceID(si.mapname, EResType::MAP));
  279. //TODO some checking for campaigns
  280. if(!mapFound && si.mode == StartInfo::NEW_GAME)
  281. {
  282. c << ui8(1); //WRONG!
  283. return nullptr;
  284. }
  285. }
  286. c << ui8(0); //OK!
  287. gh->init(&si);
  288. gh->conns.insert(&c);
  289. return gh;
  290. }
  291. void CVCMIServer::newGame()
  292. {
  293. CConnection &c = *firstConnection;
  294. ui8 clients;
  295. c >> clients; //how many clients should be connected
  296. assert(clients == 1); //multi goes now by newPregame, TODO: custom lobbies
  297. CGameHandler *gh = initGhFromHostingConnection(c);
  298. gh->run(false);
  299. vstd::clear_pointer(gh);
  300. }
  301. void CVCMIServer::newPregame()
  302. {
  303. CPregameServer *cps = new CPregameServer(firstConnection, acceptor);
  304. cps->run();
  305. if(cps->state == CPregameServer::ENDING_WITHOUT_START)
  306. {
  307. delete cps;
  308. return;
  309. }
  310. if(cps->state == CPregameServer::ENDING_AND_STARTING_GAME)
  311. {
  312. CGameHandler gh;
  313. gh.conns = cps->connections;
  314. gh.init(cps->curStartInfo);
  315. BOOST_FOREACH(CConnection *c, gh.conns)
  316. c->addStdVecItems(gh.gs);
  317. gh.run(false);
  318. }
  319. }
  320. void CVCMIServer::start()
  321. {
  322. ServerReady *sr = NULL;
  323. intpr::mapped_region *mr;
  324. try
  325. {
  326. intpr::shared_memory_object smo(intpr::open_only,"vcmi_memory",intpr::read_write);
  327. smo.truncate(sizeof(ServerReady));
  328. mr = new intpr::mapped_region(smo,intpr::read_write);
  329. sr = reinterpret_cast<ServerReady*>(mr->get_address());
  330. }
  331. catch(...)
  332. {
  333. intpr::shared_memory_object smo(intpr::create_only,"vcmi_memory",intpr::read_write);
  334. smo.truncate(sizeof(ServerReady));
  335. mr = new intpr::mapped_region(smo,intpr::read_write);
  336. sr = new(mr->get_address())ServerReady();
  337. }
  338. boost::system::error_code error;
  339. logNetwork->infoStream()<<"Listening for connections at port " << acceptor->local_endpoint().port();
  340. tcp::socket * s = new tcp::socket(acceptor->get_io_service());
  341. boost::thread acc(boost::bind(vaccept,acceptor,s,&error));
  342. sr->setToTrueAndNotify();
  343. delete mr;
  344. acc.join();
  345. if (error)
  346. {
  347. logNetwork->warnStream()<<"Got connection but there is an error " << error;
  348. return;
  349. }
  350. logNetwork->infoStream()<<"We've accepted someone... ";
  351. firstConnection = new CConnection(s,NAME);
  352. logNetwork->infoStream()<<"Got connection!";
  353. while(!end2)
  354. {
  355. ui8 mode;
  356. *firstConnection >> mode;
  357. switch (mode)
  358. {
  359. case 0:
  360. firstConnection->close();
  361. exit(0);
  362. break;
  363. case 1:
  364. firstConnection->close();
  365. return;
  366. break;
  367. case 2:
  368. newGame();
  369. break;
  370. case 3:
  371. loadGame();
  372. break;
  373. case 4:
  374. newPregame();
  375. break;
  376. }
  377. }
  378. }
  379. void CVCMIServer::loadGame()
  380. {
  381. CConnection &c = *firstConnection;
  382. std::string fname;
  383. CGameHandler gh;
  384. boost::system::error_code error;
  385. ui8 clients;
  386. c >> clients >> fname; //how many clients should be connected - TODO: support more than one
  387. // {
  388. // char sig[8];
  389. // CMapHeader dum;
  390. // StartInfo *si;
  391. //
  392. // CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::LIB_SAVEGAME)));
  393. // lf >> sig >> dum >> si;
  394. // logNetwork->infoStream() <<"Reading save signature";
  395. //
  396. // lf >> *VLC;
  397. // logNetwork->infoStream() <<"Reading handlers";
  398. //
  399. // lf >> (gh.gs);
  400. // c.addStdVecItems(gh.gs);
  401. // logNetwork->infoStream() <<"Reading gamestate";
  402. // }
  403. {
  404. CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME)));
  405. gh.loadCommonState(lf);
  406. lf >> gh;
  407. }
  408. c << ui8(0);
  409. CConnection* cc; //tcp::socket * ss;
  410. for(int i=0; i<clients; i++)
  411. {
  412. if(!i)
  413. {
  414. cc = &c;
  415. }
  416. else
  417. {
  418. tcp::socket * s = new tcp::socket(acceptor->get_io_service());
  419. acceptor->accept(*s,error);
  420. if(error) //retry
  421. {
  422. logNetwork->warnStream()<<"Cannot establish connection - retrying...";
  423. i--;
  424. continue;
  425. }
  426. cc = new CConnection(s,NAME);
  427. cc->addStdVecItems(gh.gs);
  428. }
  429. gh.conns.insert(cc);
  430. }
  431. gh.run(true);
  432. }
  433. #ifndef __GNUC__
  434. int _tmain(int argc, _TCHAR* argv[])
  435. #else
  436. int main(int argc, char** argv)
  437. #endif
  438. {
  439. console = new CConsoleHandler;
  440. CBasicLogConfigurator logConfig(VCMIDirs::get().localPath() + "/VCMI_Server_log.txt", console);
  441. logConfig.configureDefault();
  442. //boost::thread t(boost::bind(&CConsoleHandler::run,::console));
  443. if(argc > 1)
  444. {
  445. #ifdef _MSC_VER
  446. port = _tstoi(argv[1]);
  447. #else
  448. port = _ttoi(argv[1]);
  449. #endif
  450. }
  451. preinitDLL(console);
  452. settings.init();
  453. logConfig.configure();
  454. logNetwork->infoStream() << "Port " << port << " will be used.";
  455. loadDLLClasses();
  456. srand ( (ui32)time(NULL) );
  457. try
  458. {
  459. io_service io_service;
  460. CVCMIServer server;
  461. try
  462. {
  463. while(!end2)
  464. {
  465. server.start();
  466. }
  467. io_service.run();
  468. }
  469. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  470. {
  471. logNetwork->errorStream() << e.what();
  472. end2 = true;
  473. }HANDLE_EXCEPTION
  474. }
  475. catch(boost::system::system_error &e)
  476. {
  477. logNetwork->errorStream() << e.what();
  478. //catch any startup errors (e.g. can't access port) errors
  479. //and return non-zero status so client can detect error
  480. throw;
  481. }
  482. return 0;
  483. }