CVCMIServer.cpp 13 KB

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