Connection.cpp 7.0 KB

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