CVCMIServer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. c.addStdVecItems(gh->gs);
  290. gh->conns.insert(&c);
  291. return gh;
  292. }
  293. void CVCMIServer::newGame()
  294. {
  295. CConnection &c = *firstConnection;
  296. ui8 clients;
  297. c >> clients; //how many clients should be connected
  298. assert(clients == 1); //multi goes now by newPregame, TODO: custom lobbies
  299. CGameHandler *gh = initGhFromHostingConnection(c);
  300. gh->run(false);
  301. delNull(gh);
  302. }
  303. void CVCMIServer::newPregame()
  304. {
  305. CPregameServer *cps = new CPregameServer(firstConnection, acceptor);
  306. cps->run();
  307. if(cps->state == CPregameServer::ENDING_WITHOUT_START)
  308. {
  309. delete cps;
  310. return;
  311. }
  312. if(cps->state == CPregameServer::ENDING_AND_STARTING_GAME)
  313. {
  314. CGameHandler gh;
  315. gh.conns = cps->connections;
  316. gh.init(cps->curStartInfo,std::clock());
  317. BOOST_FOREACH(CConnection *c, gh.conns)
  318. c->addStdVecItems(gh.gs);
  319. gh.run(false);
  320. }
  321. }
  322. void CVCMIServer::start()
  323. {
  324. ServerReady *sr = NULL;
  325. intpr::mapped_region *mr;
  326. try
  327. {
  328. intpr::shared_memory_object smo(intpr::open_only,"vcmi_memory",intpr::read_write);
  329. smo.truncate(sizeof(ServerReady));
  330. mr = new intpr::mapped_region(smo,intpr::read_write);
  331. sr = reinterpret_cast<ServerReady*>(mr->get_address());
  332. }
  333. catch(...)
  334. {
  335. intpr::shared_memory_object smo(intpr::create_only,"vcmi_memory",intpr::read_write);
  336. smo.truncate(sizeof(ServerReady));
  337. mr = new intpr::mapped_region(smo,intpr::read_write);
  338. sr = new(mr->get_address())ServerReady();
  339. }
  340. boost::system::error_code error;
  341. tlog0<<"Listening for connections at port " << acceptor->local_endpoint().port() << std::endl;
  342. tcp::socket * s = new tcp::socket(acceptor->get_io_service());
  343. boost::thread acc(boost::bind(vaccept,acceptor,s,&error));
  344. sr->setToTrueAndNotify();
  345. delete mr;
  346. acc.join();
  347. if (error)
  348. {
  349. tlog2<<"Got connection but there is an error " << std::endl << error;
  350. return;
  351. }
  352. tlog0<<"We've accepted someone... " << std::endl;
  353. firstConnection = new CConnection(s,NAME);
  354. tlog0<<"Got connection!" << std::endl;
  355. while(!end2)
  356. {
  357. ui8 mode;
  358. *firstConnection >> mode;
  359. switch (mode)
  360. {
  361. case 0:
  362. firstConnection->close();
  363. exit(0);
  364. break;
  365. case 1:
  366. firstConnection->close();
  367. return;
  368. break;
  369. case 2:
  370. newGame();
  371. break;
  372. case 3:
  373. loadGame();
  374. break;
  375. case 4:
  376. newPregame();
  377. break;
  378. }
  379. }
  380. }
  381. void CVCMIServer::loadGame()
  382. {
  383. CConnection &c = *firstConnection;
  384. std::string fname;
  385. CGameHandler gh;
  386. boost::system::error_code error;
  387. ui8 clients;
  388. c >> clients >> fname; //how many clients should be connected - TODO: support more than one
  389. {
  390. char sig[8];
  391. CMapHeader dum;
  392. StartInfo *si;
  393. CLoadFile lf(fname + ".vlgm1");
  394. lf >> sig >> dum >> si;
  395. tlog0 <<"Reading save signature"<<std::endl;
  396. lf >> *VLC;
  397. tlog0 <<"Reading handlers"<<std::endl;
  398. lf >> (gh.gs);
  399. c.addStdVecItems(gh.gs);
  400. tlog0 <<"Reading gamestate"<<std::endl;
  401. }
  402. {
  403. CLoadFile lf(fname + ".vsgm1");
  404. lf >> gh;
  405. }
  406. c << ui8(0);
  407. CConnection* cc; //tcp::socket * ss;
  408. for(int i=0; i<clients; i++)
  409. {
  410. if(!i)
  411. {
  412. cc = &c;
  413. }
  414. else
  415. {
  416. tcp::socket * s = new tcp::socket(acceptor->get_io_service());
  417. acceptor->accept(*s,error);
  418. if(error) //retry
  419. {
  420. tlog3<<"Cannot establish connection - retrying..." << std::endl;
  421. i--;
  422. continue;
  423. }
  424. cc = new CConnection(s,NAME);
  425. cc->addStdVecItems(gh.gs);
  426. }
  427. gh.conns.insert(cc);
  428. }
  429. gh.run(true);
  430. }
  431. void CVCMIServer::startDuel(const std::string &battle, const std::string &leftAI, const std::string &rightAI)
  432. {
  433. //we need three connections
  434. boost::thread* threads[3] = {0};
  435. CConnection *conns[3] = {0};
  436. for (int i = 0; i < 3 ; i++)
  437. {
  438. boost::system::error_code error;
  439. tlog0<<"Listening for connections at port " << acceptor->local_endpoint().port() << std::endl;
  440. tcp::socket * s = new tcp::socket(acceptor->get_io_service());
  441. acceptor->accept(*s, error);
  442. if (error)
  443. {
  444. tlog2<<"Got connection but there is an error " << std::endl << error;
  445. i--;
  446. delNull(s);
  447. }
  448. else
  449. {
  450. tlog0<<"We've accepted someone... " << std::endl;
  451. conns[i] = new CConnection(s, NAME);
  452. tlog0<<"Got connection!" << std::endl;
  453. }
  454. }
  455. StartInfo si;
  456. si.mode = StartInfo::DUEL;
  457. si.mapname = battle;
  458. tlog0 << "Preparing gh!\n";
  459. CGameHandler *gh = new CGameHandler();
  460. gh->init(&si,std::time(NULL));
  461. BOOST_FOREACH(CConnection *c, conns)
  462. {
  463. ui8 player = gh->conns.size();
  464. tlog0 << boost::format("Preparing connection %d!\n") % (int)player;
  465. c->addStdVecItems(gh->gs, VLC);
  466. gh->connections[player] = c;
  467. gh->conns.insert(c);
  468. gh->states.addPlayer(player);
  469. *c << si;
  470. std::set<int> pom;
  471. pom.insert(player);
  472. threads[player] = new boost::thread(boost::bind(&CGameHandler::handleConnection, gh, pom, boost::ref(*c)));
  473. }
  474. tlog0 << boost::format("Sending start info to connections!\n");
  475. *gh->connections[0] << leftAI << ui8(0);
  476. *gh->connections[1] << rightAI << ui8(1);
  477. *gh->connections[2] << std::string() << ui8(254);
  478. tlog0 << "Starting battle!\n";
  479. gh->runBattle();
  480. tlog0 << "Battle over!\n";
  481. delNull(gh);
  482. tlog0 << "Removed gh!\n";
  483. tlog0 << "Waiting for connections to close\n";
  484. BOOST_FOREACH(boost::thread *t, threads)
  485. {
  486. t->join();
  487. delNull(t);
  488. }
  489. tlog0 << "Dying...\n";
  490. exit(0);
  491. }
  492. #ifndef __GNUC__
  493. int _tmain(int argc, _TCHAR* argv[])
  494. #else
  495. int main(int argc, char** argv)
  496. #endif
  497. {
  498. logfile = new std::ofstream("VCMI_Server_log.txt");
  499. console = new CConsoleHandler;
  500. //boost::thread t(boost::bind(&CConsoleHandler::run,::console));
  501. initDLL(console,logfile);
  502. srand ( (unsigned int)time(NULL) );
  503. try
  504. {
  505. io_service io_service;
  506. CVCMIServer server;
  507. if(argc == 4)
  508. server.startDuel(argv[1], argv[2], argv[3]);
  509. else
  510. server.startDuel("b1.json", "StupidAI", "StupidAI");
  511. while(!end2)
  512. {
  513. server.start();
  514. }
  515. io_service.run();
  516. }
  517. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  518. {
  519. tlog1 << e.what() << std::endl;
  520. end2 = true;
  521. }HANDLE_EXCEPTION
  522. return 0;
  523. }