Connection.cpp 6.8 KB

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