CVCMIServer.cpp 13 KB

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