CVCMIServer.cpp 13 KB

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