CVCMIServer.cpp 13 KB

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