Connection.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #include "StdInc.h"
  2. #include "Connection.h"
  3. #ifndef _MSC_VER
  4. #include "../lib/RegisterTypes.h"
  5. #endif
  6. //for smart objs serialization over net
  7. #include "../lib/CMapInfo.h"
  8. #include "StartInfo.h"
  9. #include "BattleState.h"
  10. #include "CGameState.h"
  11. #include "map.h"
  12. #include "CObjectHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "VCMI_Lib.h"
  15. #include "CArtHandler.h"
  16. #include "CHeroHandler.h"
  17. #include "CSpellHandler.h"
  18. #include "CTownHandler.h"
  19. #include "CCampaignHandler.h"
  20. #include "NetPacks.h"
  21. #include <boost/asio.hpp>
  22. /*
  23. * Connection.cpp, part of VCMI engine
  24. *
  25. * Authors: listed in file AUTHORS in main folder
  26. *
  27. * License: GNU General Public License v2.0 or later
  28. * Full text of license available in license.txt file, in main folder
  29. *
  30. */
  31. using namespace boost;
  32. using namespace boost::asio::ip;
  33. template<typename Serializer> DLL_LINKAGE void registerTypes(Serializer &s); //defined elsewhere and explicitly instantiated for used serializers
  34. CTypeList typeList;
  35. #define LOG(a) \
  36. if(logging)\
  37. out << a
  38. #if defined(__hppa__) || \
  39. defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \
  40. (defined(__MIPS__) && defined(__MISPEB__)) || \
  41. defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \
  42. defined(__sparc__)
  43. #define BIG_ENDIAN
  44. #else
  45. #define LIL_ENDIAN
  46. #endif
  47. void CConnection::init()
  48. {
  49. CISer<CConnection>::smartPointerSerialization = false;
  50. COSer<CConnection>::smartPointerSerialization = false;
  51. registerTypes(static_cast<CISer<CConnection>&>(*this));
  52. registerTypes(static_cast<COSer<CConnection>&>(*this));
  53. #ifdef LIL_ENDIAN
  54. myEndianess = true;
  55. #else
  56. myEndianess = false;
  57. #endif
  58. connected = true;
  59. std::string pom;
  60. //we got connection
  61. (*this) << std::string("Aiya!\n") << name << myEndianess; //identify ourselves
  62. (*this) >> pom >> pom >> contactEndianess;
  63. tlog0 << "Established connection with "<<pom<<std::endl;
  64. wmx = new boost::mutex;
  65. rmx = new boost::mutex;
  66. handler = NULL;
  67. receivedStop = sendStop = false;
  68. static int cid = 1;
  69. connectionID = cid++;
  70. }
  71. CConnection::CConnection(std::string host, std::string port, std::string Name)
  72. :io_service(new asio::io_service), name(Name)
  73. {
  74. int i;
  75. boost::system::error_code error = asio::error::host_not_found;
  76. socket = new tcp::socket(*io_service);
  77. tcp::resolver resolver(*io_service);
  78. tcp::resolver::iterator end, pom, endpoint_iterator = resolver.resolve(tcp::resolver::query(host,port),error);
  79. if(error)
  80. {
  81. tlog1 << "Problem with resolving: " << std::endl << error <<std::endl;
  82. goto connerror1;
  83. }
  84. pom = endpoint_iterator;
  85. if(pom != end)
  86. tlog0<<"Found endpoints:" << std::endl;
  87. else
  88. {
  89. tlog1 << "Critical problem: No endpoints found!" << std::endl;
  90. goto connerror1;
  91. }
  92. i=0;
  93. while(pom != end)
  94. {
  95. tlog0 << "\t" << i << ": " << (boost::asio::ip::tcp::endpoint&)*pom << std::endl;
  96. pom++;
  97. }
  98. i=0;
  99. while(endpoint_iterator != end)
  100. {
  101. tlog0 << "Trying connection to " << (boost::asio::ip::tcp::endpoint&)*endpoint_iterator << " (" << i++ << ")" << std::endl;
  102. socket->connect(*endpoint_iterator, error);
  103. if(!error)
  104. {
  105. init();
  106. return;
  107. }
  108. else
  109. {
  110. tlog1 << "Problem with connecting: " << std::endl << error << std::endl;
  111. }
  112. endpoint_iterator++;
  113. }
  114. //we shouldn't be here - error handling
  115. connerror1:
  116. tlog1 << "Something went wrong... checking for error info" << std::endl;
  117. if(error)
  118. tlog1 << error <<std::endl;
  119. else
  120. tlog1 << "No error info. " << std::endl;
  121. delete io_service;
  122. //delete socket;
  123. throw std::string("Can't establish connection :(");
  124. }
  125. CConnection::CConnection(TSocket * Socket, std::string Name )
  126. :socket(Socket),io_service(&Socket->get_io_service()), name(Name)//, send(this), rec(this)
  127. {
  128. init();
  129. }
  130. CConnection::CConnection(TAcceptor * acceptor, boost::asio::io_service *Io_service, std::string Name)
  131. : name(Name)//, send(this), rec(this)
  132. {
  133. boost::system::error_code error = asio::error::host_not_found;
  134. socket = new tcp::socket(*io_service);
  135. acceptor->accept(*socket,error);
  136. if (error)
  137. {
  138. tlog1 << "Error on accepting: " << std::endl << error << std::endl;
  139. delete socket;
  140. throw "Can't establish connection :(";
  141. }
  142. init();
  143. }
  144. int CConnection::write(const void * data, unsigned size)
  145. {
  146. //LOG("Sending " << size << " byte(s) of data" <<std::endl);
  147. try
  148. {
  149. int ret;
  150. ret = asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size)));
  151. return ret;
  152. }
  153. catch(...)
  154. {
  155. //connection has been lost
  156. connected = false;
  157. throw;
  158. }
  159. }
  160. int CConnection::read(void * data, unsigned size)
  161. {
  162. //LOG("Receiving " << size << " byte(s) of data" <<std::endl);
  163. try
  164. {
  165. int ret = asio::read(*socket,asio::mutable_buffers_1(asio::mutable_buffer(data,size)));
  166. return ret;
  167. }
  168. catch(...)
  169. {
  170. //connection has been lost
  171. connected = false;
  172. throw;
  173. }
  174. }
  175. CConnection::~CConnection(void)
  176. {
  177. if(handler)
  178. handler->join();
  179. delete handler;
  180. close();
  181. delete io_service;
  182. delete wmx;
  183. delete rmx;
  184. }
  185. template<class T>
  186. CConnection & CConnection::operator&(const T &t) {
  187. throw new std::exception();
  188. //XXX this is temporaly ? solution to fix gcc (4.3.3, other?) compilation
  189. // problem for more details contact [email protected] or [email protected]
  190. // do not remove this exception it shoudnt be called
  191. return *this;
  192. }
  193. void CConnection::close()
  194. {
  195. if(socket)
  196. {
  197. socket->close();
  198. delete socket;
  199. socket = NULL;
  200. }
  201. }
  202. bool CConnection::isOpen() const
  203. {
  204. return socket && connected;
  205. }
  206. void CConnection::reportState(CLogger &out)
  207. {
  208. out << "CConnection\n";
  209. if(socket && socket->is_open())
  210. {
  211. out << "\tWe have an open and valid socket\n";
  212. out << "\t" << socket->available() <<" bytes awaiting\n";
  213. }
  214. }
  215. CPack * CConnection::retreivePack()
  216. {
  217. CPack *ret = NULL;
  218. boost::unique_lock<boost::mutex> lock(*rmx);
  219. tlog5 << "Listening... ";
  220. *this >> ret;
  221. tlog5 << "\treceived server message of type " << typeid(*ret).name() << std::endl;
  222. return ret;
  223. }
  224. void CConnection::sendPackToServer(const CPack &pack, ui8 player)
  225. {
  226. boost::unique_lock<boost::mutex> lock(*wmx);
  227. tlog5 << "Sending to server a pack of type " << typeid(pack).name() << std::endl;
  228. *this << player << &pack; //packs has to be sent as polymorphic pointers!
  229. }
  230. CSaveFile::CSaveFile( const std::string &fname )
  231. :sfile(NULL)
  232. {
  233. registerTypes(*this);
  234. openNextFile(fname);
  235. }
  236. CSaveFile::~CSaveFile()
  237. {
  238. delete sfile;
  239. }
  240. int CSaveFile::write( const void * data, unsigned size )
  241. {
  242. sfile->write((char *)data,size);
  243. return size;
  244. }
  245. void CSaveFile::close()
  246. {
  247. delete sfile;
  248. sfile = NULL;
  249. }
  250. void CSaveFile::openNextFile(const std::string &fname)
  251. {
  252. fName = fname;
  253. close();
  254. sfile = new std::ofstream(fname.c_str(),std::ios::binary);
  255. if(!(*sfile))
  256. {
  257. tlog1 << "Error: cannot open to write " << fname << std::endl;
  258. sfile = NULL;
  259. }
  260. else
  261. {
  262. sfile->write("VCMI",4); //write magic identifier
  263. *this << version; //write format version
  264. }
  265. }
  266. void CSaveFile::reportState(CLogger &out)
  267. {
  268. out << "CSaveFile" << std::endl;
  269. if(sfile && *sfile)
  270. {
  271. out << "\tOpened " << fName << "\n\tPosition: " << sfile->tellp() << std::endl;
  272. }
  273. }
  274. CLoadFile::CLoadFile(const std::string &fname, int minimalVersion /*= version*/)
  275. :sfile(NULL)
  276. {
  277. registerTypes(*this);
  278. openNextFile(fname, minimalVersion);
  279. }
  280. CLoadFile::~CLoadFile()
  281. {
  282. delete sfile;
  283. }
  284. int CLoadFile::read( const void * data, unsigned size )
  285. {
  286. sfile->read((char *)data,size);
  287. return size;
  288. }
  289. void CLoadFile::close()
  290. {
  291. delete sfile;
  292. sfile = NULL;
  293. }
  294. void CLoadFile::openNextFile(const std::string &fname, int minimalVersion)
  295. {
  296. fName = fname;
  297. sfile = new std::ifstream(fname.c_str(),std::ios::binary);
  298. if(!(*sfile))
  299. {
  300. tlog1 << "Error: cannot open to read " << fname << std::endl;
  301. sfile = NULL;
  302. }
  303. else
  304. {
  305. char buffer[4];
  306. sfile->read(buffer, 4);
  307. if(std::memcmp(buffer,"VCMI",4))
  308. {
  309. tlog1 << "Error: not a VCMI file! ( " << fname << " )\n";
  310. delete sfile;
  311. sfile = NULL;
  312. return;
  313. }
  314. *this >> myVersion;
  315. if(myVersion < minimalVersion)
  316. {
  317. tlog1 << "Error: Old file format! (file " << fname << " )\n";
  318. delete sfile;
  319. sfile = NULL;
  320. }
  321. }
  322. }
  323. void CLoadFile::reportState(CLogger &out)
  324. {
  325. out << "CLoadFile" << std::endl;
  326. if(sfile && *sfile)
  327. {
  328. out << "\tOpened " << fName << "\n\tPosition: " << sfile->tellg() << std::endl;
  329. }
  330. }
  331. CTypeList::CTypeList()
  332. {
  333. registerTypes(*this);
  334. }
  335. ui16 CTypeList::registerType( const std::type_info *type )
  336. {
  337. TTypeMap::const_iterator i = types.find(type);
  338. if(i != types.end())
  339. return i->second; //type found, return ID
  340. //type not found - add it to the list and return given ID
  341. ui16 id = types.size() + 1;
  342. types.insert(std::make_pair(type,id));
  343. return id;
  344. }
  345. ui16 CTypeList::getTypeID( const std::type_info *type )
  346. {
  347. TTypeMap::const_iterator i = types.find(type);
  348. if(i != types.end())
  349. return i->second;
  350. else
  351. return 0;
  352. }
  353. std::ostream & operator<<(std::ostream &str, const CConnection &cpc)
  354. {
  355. return str << "Connection with " << cpc.name << " (ID: " << cpc.connectionID << /*", " << (cpc.host ? "host" : "guest") <<*/ ")";
  356. }
  357. CSerializer::~CSerializer()
  358. {
  359. }
  360. CSerializer::CSerializer()
  361. {
  362. smartVectorMembersSerialization = false;
  363. }
  364. void CSerializer::addStdVecItems(CGameState *gs, LibClasses *lib)
  365. {
  366. registerVectoredType(&gs->map->objects, &CGObjectInstance::id);
  367. registerVectoredType(&lib->heroh->heroes, &CHero::ID);
  368. registerVectoredType(&lib->creh->creatures, &CCreature::idNumber);
  369. registerVectoredType(&lib->arth->artifacts, &CArtifact::id);
  370. registerVectoredType(&gs->map->artInstances, &CArtifactInstance::id);
  371. smartVectorMembersSerialization = true;
  372. }