CVCMIServer.cpp 13 KB

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