CVCMIServer.cpp 13 KB

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