CVCMIServer.cpp 13 KB

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