Connection.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Connection.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "Connection.h"
  12. #include "../registerTypes/RegisterTypes.h"
  13. #include "../mapping/CMap.h"
  14. #include "../CGameState.h"
  15. #include <boost/asio.hpp>
  16. using namespace boost;
  17. using namespace boost::asio::ip;
  18. #if defined(__hppa__) || \
  19. defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \
  20. (defined(__MIPS__) && defined(__MISPEB__)) || \
  21. defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \
  22. defined(__sparc__)
  23. #define BIG_ENDIAN
  24. #else
  25. #define LIL_ENDIAN
  26. #endif
  27. void CConnection::init()
  28. {
  29. socket->set_option(boost::asio::ip::tcp::no_delay(true));
  30. try
  31. {
  32. socket->set_option(boost::asio::socket_base::send_buffer_size(4194304));
  33. socket->set_option(boost::asio::socket_base::receive_buffer_size(4194304));
  34. }
  35. catch (const boost::system::system_error & e)
  36. {
  37. logNetwork->error("error setting socket option: %s", e.what());
  38. }
  39. enableSmartPointerSerialization();
  40. disableStackSendingByID();
  41. registerTypes(iser);
  42. registerTypes(oser);
  43. #ifdef LIL_ENDIAN
  44. myEndianess = true;
  45. #else
  46. myEndianess = false;
  47. #endif
  48. connected = true;
  49. std::string pom;
  50. //we got connection
  51. oser & std::string("Aiya!\n") & name & uuid & myEndianess; //identify ourselves
  52. iser & pom & pom & contactUuid & contactEndianess;
  53. logNetwork->info("Established connection with %s. UUID: %s", pom, contactUuid);
  54. mutexRead = std::make_shared<boost::mutex>();
  55. mutexWrite = std::make_shared<boost::mutex>();
  56. iser.fileVersion = SERIALIZATION_VERSION;
  57. }
  58. CConnection::CConnection(std::string host, ui16 port, std::string Name, std::string UUID)
  59. : io_service(std::make_shared<asio::io_service>()), iser(this), oser(this), name(Name), uuid(UUID), connectionID(0)
  60. {
  61. int i;
  62. boost::system::error_code error = asio::error::host_not_found;
  63. socket = std::make_shared<tcp::socket>(*io_service);
  64. tcp::resolver resolver(*io_service);
  65. // todo ios: is new param really needed?
  66. tcp::resolver::iterator end, pom, endpoint_iterator = resolver.resolve(tcp::resolver::query(host, std::to_string(port), resolver_query_base::numeric_service), error);
  67. if(error)
  68. {
  69. logNetwork->error("Problem with resolving: \n%s", error.message());
  70. goto connerror1;
  71. }
  72. pom = endpoint_iterator;
  73. if(pom != end)
  74. logNetwork->info("Found endpoints:");
  75. else
  76. {
  77. logNetwork->error("Critical problem: No endpoints found!");
  78. goto connerror1;
  79. }
  80. i=0;
  81. while(pom != end)
  82. {
  83. logNetwork->info("\t%d:%s", i, (boost::asio::ip::tcp::endpoint&)*pom);
  84. pom++;
  85. }
  86. i=0;
  87. while(endpoint_iterator != end)
  88. {
  89. logNetwork->info("Trying connection to %s(%d)", (boost::asio::ip::tcp::endpoint&)*endpoint_iterator, i++);
  90. socket->connect(*endpoint_iterator, error);
  91. if(!error)
  92. {
  93. init();
  94. return;
  95. }
  96. else
  97. {
  98. logNetwork->error("Problem with connecting: %s", error.message());
  99. }
  100. endpoint_iterator++;
  101. }
  102. //we shouldn't be here - error handling
  103. connerror1:
  104. logNetwork->error("Something went wrong... checking for error info");
  105. if(error)
  106. logNetwork->error(error.message());
  107. else
  108. logNetwork->error("No error info. ");
  109. throw std::runtime_error("Can't establish connection :(");
  110. }
  111. CConnection::CConnection(std::shared_ptr<TSocket> Socket, std::string Name, std::string UUID)
  112. : iser(this), oser(this), socket(Socket), name(Name), uuid(UUID), connectionID(0)
  113. {
  114. init();
  115. }
  116. CConnection::CConnection(std::shared_ptr<TAcceptor> acceptor, std::shared_ptr<boost::asio::io_service> io_service, std::string Name, std::string UUID)
  117. : io_service(io_service), iser(this), oser(this), name(Name), uuid(UUID), connectionID(0)
  118. {
  119. boost::system::error_code error = asio::error::host_not_found;
  120. socket = std::make_shared<tcp::socket>(*io_service);
  121. acceptor->accept(*socket,error);
  122. if (error)
  123. {
  124. logNetwork->error("Error on accepting: %s", error.message());
  125. socket.reset();
  126. throw std::runtime_error("Can't establish connection :(");
  127. }
  128. init();
  129. }
  130. int CConnection::write(const void * data, unsigned size)
  131. {
  132. try
  133. {
  134. int ret;
  135. ret = static_cast<int>(asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size))));
  136. return ret;
  137. }
  138. catch(...)
  139. {
  140. //connection has been lost
  141. connected = false;
  142. throw;
  143. }
  144. }
  145. int CConnection::read(void * data, unsigned size)
  146. {
  147. try
  148. {
  149. int ret = static_cast<int>(asio::read(*socket,asio::mutable_buffers_1(asio::mutable_buffer(data,size))));
  150. return ret;
  151. }
  152. catch(...)
  153. {
  154. //connection has been lost
  155. connected = false;
  156. throw;
  157. }
  158. }
  159. CConnection::~CConnection()
  160. {
  161. if(handler)
  162. handler->join();
  163. close();
  164. }
  165. template<class T>
  166. CConnection & CConnection::operator&(const T &t) {
  167. // throw std::exception();
  168. //XXX this is temporaly ? solution to fix gcc (4.3.3, other?) compilation
  169. // problem for more details contact [email protected] or [email protected]
  170. // do not remove this exception it shoudnt be called
  171. return *this;
  172. }
  173. void CConnection::close()
  174. {
  175. if(socket)
  176. {
  177. socket->close();
  178. socket.reset();
  179. }
  180. }
  181. bool CConnection::isOpen() const
  182. {
  183. return socket && connected;
  184. }
  185. void CConnection::reportState(vstd::CLoggerBase * out)
  186. {
  187. out->debug("CConnection");
  188. if(socket && socket->is_open())
  189. {
  190. out->debug("\tWe have an open and valid socket");
  191. out->debug("\t %d bytes awaiting", socket->available());
  192. }
  193. }
  194. CPack * CConnection::retrievePack()
  195. {
  196. CPack * pack = nullptr;
  197. boost::unique_lock<boost::mutex> lock(*mutexRead);
  198. iser & pack;
  199. logNetwork->trace("Received CPack of type %s", (pack ? typeid(*pack).name() : "nullptr"));
  200. if(pack == nullptr)
  201. {
  202. logNetwork->error("Received a nullptr CPack! You should check whether client and server ABI matches.");
  203. }
  204. else
  205. {
  206. pack->c = this->shared_from_this();
  207. }
  208. return pack;
  209. }
  210. void CConnection::sendPack(const CPack * pack)
  211. {
  212. boost::unique_lock<boost::mutex> lock(*mutexWrite);
  213. logNetwork->trace("Sending a pack of type %s", typeid(*pack).name());
  214. oser & pack;
  215. }
  216. void CConnection::disableStackSendingByID()
  217. {
  218. CSerializer::sendStackInstanceByIds = false;
  219. }
  220. void CConnection::enableStackSendingByID()
  221. {
  222. CSerializer::sendStackInstanceByIds = true;
  223. }
  224. void CConnection::disableSmartPointerSerialization()
  225. {
  226. iser.smartPointerSerialization = oser.smartPointerSerialization = false;
  227. }
  228. void CConnection::enableSmartPointerSerialization()
  229. {
  230. iser.smartPointerSerialization = oser.smartPointerSerialization = true;
  231. }
  232. void CConnection::enterLobbyConnectionMode()
  233. {
  234. iser.loadedPointers.clear();
  235. oser.savedPointers.clear();
  236. disableSmartVectorMemberSerialization();
  237. disableSmartPointerSerialization();
  238. }
  239. void CConnection::enterGameplayConnectionMode(CGameState * gs)
  240. {
  241. enableStackSendingByID();
  242. disableSmartPointerSerialization();
  243. addStdVecItems(gs);
  244. }
  245. void CConnection::disableSmartVectorMemberSerialization()
  246. {
  247. CSerializer::smartVectorMembersSerialization = false;
  248. }
  249. void CConnection::enableSmartVectorMemberSerializatoin()
  250. {
  251. CSerializer::smartVectorMembersSerialization = true;
  252. }
  253. std::string CConnection::toString() const
  254. {
  255. boost::format fmt("Connection with %s (ID: %d UUID: %s)");
  256. fmt % name % connectionID % uuid;
  257. return fmt.str();
  258. }