CVCMIServer.cpp 13 KB

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