basic_socket_streambuf.hpp 21 KB

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