Connection.cpp 8.9 KB

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