Connection.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. contactName = pom;
  70. handler = NULL;
  71. receivedStop = sendStop = false;
  72. static int cid = 1;
  73. connectionID = cid++;
  74. }
  75. CConnection::CConnection(std::string host, std::string port, std::string Name)
  76. :io_service(new asio::io_service), name(Name)
  77. {
  78. int i;
  79. boost::system::error_code error = asio::error::host_not_found;
  80. socket = new tcp::socket(*io_service);
  81. tcp::resolver resolver(*io_service);
  82. tcp::resolver::iterator end, pom, endpoint_iterator = resolver.resolve(tcp::resolver::query(host,port),error);
  83. if(error)
  84. {
  85. tlog1 << "Problem with resolving: " << std::endl << error <<std::endl;
  86. goto connerror1;
  87. }
  88. pom = endpoint_iterator;
  89. if(pom != end)
  90. tlog0<<"Found endpoints:" << std::endl;
  91. else
  92. {
  93. tlog1 << "Critical problem: No endpoints found!" << std::endl;
  94. goto connerror1;
  95. }
  96. i=0;
  97. while(pom != end)
  98. {
  99. tlog0 << "\t" << i << ": " << (boost::asio::ip::tcp::endpoint&)*pom << std::endl;
  100. pom++;
  101. }
  102. i=0;
  103. while(endpoint_iterator != end)
  104. {
  105. tlog0 << "Trying connection to " << (boost::asio::ip::tcp::endpoint&)*endpoint_iterator << " (" << i++ << ")" << std::endl;
  106. socket->connect(*endpoint_iterator, error);
  107. if(!error)
  108. {
  109. init();
  110. return;
  111. }
  112. else
  113. {
  114. tlog1 << "Problem with connecting: " << std::endl << error << std::endl;
  115. tlog1 << error.message() << std::endl;
  116. }
  117. endpoint_iterator++;
  118. }
  119. //we shouldn't be here - error handling
  120. connerror1:
  121. tlog1 << "Something went wrong... checking for error info" << std::endl;
  122. if(error)
  123. tlog1 << error <<std::endl;
  124. else
  125. tlog1 << "No error info. " << std::endl;
  126. delete io_service;
  127. //delete socket;
  128. throw std::string("Can't establish connection :(");
  129. }
  130. CConnection::CConnection(TSocket * Socket, std::string Name )
  131. :socket(Socket),io_service(&Socket->get_io_service()), name(Name)//, send(this), rec(this)
  132. {
  133. init();
  134. }
  135. CConnection::CConnection(TAcceptor * acceptor, boost::asio::io_service *Io_service, std::string Name)
  136. : name(Name)//, send(this), rec(this)
  137. {
  138. boost::system::error_code error = asio::error::host_not_found;
  139. socket = new tcp::socket(*io_service);
  140. acceptor->accept(*socket,error);
  141. if (error)
  142. {
  143. tlog1 << "Error on accepting: " << std::endl << error << std::endl;
  144. delete socket;
  145. throw "Can't establish connection :(";
  146. }
  147. init();
  148. }
  149. int CConnection::write(const void * data, unsigned size)
  150. {
  151. //LOG("Sending " << size << " byte(s) of data" <<std::endl);
  152. try
  153. {
  154. int ret;
  155. ret = asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size)));
  156. return ret;
  157. }
  158. catch(...)
  159. {
  160. //connection has been lost
  161. connected = false;
  162. throw;
  163. }
  164. }
  165. int CConnection::read(void * data, unsigned size)
  166. {
  167. //LOG("Receiving " << size << " byte(s) of data" <<std::endl);
  168. try
  169. {
  170. int ret = asio::read(*socket,asio::mutable_buffers_1(asio::mutable_buffer(data,size)));
  171. return ret;
  172. }
  173. catch(...)
  174. {
  175. //connection has been lost
  176. connected = false;
  177. throw;
  178. }
  179. }
  180. CConnection::~CConnection(void)
  181. {
  182. if(handler)
  183. handler->join();
  184. delete handler;
  185. close();
  186. delete io_service;
  187. delete wmx;
  188. delete rmx;
  189. }
  190. template<class T>
  191. CConnection & CConnection::operator&(const T &t) {
  192. throw new std::exception();
  193. //XXX this is temporaly ? solution to fix gcc (4.3.3, other?) compilation
  194. // problem for more details contact [email protected] or [email protected]
  195. // do not remove this exception it shoudnt be called
  196. return *this;
  197. }
  198. void CConnection::close()
  199. {
  200. if(socket)
  201. {
  202. socket->close();
  203. delete socket;
  204. socket = NULL;
  205. }
  206. }
  207. bool CConnection::isOpen() const
  208. {
  209. return socket && connected;
  210. }
  211. void CConnection::reportState(CLogger &out)
  212. {
  213. out << "CConnection\n";
  214. if(socket && socket->is_open())
  215. {
  216. out << "\tWe have an open and valid socket\n";
  217. out << "\t" << socket->available() <<" bytes awaiting\n";
  218. }
  219. }
  220. CPack * CConnection::retreivePack()
  221. {
  222. CPack *ret = NULL;
  223. boost::unique_lock<boost::mutex> lock(*rmx);
  224. tlog5 << "Listening... ";
  225. *this >> ret;
  226. tlog5 << "\treceived message of type " << typeid(*ret).name() << std::endl;
  227. return ret;
  228. }
  229. void CConnection::sendPack(const CPack &pack)
  230. {
  231. boost::unique_lock<boost::mutex> lock(*wmx);
  232. *this << &pack; //packs has to be sent as polymorphic pointers!
  233. }
  234. CSaveFile::CSaveFile( const std::string &fname )
  235. :sfile(NULL)
  236. {
  237. registerTypes(*this);
  238. openNextFile(fname);
  239. }
  240. CSaveFile::~CSaveFile()
  241. {
  242. delete sfile;
  243. }
  244. int CSaveFile::write( const void * data, unsigned size )
  245. {
  246. sfile->write((char *)data,size);
  247. return size;
  248. }
  249. void CSaveFile::close()
  250. {
  251. delete sfile;
  252. sfile = NULL;
  253. }
  254. void CSaveFile::openNextFile(const std::string &fname)
  255. {
  256. fName = fname;
  257. close();
  258. sfile = new std::ofstream(fname.c_str(),std::ios::binary);
  259. if(!(*sfile))
  260. {
  261. tlog1 << "Error: cannot open to write " << fname << std::endl;
  262. sfile = NULL;
  263. }
  264. else
  265. {
  266. sfile->write("VCMI",4); //write magic identifier
  267. *this << version; //write format version
  268. }
  269. }
  270. void CSaveFile::reportState(CLogger &out)
  271. {
  272. out << "CSaveFile" << std::endl;
  273. if(sfile && *sfile)
  274. {
  275. out << "\tOpened " << fName << "\n\tPosition: " << sfile->tellp() << std::endl;
  276. }
  277. }
  278. CLoadFile::CLoadFile(const std::string &fname, int minimalVersion /*= version*/)
  279. :sfile(NULL)
  280. {
  281. registerTypes(*this);
  282. openNextFile(fname, minimalVersion);
  283. }
  284. CLoadFile::~CLoadFile()
  285. {
  286. delete sfile;
  287. }
  288. int CLoadFile::read( const void * data, unsigned size )
  289. {
  290. sfile->read((char *)data,size);
  291. return size;
  292. }
  293. void CLoadFile::close()
  294. {
  295. delete sfile;
  296. sfile = NULL;
  297. }
  298. void CLoadFile::openNextFile(const std::string &fname, int minimalVersion)
  299. {
  300. fName = fname;
  301. sfile = new std::ifstream(fname.c_str(),std::ios::binary);
  302. if(!(*sfile))
  303. {
  304. tlog1 << "Error: cannot open to read " << fname << std::endl;
  305. sfile = NULL;
  306. }
  307. else
  308. {
  309. char buffer[4];
  310. sfile->read(buffer, 4);
  311. if(std::memcmp(buffer,"VCMI",4))
  312. {
  313. tlog1 << "Error: not a VCMI file! ( " << fname << " )\n";
  314. delete sfile;
  315. sfile = NULL;
  316. return;
  317. }
  318. *this >> myVersion;
  319. if(myVersion < minimalVersion)
  320. {
  321. tlog1 << "Error: Old file format! (file " << fname << " )\n";
  322. delete sfile;
  323. sfile = NULL;
  324. }
  325. }
  326. }
  327. void CLoadFile::reportState(CLogger &out)
  328. {
  329. out << "CLoadFile" << std::endl;
  330. if(sfile && *sfile)
  331. {
  332. out << "\tOpened " << fName << "\n\tPosition: " << sfile->tellg() << std::endl;
  333. }
  334. }
  335. CTypeList::CTypeList()
  336. {
  337. registerTypes(*this);
  338. }
  339. ui16 CTypeList::registerType( const std::type_info *type )
  340. {
  341. TTypeMap::const_iterator i = types.find(type);
  342. if(i != types.end())
  343. return i->second; //type found, return ID
  344. //type not found - add it to the list and return given ID
  345. ui16 id = types.size() + 1;
  346. types.insert(std::make_pair(type,id));
  347. return id;
  348. }
  349. ui16 CTypeList::getTypeID( const std::type_info *type )
  350. {
  351. TTypeMap::const_iterator i = types.find(type);
  352. if(i != types.end())
  353. return i->second;
  354. else
  355. return 0;
  356. }
  357. std::ostream & operator<<(std::ostream &str, const CConnection &cpc)
  358. {
  359. return str << "Connection with " << cpc.name << " (ID: " << cpc.connectionID << /*", " << (cpc.host ? "host" : "guest") <<*/ ")";
  360. }
  361. CSerializer::~CSerializer()
  362. {
  363. }
  364. CSerializer::CSerializer()
  365. {
  366. smartVectorMembersSerialization = false;
  367. }
  368. void CSerializer::addStdVecItems(CGameState *gs, LibClasses *lib)
  369. {
  370. assert(gs);
  371. registerVectoredType(&gs->map->objects, &CGObjectInstance::id);
  372. registerVectoredType(&lib->heroh->heroes, &CHero::ID);
  373. registerVectoredType(&lib->creh->creatures, &CCreature::idNumber);
  374. registerVectoredType(&lib->arth->artifacts, &CArtifact::id);
  375. registerVectoredType(&gs->map->artInstances, &CArtifactInstance::id);
  376. smartVectorMembersSerialization = true;
  377. }