basic_socket_streambuf.hpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. //
  2. // basic_socket_streambuf.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_BASIC_SOCKET_STREAMBUF_HPP
  11. #define ASIO_BASIC_SOCKET_STREAMBUF_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #if !defined(ASIO_NO_IOSTREAM)
  17. #include <streambuf>
  18. #include <vector>
  19. #include "asio/basic_socket.hpp"
  20. #include "asio/basic_stream_socket.hpp"
  21. #include "asio/detail/buffer_sequence_adapter.hpp"
  22. #include "asio/detail/memory.hpp"
  23. #include "asio/detail/throw_error.hpp"
  24. #include "asio/io_context.hpp"
  25. #if defined(ASIO_ENABLE_OLD_SERVICES)
  26. # include "asio/stream_socket_service.hpp"
  27. #endif // defined(ASIO_ENABLE_OLD_SERVICES)
  28. #if defined(ASIO_HAS_BOOST_DATE_TIME) \
  29. && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  30. # if defined(ASIO_ENABLE_OLD_SERVICES)
  31. # include "asio/deadline_timer_service.hpp"
  32. # else // defined(ASIO_ENABLE_OLD_SERVICES)
  33. # include "asio/detail/deadline_timer_service.hpp"
  34. # endif // defined(ASIO_ENABLE_OLD_SERVICES)
  35. #else // defined(ASIO_HAS_BOOST_DATE_TIME)
  36. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  37. # include "asio/steady_timer.hpp"
  38. #endif // defined(ASIO_HAS_BOOST_DATE_TIME)
  39. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  40. #if !defined(ASIO_HAS_VARIADIC_TEMPLATES)
  41. # include "asio/detail/variadic_templates.hpp"
  42. // A macro that should expand to:
  43. // template <typename T1, ..., typename Tn>
  44. // basic_socket_streambuf* connect(T1 x1, ..., Tn xn)
  45. // {
  46. // init_buffers();
  47. // typedef typename Protocol::resolver resolver_type;
  48. // resolver_type resolver(socket().get_executor().context());
  49. // connect_to_endpoints(
  50. // resolver.resolve(x1, ..., xn, ec_));
  51. // return !ec_ ? this : 0;
  52. // }
  53. // This macro should only persist within this file.
  54. # define ASIO_PRIVATE_CONNECT_DEF(n) \
  55. template <ASIO_VARIADIC_TPARAMS(n)> \
  56. basic_socket_streambuf* connect(ASIO_VARIADIC_BYVAL_PARAMS(n)) \
  57. { \
  58. init_buffers(); \
  59. typedef typename Protocol::resolver resolver_type; \
  60. resolver_type resolver(socket().get_executor().context()); \
  61. connect_to_endpoints( \
  62. resolver.resolve(ASIO_VARIADIC_BYVAL_ARGS(n), ec_)); \
  63. return !ec_ ? this : 0; \
  64. } \
  65. /**/
  66. #endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES)
  67. #if !defined(ASIO_ENABLE_OLD_SERVICES)
  68. # define ASIO_SVC_T1 detail::deadline_timer_service<traits_helper>
  69. #endif // !defined(ASIO_ENABLE_OLD_SERVICES)
  70. #include "asio/detail/push_options.hpp"
  71. namespace asio {
  72. namespace detail {
  73. // A separate base class is used to ensure that the io_context member is
  74. // initialised prior to the basic_socket_streambuf's basic_socket base class.
  75. class socket_streambuf_io_context
  76. {
  77. protected:
  78. socket_streambuf_io_context(io_context* ctx)
  79. : default_io_context_(ctx)
  80. {
  81. }
  82. shared_ptr<io_context> default_io_context_;
  83. };
  84. // A separate base class is used to ensure that the dynamically allocated
  85. // buffers are constructed prior to the basic_socket_streambuf's basic_socket
  86. // base class. This makes moving the socket is the last potentially throwing
  87. // step in the streambuf's move constructor, giving the constructor a strong
  88. // exception safety guarantee.
  89. class socket_streambuf_buffers
  90. {
  91. protected:
  92. socket_streambuf_buffers()
  93. : get_buffer_(buffer_size),
  94. put_buffer_(buffer_size)
  95. {
  96. }
  97. enum { buffer_size = 512 };
  98. std::vector<char> get_buffer_;
  99. std::vector<char> put_buffer_;
  100. };
  101. } // namespace detail
  102. #if !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL)
  103. #define ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL
  104. // Forward declaration with defaulted arguments.
  105. template <typename Protocol
  106. ASIO_SVC_TPARAM_DEF1(= stream_socket_service<Protocol>),
  107. #if defined(ASIO_HAS_BOOST_DATE_TIME) \
  108. && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  109. typename Clock = boost::posix_time::ptime,
  110. typename WaitTraits = time_traits<Clock>
  111. ASIO_SVC_TPARAM1_DEF2(= deadline_timer_service<Clock, WaitTraits>)>
  112. #else // defined(ASIO_HAS_BOOST_DATE_TIME)
  113. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  114. typename Clock = chrono::steady_clock,
  115. typename WaitTraits = wait_traits<Clock>
  116. ASIO_SVC_TPARAM1_DEF1(= steady_timer::service_type)>
  117. #endif // defined(ASIO_HAS_BOOST_DATE_TIME)
  118. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  119. class basic_socket_streambuf;
  120. #endif // !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL)
  121. /// Iostream streambuf for a socket.
  122. #if defined(GENERATING_DOCUMENTATION)
  123. template <typename Protocol,
  124. typename Clock = chrono::steady_clock,
  125. typename WaitTraits = wait_traits<Clock> >
  126. #else // defined(GENERATING_DOCUMENTATION)
  127. template <typename Protocol ASIO_SVC_TPARAM,
  128. typename Clock, typename WaitTraits ASIO_SVC_TPARAM1>
  129. #endif // defined(GENERATING_DOCUMENTATION)
  130. class basic_socket_streambuf
  131. : public std::streambuf,
  132. private detail::socket_streambuf_io_context,
  133. private detail::socket_streambuf_buffers,
  134. #if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION)
  135. private basic_socket<Protocol ASIO_SVC_TARG>
  136. #else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION)
  137. public basic_socket<Protocol ASIO_SVC_TARG>
  138. #endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION)
  139. {
  140. private:
  141. // These typedefs are intended keep this class's implementation independent
  142. // of whether it's using Boost.DateClock, Boost.Chrono or std::chrono.
  143. #if defined(ASIO_HAS_BOOST_DATE_TIME) \
  144. && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  145. typedef WaitTraits traits_helper;
  146. #else // defined(ASIO_HAS_BOOST_DATE_TIME)
  147. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  148. typedef detail::chrono_time_traits<Clock, WaitTraits> traits_helper;
  149. #endif // defined(ASIO_HAS_BOOST_DATE_TIME)
  150. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  151. public:
  152. /// The protocol type.
  153. typedef Protocol protocol_type;
  154. /// The endpoint type.
  155. typedef typename Protocol::endpoint endpoint_type;
  156. /// The clock type.
  157. typedef Clock clock_type;
  158. #if defined(GENERATING_DOCUMENTATION)
  159. /// (Deprecated: Use time_point.) The time type.
  160. typedef typename WaitTraits::time_type time_type;
  161. /// The time type.
  162. typedef typename WaitTraits::time_point time_point;
  163. /// (Deprecated: Use duration.) The duration type.
  164. typedef typename WaitTraits::duration_type duration_type;
  165. /// The duration type.
  166. typedef typename WaitTraits::duration duration;
  167. #else
  168. # if !defined(ASIO_NO_DEPRECATED)
  169. typedef typename traits_helper::time_type time_type;
  170. typedef typename traits_helper::duration_type duration_type;
  171. # endif // !defined(ASIO_NO_DEPRECATED)
  172. typedef typename traits_helper::time_type time_point;
  173. typedef typename traits_helper::duration_type duration;
  174. #endif
  175. /// Construct a basic_socket_streambuf without establishing a connection.
  176. basic_socket_streambuf()
  177. : detail::socket_streambuf_io_context(new io_context),
  178. basic_socket<Protocol ASIO_SVC_TARG>(*default_io_context_),
  179. expiry_time_(max_expiry_time())
  180. {
  181. init_buffers();
  182. }
  183. #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  184. /// Construct a basic_socket_streambuf from the supplied socket.
  185. explicit basic_socket_streambuf(basic_stream_socket<protocol_type> s)
  186. : detail::socket_streambuf_io_context(0),
  187. basic_socket<Protocol ASIO_SVC_TARG>(std::move(s)),
  188. expiry_time_(max_expiry_time())
  189. {
  190. init_buffers();
  191. }
  192. /// Move-construct a basic_socket_streambuf from another.
  193. basic_socket_streambuf(basic_socket_streambuf&& other)
  194. : detail::socket_streambuf_io_context(other),
  195. basic_socket<Protocol ASIO_SVC_TARG>(std::move(other.socket())),
  196. ec_(other.ec_),
  197. expiry_time_(other.expiry_time_)
  198. {
  199. get_buffer_.swap(other.get_buffer_);
  200. put_buffer_.swap(other.put_buffer_);
  201. setg(other.eback(), other.gptr(), other.egptr());
  202. setp(other.pptr(), other.epptr());
  203. other.ec_ = asio::error_code();
  204. other.expiry_time_ = max_expiry_time();
  205. other.init_buffers();
  206. }
  207. /// Move-assign a basic_socket_streambuf from another.
  208. basic_socket_streambuf& operator=(basic_socket_streambuf&& other)
  209. {
  210. this->close();
  211. socket() = std::move(other.socket());
  212. detail::socket_streambuf_io_context::operator=(other);
  213. ec_ = other.ec_;
  214. expiry_time_ = other.expiry_time_;
  215. get_buffer_.swap(other.get_buffer_);
  216. put_buffer_.swap(other.put_buffer_);
  217. setg(other.eback(), other.gptr(), other.egptr());
  218. setp(other.pptr(), other.epptr());
  219. other.ec_ = asio::error_code();
  220. other.expiry_time_ = max_expiry_time();
  221. other.put_buffer_.resize(buffer_size);
  222. other.init_buffers();
  223. return *this;
  224. }
  225. #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  226. /// Destructor flushes buffered data.
  227. virtual ~basic_socket_streambuf()
  228. {
  229. if (pptr() != pbase())
  230. overflow(traits_type::eof());
  231. }
  232. /// Establish a connection.
  233. /**
  234. * This function establishes a connection to the specified endpoint.
  235. *
  236. * @return \c this if a connection was successfully established, a null
  237. * pointer otherwise.
  238. */
  239. basic_socket_streambuf* connect(const endpoint_type& endpoint)
  240. {
  241. init_buffers();
  242. ec_ = asio::error_code();
  243. this->connect_to_endpoints(&endpoint, &endpoint + 1);
  244. return !ec_ ? this : 0;
  245. }
  246. #if defined(GENERATING_DOCUMENTATION)
  247. /// Establish a connection.
  248. /**
  249. * This function automatically establishes a connection based on the supplied
  250. * resolver query parameters. The arguments are used to construct a resolver
  251. * query object.
  252. *
  253. * @return \c this if a connection was successfully established, a null
  254. * pointer otherwise.
  255. */
  256. template <typename T1, ..., typename TN>
  257. basic_socket_streambuf* connect(T1 t1, ..., TN tn);
  258. #elif defined(ASIO_HAS_VARIADIC_TEMPLATES)
  259. template <typename... T>
  260. basic_socket_streambuf* connect(T... x)
  261. {
  262. init_buffers();
  263. typedef typename Protocol::resolver resolver_type;
  264. resolver_type resolver(socket().get_executor().context());
  265. connect_to_endpoints(resolver.resolve(x..., ec_));
  266. return !ec_ ? this : 0;
  267. }
  268. #else
  269. ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CONNECT_DEF)
  270. #endif
  271. /// Close the connection.
  272. /**
  273. * @return \c this if a connection was successfully established, a null
  274. * pointer otherwise.
  275. */
  276. basic_socket_streambuf* close()
  277. {
  278. sync();
  279. socket().close(ec_);
  280. if (!ec_)
  281. init_buffers();
  282. return !ec_ ? this : 0;
  283. }
  284. /// Get a reference to the underlying socket.
  285. basic_socket<Protocol ASIO_SVC_TARG>& socket()
  286. {
  287. return *this;
  288. }
  289. /// Get the last error associated with the stream buffer.
  290. /**
  291. * @return An \c error_code corresponding to the last error from the stream
  292. * buffer.
  293. */
  294. const asio::error_code& error() const
  295. {
  296. return ec_;
  297. }
  298. #if !defined(ASIO_NO_DEPRECATED)
  299. /// (Deprecated: Use error().) Get the last error associated with the stream
  300. /// buffer.
  301. /**
  302. * @return An \c error_code corresponding to the last error from the stream
  303. * buffer.
  304. */
  305. const asio::error_code& puberror() const
  306. {
  307. return error();
  308. }
  309. /// (Deprecated: Use expiry().) Get the stream buffer's expiry time as an
  310. /// absolute time.
  311. /**
  312. * @return An absolute time value representing the stream buffer's expiry
  313. * time.
  314. */
  315. time_point expires_at() const
  316. {
  317. return expiry_time_;
  318. }
  319. #endif // !defined(ASIO_NO_DEPRECATED)
  320. /// Get the stream buffer's expiry time as an absolute time.
  321. /**
  322. * @return An absolute time value representing the stream buffer's expiry
  323. * time.
  324. */
  325. time_point expiry() const
  326. {
  327. return expiry_time_;
  328. }
  329. /// Set the stream buffer's expiry time as an absolute time.
  330. /**
  331. * This function sets the expiry time associated with the stream. Stream
  332. * operations performed after this time (where the operations cannot be
  333. * completed using the internal buffers) will fail with the error
  334. * asio::error::operation_aborted.
  335. *
  336. * @param expiry_time The expiry time to be used for the stream.
  337. */
  338. void expires_at(const time_point& expiry_time)
  339. {
  340. expiry_time_ = expiry_time;
  341. }
  342. /// Set the stream buffer's expiry time relative to now.
  343. /**
  344. * This function sets the expiry time associated with the stream. Stream
  345. * operations performed after this time (where the operations cannot be
  346. * completed using the internal buffers) will fail with the error
  347. * asio::error::operation_aborted.
  348. *
  349. * @param expiry_time The expiry time to be used for the timer.
  350. */
  351. void expires_after(const duration& expiry_time)
  352. {
  353. expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time);
  354. }
  355. #if !defined(ASIO_NO_DEPRECATED)
  356. /// (Deprecated: Use expiry().) Get the stream buffer's expiry time relative
  357. /// to now.
  358. /**
  359. * @return A relative time value representing the stream buffer's expiry time.
  360. */
  361. duration expires_from_now() const
  362. {
  363. return traits_helper::subtract(expires_at(), traits_helper::now());
  364. }
  365. /// (Deprecated: Use expires_after().) Set the stream buffer's expiry time
  366. /// relative to now.
  367. /**
  368. * This function sets the expiry time associated with the stream. Stream
  369. * operations performed after this time (where the operations cannot be
  370. * completed using the internal buffers) will fail with the error
  371. * asio::error::operation_aborted.
  372. *
  373. * @param expiry_time The expiry time to be used for the timer.
  374. */
  375. void expires_from_now(const duration& expiry_time)
  376. {
  377. expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time);
  378. }
  379. #endif // !defined(ASIO_NO_DEPRECATED)
  380. protected:
  381. int_type underflow()
  382. {
  383. #if defined(ASIO_WINDOWS_RUNTIME)
  384. ec_ = asio::error::operation_not_supported;
  385. return traits_type::eof();
  386. #else // defined(ASIO_WINDOWS_RUNTIME)
  387. if (gptr() != egptr())
  388. return traits_type::eof();
  389. for (;;)
  390. {
  391. // Check if we are past the expiry time.
  392. if (traits_helper::less_than(expiry_time_, traits_helper::now()))
  393. {
  394. ec_ = asio::error::timed_out;
  395. return traits_type::eof();
  396. }
  397. // Try to complete the operation without blocking.
  398. if (!socket().native_non_blocking())
  399. socket().native_non_blocking(true, ec_);
  400. detail::buffer_sequence_adapter<mutable_buffer, mutable_buffer>
  401. bufs(asio::buffer(get_buffer_) + putback_max);
  402. detail::signed_size_type bytes = detail::socket_ops::recv(
  403. socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_);
  404. // Check if operation succeeded.
  405. if (bytes > 0)
  406. {
  407. setg(&get_buffer_[0], &get_buffer_[0] + putback_max,
  408. &get_buffer_[0] + putback_max + bytes);
  409. return traits_type::to_int_type(*gptr());
  410. }
  411. // Check for EOF.
  412. if (bytes == 0)
  413. {
  414. ec_ = asio::error::eof;
  415. return traits_type::eof();
  416. }
  417. // Operation failed.
  418. if (ec_ != asio::error::would_block
  419. && ec_ != asio::error::try_again)
  420. return traits_type::eof();
  421. // Wait for socket to become ready.
  422. if (detail::socket_ops::poll_read(
  423. socket().native_handle(), 0, timeout(), ec_) < 0)
  424. return traits_type::eof();
  425. }
  426. #endif // defined(ASIO_WINDOWS_RUNTIME)
  427. }
  428. int_type overflow(int_type c)
  429. {
  430. #if defined(ASIO_WINDOWS_RUNTIME)
  431. ec_ = asio::error::operation_not_supported;
  432. return traits_type::eof();
  433. #else // defined(ASIO_WINDOWS_RUNTIME)
  434. char_type ch = traits_type::to_char_type(c);
  435. // Determine what needs to be sent.
  436. const_buffer output_buffer;
  437. if (put_buffer_.empty())
  438. {
  439. if (traits_type::eq_int_type(c, traits_type::eof()))
  440. return traits_type::not_eof(c); // Nothing to do.
  441. output_buffer = asio::buffer(&ch, sizeof(char_type));
  442. }
  443. else
  444. {
  445. output_buffer = asio::buffer(pbase(),
  446. (pptr() - pbase()) * sizeof(char_type));
  447. }
  448. while (output_buffer.size() > 0)
  449. {
  450. // Check if we are past the expiry time.
  451. if (traits_helper::less_than(expiry_time_, traits_helper::now()))
  452. {
  453. ec_ = asio::error::timed_out;
  454. return traits_type::eof();
  455. }
  456. // Try to complete the operation without blocking.
  457. if (!socket().native_non_blocking())
  458. socket().native_non_blocking(true, ec_);
  459. detail::buffer_sequence_adapter<
  460. const_buffer, const_buffer> bufs(output_buffer);
  461. detail::signed_size_type bytes = detail::socket_ops::send(
  462. socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_);
  463. // Check if operation succeeded.
  464. if (bytes > 0)
  465. {
  466. output_buffer += static_cast<std::size_t>(bytes);
  467. continue;
  468. }
  469. // Operation failed.
  470. if (ec_ != asio::error::would_block
  471. && ec_ != asio::error::try_again)
  472. return traits_type::eof();
  473. // Wait for socket to become ready.
  474. if (detail::socket_ops::poll_write(
  475. socket().native_handle(), 0, timeout(), ec_) < 0)
  476. return traits_type::eof();
  477. }
  478. if (!put_buffer_.empty())
  479. {
  480. setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size());
  481. // If the new character is eof then our work here is done.
  482. if (traits_type::eq_int_type(c, traits_type::eof()))
  483. return traits_type::not_eof(c);
  484. // Add the new character to the output buffer.
  485. *pptr() = ch;
  486. pbump(1);
  487. }
  488. return c;
  489. #endif // defined(ASIO_WINDOWS_RUNTIME)
  490. }
  491. int sync()
  492. {
  493. return overflow(traits_type::eof());
  494. }
  495. std::streambuf* setbuf(char_type* s, std::streamsize n)
  496. {
  497. if (pptr() == pbase() && s == 0 && n == 0)
  498. {
  499. put_buffer_.clear();
  500. setp(0, 0);
  501. sync();
  502. return this;
  503. }
  504. return 0;
  505. }
  506. private:
  507. // Disallow copying and assignment.
  508. basic_socket_streambuf(const basic_socket_streambuf&) ASIO_DELETED;
  509. basic_socket_streambuf& operator=(
  510. const basic_socket_streambuf&) ASIO_DELETED;
  511. void init_buffers()
  512. {
  513. setg(&get_buffer_[0],
  514. &get_buffer_[0] + putback_max,
  515. &get_buffer_[0] + putback_max);
  516. if (put_buffer_.empty())
  517. setp(0, 0);
  518. else
  519. setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size());
  520. }
  521. int timeout() const
  522. {
  523. int64_t msec = traits_helper::to_posix_duration(
  524. traits_helper::subtract(expiry_time_,
  525. traits_helper::now())).total_milliseconds();
  526. if (msec > (std::numeric_limits<int>::max)())
  527. msec = (std::numeric_limits<int>::max)();
  528. else if (msec < 0)
  529. msec = 0;
  530. return static_cast<int>(msec);
  531. }
  532. template <typename EndpointSequence>
  533. void connect_to_endpoints(const EndpointSequence& endpoints)
  534. {
  535. this->connect_to_endpoints(endpoints.begin(), endpoints.end());
  536. }
  537. template <typename EndpointIterator>
  538. void connect_to_endpoints(EndpointIterator begin, EndpointIterator end)
  539. {
  540. #if defined(ASIO_WINDOWS_RUNTIME)
  541. ec_ = asio::error::operation_not_supported;
  542. #else // defined(ASIO_WINDOWS_RUNTIME)
  543. if (ec_)
  544. return;
  545. ec_ = asio::error::not_found;
  546. for (EndpointIterator i = begin; i != end; ++i)
  547. {
  548. // Check if we are past the expiry time.
  549. if (traits_helper::less_than(expiry_time_, traits_helper::now()))
  550. {
  551. ec_ = asio::error::timed_out;
  552. return;
  553. }
  554. // Close and reopen the socket.
  555. typename Protocol::endpoint ep(*i);
  556. socket().close(ec_);
  557. socket().open(ep.protocol(), ec_);
  558. if (ec_)
  559. continue;
  560. // Try to complete the operation without blocking.
  561. if (!socket().native_non_blocking())
  562. socket().native_non_blocking(true, ec_);
  563. detail::socket_ops::connect(socket().native_handle(),
  564. ep.data(), ep.size(), ec_);
  565. // Check if operation succeeded.
  566. if (!ec_)
  567. return;
  568. // Operation failed.
  569. if (ec_ != asio::error::in_progress
  570. && ec_ != asio::error::would_block)
  571. continue;
  572. // Wait for socket to become ready.
  573. if (detail::socket_ops::poll_connect(
  574. socket().native_handle(), timeout(), ec_) < 0)
  575. continue;
  576. // Get the error code from the connect operation.
  577. int connect_error = 0;
  578. size_t connect_error_len = sizeof(connect_error);
  579. if (detail::socket_ops::getsockopt(socket().native_handle(), 0,
  580. SOL_SOCKET, SO_ERROR, &connect_error, &connect_error_len, ec_)
  581. == detail::socket_error_retval)
  582. return;
  583. // Check the result of the connect operation.
  584. ec_ = asio::error_code(connect_error,
  585. asio::error::get_system_category());
  586. if (!ec_)
  587. return;
  588. }
  589. #endif // defined(ASIO_WINDOWS_RUNTIME)
  590. }
  591. // Helper function to get the maximum expiry time.
  592. static time_point max_expiry_time()
  593. {
  594. #if defined(ASIO_HAS_BOOST_DATE_TIME) \
  595. && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  596. return boost::posix_time::pos_infin;
  597. #else // defined(ASIO_HAS_BOOST_DATE_TIME)
  598. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  599. return (time_point::max)();
  600. #endif // defined(ASIO_HAS_BOOST_DATE_TIME)
  601. // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM)
  602. }
  603. enum { putback_max = 8 };
  604. asio::error_code ec_;
  605. time_point expiry_time_;
  606. };
  607. } // namespace asio
  608. #include "asio/detail/pop_options.hpp"
  609. #if !defined(ASIO_ENABLE_OLD_SERVICES)
  610. # undef ASIO_SVC_T1
  611. #endif // !defined(ASIO_ENABLE_OLD_SERVICES)
  612. #if !defined(ASIO_HAS_VARIADIC_TEMPLATES)
  613. # undef ASIO_PRIVATE_CONNECT_DEF
  614. #endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES)
  615. #endif // !defined(ASIO_NO_IOSTREAM)
  616. #endif // ASIO_BASIC_SOCKET_STREAMBUF_HPP