Connection.cpp 8.2 KB

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