Connection.cpp 9.5 KB

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