CVCMIServer.cpp 13 KB

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