CVCMIServer.cpp 13 KB

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