PageRenderTime 72ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/Src/Dependencies/Boost/boost/asio/detail/impl/socket_ops.ipp

http://hadesmem.googlecode.com/
C++ Header | 3048 lines | 2550 code | 287 blank | 211 comment | 765 complexity | a110c3cf3a01d0363e2dff13e1d4da07 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.0, Apache-2.0, LGPL-3.0
  1. //
  2. // detail/impl/socket_ops.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2011 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_DETAIL_SOCKET_OPS_IPP
  11. #define BOOST_ASIO_DETAIL_SOCKET_OPS_IPP
  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. #include <boost/assert.hpp>
  17. #include <boost/detail/workaround.hpp>
  18. #include <cstdio>
  19. #include <cstdlib>
  20. #include <cstring>
  21. #include <cerrno>
  22. #include <new>
  23. #include <boost/asio/detail/socket_ops.hpp>
  24. #include <boost/asio/error.hpp>
  25. #include <boost/asio/detail/push_options.hpp>
  26. namespace boost {
  27. namespace asio {
  28. namespace detail {
  29. namespace socket_ops {
  30. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  31. struct msghdr { int msg_namelen; };
  32. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  33. #if defined(__hpux)
  34. // HP-UX doesn't declare these functions extern "C", so they are declared again
  35. // here to avoid linker errors about undefined symbols.
  36. extern "C" char* if_indextoname(unsigned int, char*);
  37. extern "C" unsigned int if_nametoindex(const char*);
  38. #endif // defined(__hpux)
  39. inline void clear_last_error()
  40. {
  41. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  42. WSASetLastError(0);
  43. #else
  44. errno = 0;
  45. #endif
  46. }
  47. template <typename ReturnType>
  48. inline ReturnType error_wrapper(ReturnType return_value,
  49. boost::system::error_code& ec)
  50. {
  51. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  52. ec = boost::system::error_code(WSAGetLastError(),
  53. boost::asio::error::get_system_category());
  54. #else
  55. ec = boost::system::error_code(errno,
  56. boost::asio::error::get_system_category());
  57. #endif
  58. return return_value;
  59. }
  60. template <typename SockLenType>
  61. inline socket_type call_accept(SockLenType msghdr::*,
  62. socket_type s, socket_addr_type* addr, std::size_t* addrlen)
  63. {
  64. SockLenType tmp_addrlen = addrlen ? (SockLenType)*addrlen : 0;
  65. socket_type result = ::accept(s, addr, addrlen ? &tmp_addrlen : 0);
  66. if (addrlen)
  67. *addrlen = (std::size_t)tmp_addrlen;
  68. return result;
  69. }
  70. socket_type accept(socket_type s, socket_addr_type* addr,
  71. std::size_t* addrlen, boost::system::error_code& ec)
  72. {
  73. if (s == invalid_socket)
  74. {
  75. ec = boost::asio::error::bad_descriptor;
  76. return invalid_socket;
  77. }
  78. clear_last_error();
  79. socket_type new_s = error_wrapper(call_accept(
  80. &msghdr::msg_namelen, s, addr, addrlen), ec);
  81. if (new_s == invalid_socket)
  82. return new_s;
  83. #if defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
  84. int optval = 1;
  85. int result = error_wrapper(::setsockopt(new_s,
  86. SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)), ec);
  87. if (result != 0)
  88. {
  89. ::close(new_s);
  90. return invalid_socket;
  91. }
  92. #endif
  93. ec = boost::system::error_code();
  94. return new_s;
  95. }
  96. socket_type sync_accept(socket_type s, state_type state,
  97. socket_addr_type* addr, std::size_t* addrlen, boost::system::error_code& ec)
  98. {
  99. // Accept a socket.
  100. for (;;)
  101. {
  102. // Try to complete the operation without blocking.
  103. socket_type new_socket = socket_ops::accept(s, addr, addrlen, ec);
  104. // Check if operation succeeded.
  105. if (new_socket != invalid_socket)
  106. return new_socket;
  107. // Operation failed.
  108. if (ec == boost::asio::error::would_block
  109. || ec == boost::asio::error::try_again)
  110. {
  111. if (state & user_set_non_blocking)
  112. return invalid_socket;
  113. // Fall through to retry operation.
  114. }
  115. else if (ec == boost::asio::error::connection_aborted)
  116. {
  117. if (state & enable_connection_aborted)
  118. return invalid_socket;
  119. // Fall through to retry operation.
  120. }
  121. #if defined(EPROTO)
  122. else if (ec.value() == EPROTO)
  123. {
  124. if (state & enable_connection_aborted)
  125. return invalid_socket;
  126. // Fall through to retry operation.
  127. }
  128. #endif // defined(EPROTO)
  129. else
  130. return invalid_socket;
  131. // Wait for socket to become ready.
  132. if (socket_ops::poll_read(s, ec) < 0)
  133. return invalid_socket;
  134. }
  135. }
  136. #if defined(BOOST_ASIO_HAS_IOCP)
  137. void complete_iocp_accept(socket_type s,
  138. void* output_buffer, DWORD address_length,
  139. socket_addr_type* addr, std::size_t* addrlen,
  140. socket_type new_socket, boost::system::error_code& ec)
  141. {
  142. // Map non-portable errors to their portable counterparts.
  143. if (ec.value() == ERROR_NETNAME_DELETED)
  144. ec = boost::asio::error::connection_aborted;
  145. if (!ec)
  146. {
  147. // Get the address of the peer.
  148. if (addr && addrlen)
  149. {
  150. LPSOCKADDR local_addr = 0;
  151. int local_addr_length = 0;
  152. LPSOCKADDR remote_addr = 0;
  153. int remote_addr_length = 0;
  154. GetAcceptExSockaddrs(output_buffer, 0, address_length,
  155. address_length, &local_addr, &local_addr_length,
  156. &remote_addr, &remote_addr_length);
  157. if (static_cast<std::size_t>(remote_addr_length) > *addrlen)
  158. {
  159. ec = boost::asio::error::invalid_argument;
  160. }
  161. else
  162. {
  163. using namespace std; // For memcpy.
  164. memcpy(addr, remote_addr, remote_addr_length);
  165. *addrlen = static_cast<std::size_t>(remote_addr_length);
  166. }
  167. }
  168. // Need to set the SO_UPDATE_ACCEPT_CONTEXT option so that getsockname
  169. // and getpeername will work on the accepted socket.
  170. SOCKET update_ctx_param = s;
  171. socket_ops::state_type state = 0;
  172. socket_ops::setsockopt(new_socket, state,
  173. SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
  174. &update_ctx_param, sizeof(SOCKET), ec);
  175. }
  176. }
  177. #else // defined(BOOST_ASIO_HAS_IOCP)
  178. bool non_blocking_accept(socket_type s,
  179. state_type state, socket_addr_type* addr, std::size_t* addrlen,
  180. boost::system::error_code& ec, socket_type& new_socket)
  181. {
  182. for (;;)
  183. {
  184. // Accept the waiting connection.
  185. new_socket = socket_ops::accept(s, addr, addrlen, ec);
  186. // Check if operation succeeded.
  187. if (new_socket != invalid_socket)
  188. return true;
  189. // Retry operation if interrupted by signal.
  190. if (ec == boost::asio::error::interrupted)
  191. continue;
  192. // Operation failed.
  193. if (ec == boost::asio::error::would_block
  194. || ec == boost::asio::error::try_again)
  195. {
  196. if (state & user_set_non_blocking)
  197. return true;
  198. // Fall through to retry operation.
  199. }
  200. else if (ec == boost::asio::error::connection_aborted)
  201. {
  202. if (state & enable_connection_aborted)
  203. return true;
  204. // Fall through to retry operation.
  205. }
  206. #if defined(EPROTO)
  207. else if (ec.value() == EPROTO)
  208. {
  209. if (state & enable_connection_aborted)
  210. return true;
  211. // Fall through to retry operation.
  212. }
  213. #endif // defined(EPROTO)
  214. else
  215. return true;
  216. return false;
  217. }
  218. }
  219. #endif // defined(BOOST_ASIO_HAS_IOCP)
  220. template <typename SockLenType>
  221. inline int call_bind(SockLenType msghdr::*,
  222. socket_type s, const socket_addr_type* addr, std::size_t addrlen)
  223. {
  224. return ::bind(s, addr, (SockLenType)addrlen);
  225. }
  226. int bind(socket_type s, const socket_addr_type* addr,
  227. std::size_t addrlen, boost::system::error_code& ec)
  228. {
  229. if (s == invalid_socket)
  230. {
  231. ec = boost::asio::error::bad_descriptor;
  232. return socket_error_retval;
  233. }
  234. clear_last_error();
  235. int result = error_wrapper(call_bind(
  236. &msghdr::msg_namelen, s, addr, addrlen), ec);
  237. if (result == 0)
  238. ec = boost::system::error_code();
  239. return result;
  240. }
  241. int close(socket_type s, state_type& state,
  242. bool destruction, boost::system::error_code& ec)
  243. {
  244. int result = 0;
  245. if (s != invalid_socket)
  246. {
  247. // We don't want the destructor to block, so set the socket to linger in
  248. // the background. If the user doesn't like this behaviour then they need
  249. // to explicitly close the socket.
  250. if (destruction && (state & user_set_linger))
  251. {
  252. ::linger opt;
  253. opt.l_onoff = 0;
  254. opt.l_linger = 0;
  255. boost::system::error_code ignored_ec;
  256. socket_ops::setsockopt(s, state, SOL_SOCKET,
  257. SO_LINGER, &opt, sizeof(opt), ignored_ec);
  258. }
  259. clear_last_error();
  260. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  261. result = error_wrapper(::closesocket(s), ec);
  262. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  263. result = error_wrapper(::close(s), ec);
  264. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  265. if (result != 0
  266. && (ec == boost::asio::error::would_block
  267. || ec == boost::asio::error::try_again))
  268. {
  269. // According to UNIX Network Programming Vol. 1, it is possible for
  270. // close() to fail with EWOULDBLOCK under certain circumstances. What
  271. // isn't clear is the state of the descriptor after this error. The one
  272. // current OS where this behaviour is seen, Windows, says that the socket
  273. // remains open. Therefore we'll put the descriptor back into blocking
  274. // mode and have another attempt at closing it.
  275. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  276. ioctl_arg_type arg = 0;
  277. ::ioctlsocket(s, FIONBIO, &arg);
  278. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  279. # if defined(__SYMBIAN32__)
  280. int flags = ::fcntl(s, F_GETFL, 0);
  281. if (flags >= 0)
  282. ::fcntl(s, F_SETFL, flags & ~O_NONBLOCK);
  283. # else // defined(__SYMBIAN32__)
  284. ioctl_arg_type arg = 0;
  285. ::ioctl(s, FIONBIO, &arg);
  286. # endif // defined(__SYMBIAN32__)
  287. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  288. state &= ~non_blocking;
  289. clear_last_error();
  290. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  291. result = error_wrapper(::closesocket(s), ec);
  292. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  293. result = error_wrapper(::close(s), ec);
  294. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  295. }
  296. }
  297. if (result == 0)
  298. ec = boost::system::error_code();
  299. return result;
  300. }
  301. bool set_user_non_blocking(socket_type s,
  302. state_type& state, bool value, boost::system::error_code& ec)
  303. {
  304. if (s == invalid_socket)
  305. {
  306. ec = boost::asio::error::bad_descriptor;
  307. return false;
  308. }
  309. clear_last_error();
  310. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  311. ioctl_arg_type arg = (value ? 1 : 0);
  312. int result = error_wrapper(::ioctlsocket(s, FIONBIO, &arg), ec);
  313. #elif defined(__SYMBIAN32__)
  314. int result = error_wrapper(::fcntl(s, F_GETFL, 0), ec);
  315. if (result >= 0)
  316. {
  317. clear_last_error();
  318. int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
  319. result = error_wrapper(::fcntl(s, F_SETFL, flag), ec);
  320. }
  321. #else
  322. ioctl_arg_type arg = (value ? 1 : 0);
  323. int result = error_wrapper(::ioctl(s, FIONBIO, &arg), ec);
  324. #endif
  325. if (result >= 0)
  326. {
  327. ec = boost::system::error_code();
  328. if (value)
  329. state |= user_set_non_blocking;
  330. else
  331. {
  332. // Clearing the user-set non-blocking mode always overrides any
  333. // internally-set non-blocking flag. Any subsequent asynchronous
  334. // operations will need to re-enable non-blocking I/O.
  335. state &= ~(user_set_non_blocking | internal_non_blocking);
  336. }
  337. return true;
  338. }
  339. return false;
  340. }
  341. bool set_internal_non_blocking(socket_type s,
  342. state_type& state, bool value, boost::system::error_code& ec)
  343. {
  344. if (s == invalid_socket)
  345. {
  346. ec = boost::asio::error::bad_descriptor;
  347. return false;
  348. }
  349. if (!value && (state & user_set_non_blocking))
  350. {
  351. // It does not make sense to clear the internal non-blocking flag if the
  352. // user still wants non-blocking behaviour. Return an error and let the
  353. // caller figure out whether to update the user-set non-blocking flag.
  354. ec = boost::asio::error::invalid_argument;
  355. return false;
  356. }
  357. clear_last_error();
  358. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  359. ioctl_arg_type arg = (value ? 1 : 0);
  360. int result = error_wrapper(::ioctlsocket(s, FIONBIO, &arg), ec);
  361. #elif defined(__SYMBIAN32__)
  362. int result = error_wrapper(::fcntl(s, F_GETFL, 0), ec);
  363. if (result >= 0)
  364. {
  365. clear_last_error();
  366. int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
  367. result = error_wrapper(::fcntl(s, F_SETFL, flag), ec);
  368. }
  369. #else
  370. ioctl_arg_type arg = (value ? 1 : 0);
  371. int result = error_wrapper(::ioctl(s, FIONBIO, &arg), ec);
  372. #endif
  373. if (result >= 0)
  374. {
  375. ec = boost::system::error_code();
  376. if (value)
  377. state |= internal_non_blocking;
  378. else
  379. state &= ~internal_non_blocking;
  380. return true;
  381. }
  382. return false;
  383. }
  384. int shutdown(socket_type s, int what, boost::system::error_code& ec)
  385. {
  386. if (s == invalid_socket)
  387. {
  388. ec = boost::asio::error::bad_descriptor;
  389. return socket_error_retval;
  390. }
  391. clear_last_error();
  392. int result = error_wrapper(::shutdown(s, what), ec);
  393. if (result == 0)
  394. ec = boost::system::error_code();
  395. return result;
  396. }
  397. template <typename SockLenType>
  398. inline int call_connect(SockLenType msghdr::*,
  399. socket_type s, const socket_addr_type* addr, std::size_t addrlen)
  400. {
  401. return ::connect(s, addr, (SockLenType)addrlen);
  402. }
  403. int connect(socket_type s, const socket_addr_type* addr,
  404. std::size_t addrlen, boost::system::error_code& ec)
  405. {
  406. if (s == invalid_socket)
  407. {
  408. ec = boost::asio::error::bad_descriptor;
  409. return socket_error_retval;
  410. }
  411. clear_last_error();
  412. int result = error_wrapper(call_connect(
  413. &msghdr::msg_namelen, s, addr, addrlen), ec);
  414. if (result == 0)
  415. ec = boost::system::error_code();
  416. return result;
  417. }
  418. void sync_connect(socket_type s, const socket_addr_type* addr,
  419. std::size_t addrlen, boost::system::error_code& ec)
  420. {
  421. // Perform the connect operation.
  422. socket_ops::connect(s, addr, addrlen, ec);
  423. if (ec != boost::asio::error::in_progress
  424. && ec != boost::asio::error::would_block)
  425. {
  426. // The connect operation finished immediately.
  427. return;
  428. }
  429. // Wait for socket to become ready.
  430. if (socket_ops::poll_connect(s, ec) < 0)
  431. return;
  432. // Get the error code from the connect operation.
  433. int connect_error = 0;
  434. size_t connect_error_len = sizeof(connect_error);
  435. if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_ERROR,
  436. &connect_error, &connect_error_len, ec) == socket_error_retval)
  437. return;
  438. // Return the result of the connect operation.
  439. ec = boost::system::error_code(connect_error,
  440. boost::asio::error::get_system_category());
  441. }
  442. bool non_blocking_connect(socket_type s, boost::system::error_code& ec)
  443. {
  444. // Get the error code from the connect operation.
  445. int connect_error = 0;
  446. size_t connect_error_len = sizeof(connect_error);
  447. if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_ERROR,
  448. &connect_error, &connect_error_len, ec) == 0)
  449. {
  450. if (connect_error)
  451. {
  452. ec = boost::system::error_code(connect_error,
  453. boost::asio::error::get_system_category());
  454. }
  455. else
  456. ec = boost::system::error_code();
  457. }
  458. return true;
  459. }
  460. int socketpair(int af, int type, int protocol,
  461. socket_type sv[2], boost::system::error_code& ec)
  462. {
  463. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  464. (void)(af);
  465. (void)(type);
  466. (void)(protocol);
  467. (void)(sv);
  468. ec = boost::asio::error::operation_not_supported;
  469. return socket_error_retval;
  470. #else
  471. clear_last_error();
  472. int result = error_wrapper(::socketpair(af, type, protocol, sv), ec);
  473. if (result == 0)
  474. ec = boost::system::error_code();
  475. return result;
  476. #endif
  477. }
  478. bool sockatmark(socket_type s, boost::system::error_code& ec)
  479. {
  480. if (s == invalid_socket)
  481. {
  482. ec = boost::asio::error::bad_descriptor;
  483. return false;
  484. }
  485. #if defined(SIOCATMARK)
  486. ioctl_arg_type value = 0;
  487. # if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  488. int result = error_wrapper(::ioctlsocket(s, SIOCATMARK, &value), ec);
  489. # else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  490. int result = error_wrapper(::ioctl(s, SIOCATMARK, &value), ec);
  491. # endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  492. if (result == 0)
  493. ec = boost::system::error_code();
  494. # if defined(ENOTTY)
  495. if (ec.value() == ENOTTY)
  496. ec = boost::asio::error::not_socket;
  497. # endif // defined(ENOTTY)
  498. #else // defined(SIOCATMARK)
  499. int value = error_wrapper(::sockatmark(s), ec);
  500. if (value != -1)
  501. ec = boost::system::error_code();
  502. #endif // defined(SIOCATMARK)
  503. return ec ? false : value != 0;
  504. }
  505. size_t available(socket_type s, boost::system::error_code& ec)
  506. {
  507. if (s == invalid_socket)
  508. {
  509. ec = boost::asio::error::bad_descriptor;
  510. return 0;
  511. }
  512. ioctl_arg_type value = 0;
  513. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  514. int result = error_wrapper(::ioctlsocket(s, FIONREAD, &value), ec);
  515. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  516. int result = error_wrapper(::ioctl(s, FIONREAD, &value), ec);
  517. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  518. if (result == 0)
  519. ec = boost::system::error_code();
  520. #if defined(ENOTTY)
  521. if (ec.value() == ENOTTY)
  522. ec = boost::asio::error::not_socket;
  523. #endif // defined(ENOTTY)
  524. return ec ? static_cast<size_t>(0) : static_cast<size_t>(value);
  525. }
  526. int listen(socket_type s, int backlog, boost::system::error_code& ec)
  527. {
  528. if (s == invalid_socket)
  529. {
  530. ec = boost::asio::error::bad_descriptor;
  531. return socket_error_retval;
  532. }
  533. clear_last_error();
  534. int result = error_wrapper(::listen(s, backlog), ec);
  535. if (result == 0)
  536. ec = boost::system::error_code();
  537. return result;
  538. }
  539. inline void init_buf_iov_base(void*& base, void* addr)
  540. {
  541. base = addr;
  542. }
  543. template <typename T>
  544. inline void init_buf_iov_base(T& base, void* addr)
  545. {
  546. base = static_cast<T>(addr);
  547. }
  548. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  549. typedef WSABUF buf;
  550. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  551. typedef iovec buf;
  552. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  553. void init_buf(buf& b, void* data, size_t size)
  554. {
  555. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  556. b.buf = static_cast<char*>(data);
  557. b.len = static_cast<u_long>(size);
  558. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  559. init_buf_iov_base(b.iov_base, data);
  560. b.iov_len = size;
  561. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  562. }
  563. void init_buf(buf& b, const void* data, size_t size)
  564. {
  565. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  566. b.buf = static_cast<char*>(const_cast<void*>(data));
  567. b.len = static_cast<u_long>(size);
  568. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  569. init_buf_iov_base(b.iov_base, const_cast<void*>(data));
  570. b.iov_len = size;
  571. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  572. }
  573. inline void init_msghdr_msg_name(void*& name, socket_addr_type* addr)
  574. {
  575. name = addr;
  576. }
  577. inline void init_msghdr_msg_name(void*& name, const socket_addr_type* addr)
  578. {
  579. name = const_cast<socket_addr_type*>(addr);
  580. }
  581. template <typename T>
  582. inline void init_msghdr_msg_name(T& name, socket_addr_type* addr)
  583. {
  584. name = reinterpret_cast<T>(addr);
  585. }
  586. template <typename T>
  587. inline void init_msghdr_msg_name(T& name, const socket_addr_type* addr)
  588. {
  589. name = reinterpret_cast<T>(const_cast<socket_addr_type*>(addr));
  590. }
  591. int recv(socket_type s, buf* bufs, size_t count, int flags,
  592. boost::system::error_code& ec)
  593. {
  594. clear_last_error();
  595. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  596. // Receive some data.
  597. DWORD recv_buf_count = static_cast<DWORD>(count);
  598. DWORD bytes_transferred = 0;
  599. DWORD recv_flags = flags;
  600. int result = error_wrapper(::WSARecv(s, bufs,
  601. recv_buf_count, &bytes_transferred, &recv_flags, 0, 0), ec);
  602. if (ec.value() == ERROR_NETNAME_DELETED)
  603. ec = boost::asio::error::connection_reset;
  604. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  605. ec = boost::asio::error::connection_refused;
  606. if (result != 0)
  607. return socket_error_retval;
  608. ec = boost::system::error_code();
  609. return bytes_transferred;
  610. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  611. msghdr msg = msghdr();
  612. msg.msg_iov = bufs;
  613. msg.msg_iovlen = count;
  614. int result = error_wrapper(::recvmsg(s, &msg, flags), ec);
  615. if (result >= 0)
  616. ec = boost::system::error_code();
  617. return result;
  618. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  619. }
  620. size_t sync_recv(socket_type s, state_type state, buf* bufs,
  621. size_t count, int flags, bool all_empty, boost::system::error_code& ec)
  622. {
  623. if (s == invalid_socket)
  624. {
  625. ec = boost::asio::error::bad_descriptor;
  626. return 0;
  627. }
  628. // A request to read 0 bytes on a stream is a no-op.
  629. if (all_empty && (state & stream_oriented))
  630. {
  631. ec = boost::system::error_code();
  632. return 0;
  633. }
  634. // Read some data.
  635. for (;;)
  636. {
  637. // Try to complete the operation without blocking.
  638. int bytes = socket_ops::recv(s, bufs, count, flags, ec);
  639. // Check if operation succeeded.
  640. if (bytes > 0)
  641. return bytes;
  642. // Check for EOF.
  643. if ((state & stream_oriented) && bytes == 0)
  644. {
  645. ec = boost::asio::error::eof;
  646. return 0;
  647. }
  648. // Operation failed.
  649. if ((state & user_set_non_blocking)
  650. || (ec != boost::asio::error::would_block
  651. && ec != boost::asio::error::try_again))
  652. return 0;
  653. // Wait for socket to become ready.
  654. if (socket_ops::poll_read(s, ec) < 0)
  655. return 0;
  656. }
  657. }
  658. #if defined(BOOST_ASIO_HAS_IOCP)
  659. void complete_iocp_recv(state_type state,
  660. const weak_cancel_token_type& cancel_token, bool all_empty,
  661. boost::system::error_code& ec, size_t bytes_transferred)
  662. {
  663. // Map non-portable errors to their portable counterparts.
  664. if (ec.value() == ERROR_NETNAME_DELETED)
  665. {
  666. if (cancel_token.expired())
  667. ec = boost::asio::error::operation_aborted;
  668. else
  669. ec = boost::asio::error::connection_reset;
  670. }
  671. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  672. {
  673. ec = boost::asio::error::connection_refused;
  674. }
  675. // Check for connection closed.
  676. else if (!ec && bytes_transferred == 0
  677. && (state & stream_oriented) != 0
  678. && !all_empty)
  679. {
  680. ec = boost::asio::error::eof;
  681. }
  682. }
  683. #else // defined(BOOST_ASIO_HAS_IOCP)
  684. bool non_blocking_recv(socket_type s,
  685. buf* bufs, size_t count, int flags, bool is_stream,
  686. boost::system::error_code& ec, size_t& bytes_transferred)
  687. {
  688. for (;;)
  689. {
  690. // Read some data.
  691. int bytes = socket_ops::recv(s, bufs, count, flags, ec);
  692. // Check for end of stream.
  693. if (is_stream && bytes == 0)
  694. {
  695. ec = boost::asio::error::eof;
  696. return true;
  697. }
  698. // Retry operation if interrupted by signal.
  699. if (ec == boost::asio::error::interrupted)
  700. continue;
  701. // Check if we need to run the operation again.
  702. if (ec == boost::asio::error::would_block
  703. || ec == boost::asio::error::try_again)
  704. return false;
  705. // Operation is complete.
  706. if (bytes >= 0)
  707. {
  708. ec = boost::system::error_code();
  709. bytes_transferred = bytes;
  710. }
  711. else
  712. bytes_transferred = 0;
  713. return true;
  714. }
  715. }
  716. #endif // defined(BOOST_ASIO_HAS_IOCP)
  717. int recvfrom(socket_type s, buf* bufs, size_t count, int flags,
  718. socket_addr_type* addr, std::size_t* addrlen,
  719. boost::system::error_code& ec)
  720. {
  721. clear_last_error();
  722. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  723. // Receive some data.
  724. DWORD recv_buf_count = static_cast<DWORD>(count);
  725. DWORD bytes_transferred = 0;
  726. DWORD recv_flags = flags;
  727. int tmp_addrlen = (int)*addrlen;
  728. int result = error_wrapper(::WSARecvFrom(s, bufs, recv_buf_count,
  729. &bytes_transferred, &recv_flags, addr, &tmp_addrlen, 0, 0), ec);
  730. *addrlen = (std::size_t)tmp_addrlen;
  731. if (ec.value() == ERROR_NETNAME_DELETED)
  732. ec = boost::asio::error::connection_reset;
  733. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  734. ec = boost::asio::error::connection_refused;
  735. if (result != 0)
  736. return socket_error_retval;
  737. ec = boost::system::error_code();
  738. return bytes_transferred;
  739. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  740. msghdr msg = msghdr();
  741. init_msghdr_msg_name(msg.msg_name, addr);
  742. msg.msg_namelen = *addrlen;
  743. msg.msg_iov = bufs;
  744. msg.msg_iovlen = count;
  745. int result = error_wrapper(::recvmsg(s, &msg, flags), ec);
  746. *addrlen = msg.msg_namelen;
  747. if (result >= 0)
  748. ec = boost::system::error_code();
  749. return result;
  750. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  751. }
  752. size_t sync_recvfrom(socket_type s, state_type state, buf* bufs,
  753. size_t count, int flags, socket_addr_type* addr,
  754. std::size_t* addrlen, boost::system::error_code& ec)
  755. {
  756. if (s == invalid_socket)
  757. {
  758. ec = boost::asio::error::bad_descriptor;
  759. return 0;
  760. }
  761. // Read some data.
  762. for (;;)
  763. {
  764. // Try to complete the operation without blocking.
  765. int bytes = socket_ops::recvfrom(s, bufs, count, flags, addr, addrlen, ec);
  766. // Check if operation succeeded.
  767. if (bytes >= 0)
  768. return bytes;
  769. // Operation failed.
  770. if ((state & user_set_non_blocking)
  771. || (ec != boost::asio::error::would_block
  772. && ec != boost::asio::error::try_again))
  773. return 0;
  774. // Wait for socket to become ready.
  775. if (socket_ops::poll_read(s, ec) < 0)
  776. return 0;
  777. }
  778. }
  779. #if defined(BOOST_ASIO_HAS_IOCP)
  780. void complete_iocp_recvfrom(
  781. const weak_cancel_token_type& cancel_token,
  782. boost::system::error_code& ec)
  783. {
  784. // Map non-portable errors to their portable counterparts.
  785. if (ec.value() == ERROR_NETNAME_DELETED)
  786. {
  787. if (cancel_token.expired())
  788. ec = boost::asio::error::operation_aborted;
  789. else
  790. ec = boost::asio::error::connection_reset;
  791. }
  792. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  793. {
  794. ec = boost::asio::error::connection_refused;
  795. }
  796. }
  797. #else // defined(BOOST_ASIO_HAS_IOCP)
  798. bool non_blocking_recvfrom(socket_type s,
  799. buf* bufs, size_t count, int flags,
  800. socket_addr_type* addr, std::size_t* addrlen,
  801. boost::system::error_code& ec, size_t& bytes_transferred)
  802. {
  803. for (;;)
  804. {
  805. // Read some data.
  806. int bytes = socket_ops::recvfrom(s, bufs, count, flags, addr, addrlen, ec);
  807. // Retry operation if interrupted by signal.
  808. if (ec == boost::asio::error::interrupted)
  809. continue;
  810. // Check if we need to run the operation again.
  811. if (ec == boost::asio::error::would_block
  812. || ec == boost::asio::error::try_again)
  813. return false;
  814. // Operation is complete.
  815. if (bytes >= 0)
  816. {
  817. ec = boost::system::error_code();
  818. bytes_transferred = bytes;
  819. }
  820. else
  821. bytes_transferred = 0;
  822. return true;
  823. }
  824. }
  825. #endif // defined(BOOST_ASIO_HAS_IOCP)
  826. int recvmsg(socket_type s, buf* bufs, size_t count,
  827. int in_flags, int& out_flags, boost::system::error_code& ec)
  828. {
  829. clear_last_error();
  830. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  831. out_flags = 0;
  832. return socket_ops::recv(s, bufs, count, in_flags, ec);
  833. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  834. msghdr msg = msghdr();
  835. msg.msg_iov = bufs;
  836. msg.msg_iovlen = count;
  837. int result = error_wrapper(::recvmsg(s, &msg, in_flags), ec);
  838. if (result >= 0)
  839. {
  840. ec = boost::system::error_code();
  841. out_flags = msg.msg_flags;
  842. }
  843. else
  844. out_flags = 0;
  845. return result;
  846. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  847. }
  848. size_t sync_recvmsg(socket_type s, state_type state,
  849. buf* bufs, size_t count, int in_flags, int& out_flags,
  850. boost::system::error_code& ec)
  851. {
  852. if (s == invalid_socket)
  853. {
  854. ec = boost::asio::error::bad_descriptor;
  855. return 0;
  856. }
  857. // Read some data.
  858. for (;;)
  859. {
  860. // Try to complete the operation without blocking.
  861. int bytes = socket_ops::recvmsg(s, bufs, count, in_flags, out_flags, ec);
  862. // Check if operation succeeded.
  863. if (bytes >= 0)
  864. return bytes;
  865. // Operation failed.
  866. if ((state & user_set_non_blocking)
  867. || (ec != boost::asio::error::would_block
  868. && ec != boost::asio::error::try_again))
  869. return 0;
  870. // Wait for socket to become ready.
  871. if (socket_ops::poll_read(s, ec) < 0)
  872. return 0;
  873. }
  874. }
  875. #if defined(BOOST_ASIO_HAS_IOCP)
  876. void complete_iocp_recvmsg(
  877. const weak_cancel_token_type& cancel_token,
  878. boost::system::error_code& ec)
  879. {
  880. // Map non-portable errors to their portable counterparts.
  881. if (ec.value() == ERROR_NETNAME_DELETED)
  882. {
  883. if (cancel_token.expired())
  884. ec = boost::asio::error::operation_aborted;
  885. else
  886. ec = boost::asio::error::connection_reset;
  887. }
  888. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  889. {
  890. ec = boost::asio::error::connection_refused;
  891. }
  892. }
  893. #else // defined(BOOST_ASIO_HAS_IOCP)
  894. bool non_blocking_recvmsg(socket_type s,
  895. buf* bufs, size_t count, int in_flags, int& out_flags,
  896. boost::system::error_code& ec, size_t& bytes_transferred)
  897. {
  898. for (;;)
  899. {
  900. // Read some data.
  901. int bytes = socket_ops::recvmsg(s, bufs, count, in_flags, out_flags, ec);
  902. // Retry operation if interrupted by signal.
  903. if (ec == boost::asio::error::interrupted)
  904. continue;
  905. // Check if we need to run the operation again.
  906. if (ec == boost::asio::error::would_block
  907. || ec == boost::asio::error::try_again)
  908. return false;
  909. // Operation is complete.
  910. if (bytes >= 0)
  911. {
  912. ec = boost::system::error_code();
  913. bytes_transferred = bytes;
  914. }
  915. else
  916. bytes_transferred = 0;
  917. return true;
  918. }
  919. }
  920. #endif // defined(BOOST_ASIO_HAS_IOCP)
  921. int send(socket_type s, const buf* bufs, size_t count, int flags,
  922. boost::system::error_code& ec)
  923. {
  924. clear_last_error();
  925. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  926. // Send the data.
  927. DWORD send_buf_count = static_cast<DWORD>(count);
  928. DWORD bytes_transferred = 0;
  929. DWORD send_flags = flags;
  930. int result = error_wrapper(::WSASend(s, const_cast<buf*>(bufs),
  931. send_buf_count, &bytes_transferred, send_flags, 0, 0), ec);
  932. if (ec.value() == ERROR_NETNAME_DELETED)
  933. ec = boost::asio::error::connection_reset;
  934. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  935. ec = boost::asio::error::connection_refused;
  936. if (result != 0)
  937. return socket_error_retval;
  938. ec = boost::system::error_code();
  939. return bytes_transferred;
  940. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  941. msghdr msg = msghdr();
  942. msg.msg_iov = const_cast<buf*>(bufs);
  943. msg.msg_iovlen = count;
  944. #if defined(__linux__)
  945. flags |= MSG_NOSIGNAL;
  946. #endif // defined(__linux__)
  947. int result = error_wrapper(::sendmsg(s, &msg, flags), ec);
  948. if (result >= 0)
  949. ec = boost::system::error_code();
  950. return result;
  951. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  952. }
  953. size_t sync_send(socket_type s, state_type state, const buf* bufs,
  954. size_t count, int flags, bool all_empty, boost::system::error_code& ec)
  955. {
  956. if (s == invalid_socket)
  957. {
  958. ec = boost::asio::error::bad_descriptor;
  959. return 0;
  960. }
  961. // A request to write 0 bytes to a stream is a no-op.
  962. if (all_empty && (state & stream_oriented))
  963. {
  964. ec = boost::system::error_code();
  965. return 0;
  966. }
  967. // Read some data.
  968. for (;;)
  969. {
  970. // Try to complete the operation without blocking.
  971. int bytes = socket_ops::send(s, bufs, count, flags, ec);
  972. // Check if operation succeeded.
  973. if (bytes >= 0)
  974. return bytes;
  975. // Operation failed.
  976. if ((state & user_set_non_blocking)
  977. || (ec != boost::asio::error::would_block
  978. && ec != boost::asio::error::try_again))
  979. return 0;
  980. // Wait for socket to become ready.
  981. if (socket_ops::poll_write(s, ec) < 0)
  982. return 0;
  983. }
  984. }
  985. #if defined(BOOST_ASIO_HAS_IOCP)
  986. void complete_iocp_send(
  987. const weak_cancel_token_type& cancel_token,
  988. boost::system::error_code& ec)
  989. {
  990. // Map non-portable errors to their portable counterparts.
  991. if (ec.value() == ERROR_NETNAME_DELETED)
  992. {
  993. if (cancel_token.expired())
  994. ec = boost::asio::error::operation_aborted;
  995. else
  996. ec = boost::asio::error::connection_reset;
  997. }
  998. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  999. {
  1000. ec = boost::asio::error::connection_refused;
  1001. }
  1002. }
  1003. #else // defined(BOOST_ASIO_HAS_IOCP)
  1004. bool non_blocking_send(socket_type s,
  1005. const buf* bufs, size_t count, int flags,
  1006. boost::system::error_code& ec, size_t& bytes_transferred)
  1007. {
  1008. for (;;)
  1009. {
  1010. // Write some data.
  1011. int bytes = socket_ops::send(s, bufs, count, flags, ec);
  1012. // Retry operation if interrupted by signal.
  1013. if (ec == boost::asio::error::interrupted)
  1014. continue;
  1015. // Check if we need to run the operation again.
  1016. if (ec == boost::asio::error::would_block
  1017. || ec == boost::asio::error::try_again)
  1018. return false;
  1019. // Operation is complete.
  1020. if (bytes >= 0)
  1021. {
  1022. ec = boost::system::error_code();
  1023. bytes_transferred = bytes;
  1024. }
  1025. else
  1026. bytes_transferred = 0;
  1027. return true;
  1028. }
  1029. }
  1030. #endif // defined(BOOST_ASIO_HAS_IOCP)
  1031. int sendto(socket_type s, const buf* bufs, size_t count, int flags,
  1032. const socket_addr_type* addr, std::size_t addrlen,
  1033. boost::system::error_code& ec)
  1034. {
  1035. clear_last_error();
  1036. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1037. // Send the data.
  1038. DWORD send_buf_count = static_cast<DWORD>(count);
  1039. DWORD bytes_transferred = 0;
  1040. int result = error_wrapper(::WSASendTo(s, const_cast<buf*>(bufs),
  1041. send_buf_count, &bytes_transferred, flags, addr,
  1042. static_cast<int>(addrlen), 0, 0), ec);
  1043. if (ec.value() == ERROR_NETNAME_DELETED)
  1044. ec = boost::asio::error::connection_reset;
  1045. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1046. ec = boost::asio::error::connection_refused;
  1047. if (result != 0)
  1048. return socket_error_retval;
  1049. ec = boost::system::error_code();
  1050. return bytes_transferred;
  1051. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1052. msghdr msg = msghdr();
  1053. init_msghdr_msg_name(msg.msg_name, addr);
  1054. msg.msg_namelen = addrlen;
  1055. msg.msg_iov = const_cast<buf*>(bufs);
  1056. msg.msg_iovlen = count;
  1057. #if defined(__linux__)
  1058. flags |= MSG_NOSIGNAL;
  1059. #endif // defined(__linux__)
  1060. int result = error_wrapper(::sendmsg(s, &msg, flags), ec);
  1061. if (result >= 0)
  1062. ec = boost::system::error_code();
  1063. return result;
  1064. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1065. }
  1066. size_t sync_sendto(socket_type s, state_type state, const buf* bufs,
  1067. size_t count, int flags, const socket_addr_type* addr,
  1068. std::size_t addrlen, boost::system::error_code& ec)
  1069. {
  1070. if (s == invalid_socket)
  1071. {
  1072. ec = boost::asio::error::bad_descriptor;
  1073. return 0;
  1074. }
  1075. // Write some data.
  1076. for (;;)
  1077. {
  1078. // Try to complete the operation without blocking.
  1079. int bytes = socket_ops::sendto(s, bufs, count, flags, addr, addrlen, ec);
  1080. // Check if operation succeeded.
  1081. if (bytes >= 0)
  1082. return bytes;
  1083. // Operation failed.
  1084. if ((state & user_set_non_blocking)
  1085. || (ec != boost::asio::error::would_block
  1086. && ec != boost::asio::error::try_again))
  1087. return 0;
  1088. // Wait for socket to become ready.
  1089. if (socket_ops::poll_write(s, ec) < 0)
  1090. return 0;
  1091. }
  1092. }
  1093. #if !defined(BOOST_ASIO_HAS_IOCP)
  1094. bool non_blocking_sendto(socket_type s,
  1095. const buf* bufs, size_t count, int flags,
  1096. const socket_addr_type* addr, std::size_t addrlen,
  1097. boost::system::error_code& ec, size_t& bytes_transferred)
  1098. {
  1099. for (;;)
  1100. {
  1101. // Write some data.
  1102. int bytes = socket_ops::sendto(s, bufs, count, flags, addr, addrlen, ec);
  1103. // Retry operation if interrupted by signal.
  1104. if (ec == boost::asio::error::interrupted)
  1105. continue;
  1106. // Check if we need to run the operation again.
  1107. if (ec == boost::asio::error::would_block
  1108. || ec == boost::asio::error::try_again)
  1109. return false;
  1110. // Operation is complete.
  1111. if (bytes >= 0)
  1112. {
  1113. ec = boost::system::error_code();
  1114. bytes_transferred = bytes;
  1115. }
  1116. else
  1117. bytes_transferred = 0;
  1118. return true;
  1119. }
  1120. }
  1121. #endif // !defined(BOOST_ASIO_HAS_IOCP)
  1122. socket_type socket(int af, int type, int protocol,
  1123. boost::system::error_code& ec)
  1124. {
  1125. clear_last_error();
  1126. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1127. socket_type s = error_wrapper(::WSASocket(af, type, protocol, 0, 0,
  1128. WSA_FLAG_OVERLAPPED), ec);
  1129. if (s == invalid_socket)
  1130. return s;
  1131. if (af == AF_INET6)
  1132. {
  1133. // Try to enable the POSIX default behaviour of having IPV6_V6ONLY set to
  1134. // false. This will only succeed on Windows Vista and later versions of
  1135. // Windows, where a dual-stack IPv4/v6 implementation is available.
  1136. DWORD optval = 0;
  1137. ::setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
  1138. reinterpret_cast<const char*>(&optval), sizeof(optval));
  1139. }
  1140. ec = boost::system::error_code();
  1141. return s;
  1142. #elif defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
  1143. socket_type s = error_wrapper(::socket(af, type, protocol), ec);
  1144. if (s == invalid_socket)
  1145. return s;
  1146. int optval = 1;
  1147. int result = error_wrapper(::setsockopt(s,
  1148. SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)), ec);
  1149. if (result != 0)
  1150. {
  1151. ::close(s);
  1152. return invalid_socket;
  1153. }
  1154. return s;
  1155. #else
  1156. int s = error_wrapper(::socket(af, type, protocol), ec);
  1157. if (s >= 0)
  1158. ec = boost::system::error_code();
  1159. return s;
  1160. #endif
  1161. }
  1162. template <typename SockLenType>
  1163. inline int call_setsockopt(SockLenType msghdr::*,
  1164. socket_type s, int level, int optname,
  1165. const void* optval, std::size_t optlen)
  1166. {
  1167. return ::setsockopt(s, level, optname,
  1168. (const char*)optval, (SockLenType)optlen);
  1169. }
  1170. int setsockopt(socket_type s, state_type& state, int level, int optname,
  1171. const void* optval, std::size_t optlen, boost::system::error_code& ec)
  1172. {
  1173. if (s == invalid_socket)
  1174. {
  1175. ec = boost::asio::error::bad_descriptor;
  1176. return socket_error_retval;
  1177. }
  1178. if (level == custom_socket_option_level && optname == always_fail_option)
  1179. {
  1180. ec = boost::asio::error::invalid_argument;
  1181. return socket_error_retval;
  1182. }
  1183. if (level == custom_socket_option_level
  1184. && optname == enable_connection_aborted_option)
  1185. {
  1186. if (optlen != sizeof(int))
  1187. {
  1188. ec = boost::asio::error::invalid_argument;
  1189. return socket_error_retval;
  1190. }
  1191. if (*static_cast<const int*>(optval))
  1192. state |= enable_connection_aborted;
  1193. else
  1194. state &= ~enable_connection_aborted;
  1195. ec = boost::system::error_code();
  1196. return 0;
  1197. }
  1198. if (level == SOL_SOCKET && optname == SO_LINGER)
  1199. state |= user_set_linger;
  1200. #if defined(__BORLANDC__)
  1201. // Mysteriously, using the getsockopt and setsockopt functions directly with
  1202. // Borland C++ results in incorrect values being set and read. The bug can be
  1203. // worked around by using function addresses resolved with GetProcAddress.
  1204. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  1205. {
  1206. typedef int (WSAAPI *sso_t)(SOCKET, int, int, const char*, int);
  1207. if (sso_t sso = (sso_t)::GetProcAddress(winsock_module, "setsockopt"))
  1208. {
  1209. clear_last_error();
  1210. return error_wrapper(sso(s, level, optname,
  1211. reinterpret_cast<const char*>(optval),
  1212. static_cast<int>(optlen)), ec);
  1213. }
  1214. }
  1215. ec = boost::asio::error::fault;
  1216. return socket_error_retval;
  1217. #else // defined(__BORLANDC__)
  1218. clear_last_error();
  1219. int result = error_wrapper(call_setsockopt(&msghdr::msg_namelen,
  1220. s, level, optname, optval, optlen), ec);
  1221. if (result == 0)
  1222. {
  1223. ec = boost::system::error_code();
  1224. #if defined(__MACH__) && defined(__APPLE__) \
  1225. || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
  1226. // To implement portable behaviour for SO_REUSEADDR with UDP sockets we
  1227. // need to also set SO_REUSEPORT on BSD-based platforms.
  1228. if ((state & datagram_oriented)
  1229. && level == SOL_SOCKET && optname == SO_REUSEADDR)
  1230. {
  1231. call_setsockopt(&msghdr::msg_namelen, s,
  1232. SOL_SOCKET, SO_REUSEPORT, optval, optlen);
  1233. }
  1234. #endif
  1235. }
  1236. return result;
  1237. #endif // defined(__BORLANDC__)
  1238. }
  1239. template <typename SockLenType>
  1240. inline int call_getsockopt(SockLenType msghdr::*,
  1241. socket_type s, int level, int optname,
  1242. void* optval, std::size_t* optlen)
  1243. {
  1244. SockLenType tmp_optlen = (SockLenType)*optlen;
  1245. int result = ::getsockopt(s, level, optname, (char*)optval, &tmp_optlen);
  1246. *optlen = (std::size_t)tmp_optlen;
  1247. return result;
  1248. }
  1249. int getsockopt(socket_type s, state_type state, int level, int optname,
  1250. void* optval, size_t* optlen, boost::system::error_code& ec)
  1251. {
  1252. if (s == invalid_socket)
  1253. {
  1254. ec = boost::asio::error::bad_descriptor;
  1255. return socket_error_retval;
  1256. }
  1257. if (level == custom_socket_option_level && optname == always_fail_option)
  1258. {
  1259. ec = boost::asio::error::invalid_argument;
  1260. return socket_error_retval;
  1261. }
  1262. if (level == custom_socket_option_level
  1263. && optname == enable_connection_aborted_option)
  1264. {
  1265. if (*optlen != sizeof(int))
  1266. {
  1267. ec = boost::asio::error::invalid_argument;
  1268. return socket_error_retval;
  1269. }
  1270. *static_cast<int*>(optval) = (state & enable_connection_aborted) ? 1 : 0;
  1271. ec = boost::system::error_code();
  1272. return 0;
  1273. }
  1274. #if defined(__BORLANDC__)
  1275. // Mysteriously, using the getsockopt and setsockopt functions directly with
  1276. // Borland C++ results in incorrect values being set and read. The bug can be
  1277. // worked around by using function addresses resolved with GetProcAddress.
  1278. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  1279. {
  1280. typedef int (WSAAPI *gso_t)(SOCKET, int, int, char*, int*);
  1281. if (gso_t gso = (gso_t)::GetProcAddress(winsock_module, "getsockopt"))
  1282. {
  1283. clear_last_error();
  1284. int tmp_optlen = static_cast<int>(*optlen);
  1285. int result = error_wrapper(gso(s, level, optname,
  1286. reinterpret_cast<char*>(optval), &tmp_optlen), ec);
  1287. *optlen = static_cast<size_t>(tmp_optlen);
  1288. if (result != 0 && level == IPPROTO_IPV6 && optname == IPV6_V6ONLY
  1289. && ec.value() == WSAENOPROTOOPT && *optlen == sizeof(DWORD))
  1290. {
  1291. // Dual-stack IPv4/v6 sockets, and the IPV6_V6ONLY socket option, are
  1292. // only supported on Windows Vista and later. To simplify program logic
  1293. // we will fake success of getting this option and specify that the
  1294. // value is non-zero (i.e. true). This corresponds to the behavior of
  1295. // IPv6 sockets on Windows platforms pre-Vista.
  1296. *static_cast<DWORD*>(optval) = 1;
  1297. ec = boost::system::error_code();
  1298. }
  1299. return result;
  1300. }
  1301. }
  1302. ec = boost::asio::error::fault;
  1303. return socket_error_retval;
  1304. #elif defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1305. clear_last_error();
  1306. int result = error_wrapper(call_getsockopt(&msghdr::msg_namelen,
  1307. s, level, optname, optval, optlen), ec);
  1308. if (result != 0 && level == IPPROTO_IPV6 && optname == IPV6_V6ONLY
  1309. && ec.value() == WSAENOPROTOOPT && *optlen == sizeof(DWORD))
  1310. {
  1311. // Dual-stack IPv4/v6 sockets, and the IPV6_V6ONLY socket option, are only
  1312. // supported on Windows Vista and later. To simplify program logic we will
  1313. // fake success of getting this option and specify that the value is
  1314. // non-zero (i.e. true). This corresponds to the behavior of IPv6 sockets
  1315. // on Windows platforms pre-Vista.
  1316. *static_cast<DWORD*>(optval) = 1;
  1317. ec = boost::system::error_code();
  1318. }
  1319. if (result == 0)
  1320. ec = boost::system::error_code();
  1321. return result;
  1322. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1323. clear_last_error();
  1324. int result = error_wrapper(call_getsockopt(&msghdr::msg_namelen,
  1325. s, level, optname, optval, optlen), ec);
  1326. #if defined(__linux__)
  1327. if (result == 0 && level == SOL_SOCKET && *optlen == sizeof(int)
  1328. && (optname == SO_SNDBUF || optname == SO_RCVBUF))
  1329. {
  1330. // On Linux, setting SO_SNDBUF or SO_RCVBUF to N actually causes the kernel
  1331. // to set the buffer size to N*2. Linux puts additional stuff into the
  1332. // buffers so that only about half is actually available to the application.
  1333. // The retrieved value is divided by 2 here to make it appear as though the
  1334. // correct value has been set.
  1335. *static_cast<int*>(optval) /= 2;
  1336. }
  1337. #endif // defined(__linux__)
  1338. if (result == 0)
  1339. ec = boost::system::error_code();
  1340. return result;
  1341. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1342. }
  1343. template <typename SockLenType>
  1344. inline int call_getpeername(SockLenType msghdr::*,
  1345. socket_type s, socket_addr_type* addr, std::size_t* addrlen)
  1346. {
  1347. SockLenType tmp_addrlen = (SockLenType)*addrlen;
  1348. int result = ::getpeername(s, addr, &tmp_addrlen);
  1349. *addrlen = (std::size_t)tmp_addrlen;
  1350. return result;
  1351. }
  1352. int getpeername(socket_type s, socket_addr_type* addr,
  1353. std::size_t* addrlen, bool cached, boost::system::error_code& ec)
  1354. {
  1355. if (s == invalid_socket)
  1356. {
  1357. ec = boost::asio::error::bad_descriptor;
  1358. return socket_error_retval;
  1359. }
  1360. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1361. if (cached)
  1362. {
  1363. // Check if socket is still connected.
  1364. DWORD connect_time = 0;
  1365. size_t connect_time_len = sizeof(connect_time);
  1366. if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_CONNECT_TIME,
  1367. &connect_time, &connect_time_len, ec) == socket_error_retval)
  1368. {
  1369. return socket_error_retval;
  1370. }
  1371. if (connect_time == 0xFFFFFFFF)
  1372. {
  1373. ec = boost::asio::error::not_connected;
  1374. return socket_error_retval;
  1375. }
  1376. // The cached value is still valid.
  1377. ec = boost::system::error_code();
  1378. return 0;
  1379. }
  1380. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1381. (void)cached;
  1382. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1383. clear_last_error();
  1384. int result = error_wrapper(call_getpeername(
  1385. &msghdr::msg_namelen, s, addr, addrlen), ec);
  1386. if (result == 0)
  1387. ec = boost::system::error_code();
  1388. return result;
  1389. }
  1390. template <typename SockLenType>
  1391. inline int call_getsockname(SockLenType msghdr::*,
  1392. socket_type s, socket_addr_type* addr, std::size_t* addrlen)
  1393. {
  1394. SockLenType tmp_addrlen = (SockLenType)*addrlen;
  1395. int result = ::getsockname(s, addr, &tmp_addrlen);
  1396. *addrlen = (std::size_t)tmp_addrlen;
  1397. return result;
  1398. }
  1399. int getsockname(socket_type s, socket_addr_type* addr,
  1400. std::size_t* addrlen, boost::system::error_code& ec)
  1401. {
  1402. if (s == invalid_socket)
  1403. {
  1404. ec = boost::asio::error::bad_descriptor;
  1405. return socket_error_retval;
  1406. }
  1407. clear_last_error();
  1408. int result = error_wrapper(call_getsockname(
  1409. &msghdr::msg_namelen, s, addr, addrlen), ec);
  1410. if (result == 0)
  1411. ec = boost::system::error_code();
  1412. return result;
  1413. }
  1414. int ioctl(socket_type s, state_type& state, int cmd,
  1415. ioctl_arg_type* arg, boost::system::error_code& ec)
  1416. {
  1417. if (s == invalid_socket)
  1418. {
  1419. ec = boost::asio::error::bad_descriptor;
  1420. return socket_error_retval;
  1421. }
  1422. clear_last_error();
  1423. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1424. int result = error_wrapper(::ioctlsocket(s, cmd, arg), ec);
  1425. #elif defined(__MACH__) && defined(__APPLE__) \
  1426. || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
  1427. int result = error_wrapper(::ioctl(s,
  1428. static_cast<unsigned int>(cmd), arg), ec);
  1429. #else
  1430. int result = error_wrapper(::ioctl(s, cmd, arg), ec);
  1431. #endif
  1432. if (result >= 0)
  1433. {
  1434. ec = boost::system::error_code();
  1435. // When updating the non-blocking mode we always perform the ioctl syscall,
  1436. // even if the flags would otherwise indicate that the socket is already in
  1437. // the correct state. This ensures that the underlying socket is put into
  1438. // the state that has been requested by the user. If the ioctl syscall was
  1439. // successful then we need to update the flags to match.
  1440. if (cmd == static_cast<int>(FIONBIO))
  1441. {
  1442. if (*arg)
  1443. {
  1444. state |= user_set_non_blocking;
  1445. }
  1446. else
  1447. {
  1448. // Clearing the non-blocking mode always overrides any internally-set
  1449. // non-blocking flag. Any subsequent asynchronous operations will need
  1450. // to re-enable non-blocking I/O.
  1451. state &= ~(user_set_non_blocking | internal_non_blocking);
  1452. }
  1453. }
  1454. }
  1455. return result;
  1456. }
  1457. int select(int nfds, fd_set* readfds, fd_set* writefds,
  1458. fd_set* exceptfds, timeval* timeout, boost::system::error_code& ec)
  1459. {
  1460. clear_last_error();
  1461. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1462. if (!readfds && !writefds && !exceptfds && timeout)
  1463. {
  1464. DWORD milliseconds = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
  1465. if (milliseconds == 0)
  1466. milliseconds = 1; // Force context switch.
  1467. ::Sleep(milliseconds);
  1468. ec = boost::system::error_code();
  1469. return 0;
  1470. }
  1471. // The select() call allows timeout values measured in microseconds, but the
  1472. // system clock (as wrapped by boost::posix_time::microsec_clock) typically
  1473. // has a resolution of 10 milliseconds. This can lead to a spinning select
  1474. // reactor, meaning increased CPU usage, when waiting for the earliest
  1475. // scheduled timeout if it's less than 10 milliseconds away. To avoid a tight
  1476. // spin we'll use a minimum timeout of 1 millisecond.
  1477. if (timeout && timeout->tv_sec == 0
  1478. && timeout->tv_usec > 0 && timeout->tv_usec < 1000)
  1479. timeout->tv_usec = 1000;
  1480. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1481. #if defined(__hpux) && defined(__SELECT)
  1482. timespec ts;
  1483. ts.tv_sec = timeout ? timeout->tv_sec : 0;
  1484. ts.tv_nsec = timeout ? timeout->tv_usec * 1000 : 0;
  1485. return error_wrapper(::pselect(nfds, readfds,
  1486. writefds, exceptfds, timeout ? &ts : 0, 0), ec);
  1487. #else
  1488. int result = error_wrapper(::select(nfds, readfds,
  1489. writefds, exceptfds, timeout), ec);
  1490. if (result >= 0)
  1491. ec = boost::system::error_code();
  1492. return result;
  1493. #endif
  1494. }
  1495. int poll_read(socket_type s, boost::system::error_code& ec)
  1496. {
  1497. if (s == invalid_socket)
  1498. {
  1499. ec = boost::asio::error::bad_descriptor;
  1500. return socket_error_retval;
  1501. }
  1502. #if defined(BOOST_WINDOWS) \
  1503. || defined(__CYGWIN__) \
  1504. || defined(__SYMBIAN32__)
  1505. fd_set fds;
  1506. FD_ZERO(&fds);
  1507. FD_SET(s, &fds);
  1508. clear_last_error();
  1509. int result = error_wrapper(::select(s, &fds, 0, 0, 0), ec);
  1510. if (result >= 0)
  1511. ec = boost::system::error_code();
  1512. return result;
  1513. #else // defined(BOOST_WINDOWS)
  1514. // || defined(__CYGWIN__)
  1515. // || defined(__SYMBIAN32__)
  1516. pollfd fds;
  1517. fds.fd = s;
  1518. fds.events = POLLIN;
  1519. fds.revents = 0;
  1520. clear_last_error();
  1521. int result = error_wrapper(::poll(&fds, 1, -1), ec);
  1522. if (result >= 0)
  1523. ec = boost::system::error_code();
  1524. return result;
  1525. #endif // defined(BOOST_WINDOWS)
  1526. // || defined(__CYGWIN__)
  1527. // || defined(__SYMBIAN32__)
  1528. }
  1529. int poll_write(socket_type s, boost::system::error_code& ec)
  1530. {
  1531. if (s == invalid_socket)
  1532. {
  1533. ec = boost::asio::error::bad_descriptor;
  1534. return socket_error_retval;
  1535. }
  1536. #if defined(BOOST_WINDOWS) \
  1537. || defined(__CYGWIN__) \
  1538. || defined(__SYMBIAN32__)
  1539. fd_set fds;
  1540. FD_ZERO(&fds);
  1541. FD_SET(s, &fds);
  1542. clear_last_error();
  1543. int result = error_wrapper(::select(s, 0, &fds, 0, 0), ec);
  1544. if (result >= 0)
  1545. ec = boost::system::error_code();
  1546. return result;
  1547. #else // defined(BOOST_WINDOWS)
  1548. // || defined(__CYGWIN__)
  1549. // || defined(__SYMBIAN32__)
  1550. pollfd fds;
  1551. fds.fd = s;
  1552. fds.events = POLLOUT;
  1553. fds.revents = 0;
  1554. clear_last_error();
  1555. int result = error_wrapper(::poll(&fds, 1, -1), ec);
  1556. if (result >= 0)
  1557. ec = boost::system::error_code();
  1558. return result;
  1559. #endif // defined(BOOST_WINDOWS)
  1560. // || defined(__CYGWIN__)
  1561. // || defined(__SYMBIAN32__)
  1562. }
  1563. int poll_connect(socket_type s, boost::system::error_code& ec)
  1564. {
  1565. if (s == invalid_socket)
  1566. {
  1567. ec = boost::asio::error::bad_descriptor;
  1568. return socket_error_retval;
  1569. }
  1570. #if defined(BOOST_WINDOWS) \
  1571. || defined(__CYGWIN__) \
  1572. || defined(__SYMBIAN32__)
  1573. fd_set write_fds;
  1574. FD_ZERO(&write_fds);
  1575. FD_SET(s, &write_fds);
  1576. fd_set except_fds;
  1577. FD_ZERO(&except_fds);
  1578. FD_SET(s, &except_fds);
  1579. clear_last_error();
  1580. int result = error_wrapper(::select(s, 0, &write_fds, &except_fds, 0), ec);
  1581. if (result >= 0)
  1582. ec = boost::system::error_code();
  1583. return result;
  1584. #else // defined(BOOST_WINDOWS)
  1585. // || defined(__CYGWIN__)
  1586. // || defined(__SYMBIAN32__)
  1587. pollfd fds;
  1588. fds.fd = s;
  1589. fds.events = POLLOUT;
  1590. fds.revents = 0;
  1591. clear_last_error();
  1592. int result = error_wrapper(::poll(&fds, 1, -1), ec);
  1593. if (result >= 0)
  1594. ec = boost::system::error_code();
  1595. return result;
  1596. #endif // defined(BOOST_WINDOWS)
  1597. // || defined(__CYGWIN__)
  1598. // || defined(__SYMBIAN32__)
  1599. }
  1600. const char* inet_ntop(int af, const void* src, char* dest, size_t length,
  1601. unsigned long scope_id, boost::system::error_code& ec)
  1602. {
  1603. clear_last_error();
  1604. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1605. using namespace std; // For memcpy.
  1606. if (af != AF_INET && af != AF_INET6)
  1607. {
  1608. ec = boost::asio::error::address_family_not_supported;
  1609. return 0;
  1610. }
  1611. union
  1612. {
  1613. socket_addr_type base;
  1614. sockaddr_storage_type storage;
  1615. sockaddr_in4_type v4;
  1616. sockaddr_in6_type v6;
  1617. } address;
  1618. DWORD address_length;
  1619. if (af == AF_INET)
  1620. {
  1621. address_length = sizeof(sockaddr_in4_type);
  1622. address.v4.sin_family = AF_INET;
  1623. address.v4.sin_port = 0;
  1624. memcpy(&address.v4.sin_addr, src, sizeof(in4_addr_type));
  1625. }
  1626. else // AF_INET6
  1627. {
  1628. address_length = sizeof(sockaddr_in6_type);
  1629. address.v6.sin6_family = AF_INET6;
  1630. address.v6.sin6_port = 0;
  1631. address.v6.sin6_flowinfo = 0;
  1632. address.v6.sin6_scope_id = scope_id;
  1633. memcpy(&address.v6.sin6_addr, src, sizeof(in6_addr_type));
  1634. }
  1635. DWORD string_length = static_cast<DWORD>(length);
  1636. #if defined(BOOST_NO_ANSI_APIS)
  1637. LPWSTR string_buffer = (LPWSTR)_alloca(length * sizeof(WCHAR));
  1638. int result = error_wrapper(::WSAAddressToStringW(&address.base,
  1639. address_length, 0, string_buffer, &string_length), ec);
  1640. ::WideCharToMultiByte(CP_ACP, 0, string_buffer, -1, dest, length, 0, 0);
  1641. #else
  1642. int result = error_wrapper(::WSAAddressToStringA(
  1643. &address.base, address_length, 0, dest, &string_length), ec);
  1644. #endif
  1645. // Windows may set error code on success.
  1646. if (result != socket_error_retval)
  1647. ec = boost::system::error_code();
  1648. // Windows may not set an error code on failure.
  1649. else if (result == socket_error_retval && !ec)
  1650. ec = boost::asio::error::invalid_argument;
  1651. return result == socket_error_retval ? 0 : dest;
  1652. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1653. const char* result = error_wrapper(::inet_ntop(af, src, dest, length), ec);
  1654. if (result == 0 && !ec)
  1655. ec = boost::asio::error::invalid_argument;
  1656. if (result != 0 && af == AF_INET6 && scope_id != 0)
  1657. {
  1658. using namespace std; // For strcat and sprintf.
  1659. char if_name[IF_NAMESIZE + 1] = "%";
  1660. const in6_addr_type* ipv6_address = static_cast<const in6_addr_type*>(src);
  1661. bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
  1662. && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
  1663. if (!is_link_local || if_indextoname(scope_id, if_name + 1) == 0)
  1664. sprintf(if_name + 1, "%lu", scope_id);
  1665. strcat(dest, if_name);
  1666. }
  1667. return result;
  1668. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1669. }
  1670. int inet_pton(int af, const char* src, void* dest,
  1671. unsigned long* scope_id, boost::system::error_code& ec)
  1672. {
  1673. clear_last_error();
  1674. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1675. using namespace std; // For memcpy and strcmp.
  1676. if (af != AF_INET && af != AF_INET6)
  1677. {
  1678. ec = boost::asio::error::address_family_not_supported;
  1679. return -1;
  1680. }
  1681. union
  1682. {
  1683. socket_addr_type base;
  1684. sockaddr_storage_type storage;
  1685. sockaddr_in4_type v4;
  1686. sockaddr_in6_type v6;
  1687. } address;
  1688. int address_length = sizeof(sockaddr_storage_type);
  1689. #if defined(BOOST_NO_ANSI_APIS)
  1690. int num_wide_chars = strlen(src) + 1;
  1691. LPWSTR wide_buffer = (LPWSTR)_alloca(num_wide_chars * sizeof(WCHAR));
  1692. ::MultiByteToWideChar(CP_ACP, 0, src, -1, wide_buffer, num_wide_chars);
  1693. int result = error_wrapper(::WSAStringToAddressW(
  1694. wide_buffer, af, 0, &address.base, &address_length), ec);
  1695. #else
  1696. int result = error_wrapper(::WSAStringToAddressA(
  1697. const_cast<char*>(src), af, 0, &address.base, &address_length), ec);
  1698. #endif
  1699. if (af == AF_INET)
  1700. {
  1701. if (result != socket_error_retval)
  1702. {
  1703. memcpy(dest, &address.v4.sin_addr, sizeof(in4_addr_type));
  1704. ec = boost::system::error_code();
  1705. }
  1706. else if (strcmp(src, "255.255.255.255") == 0)
  1707. {
  1708. static_cast<in4_addr_type*>(dest)->s_addr = INADDR_NONE;
  1709. ec = boost::system::error_code();
  1710. }
  1711. }
  1712. else // AF_INET6
  1713. {
  1714. if (result != socket_error_retval)
  1715. {
  1716. memcpy(dest, &address.v6.sin6_addr, sizeof(in6_addr_type));
  1717. if (scope_id)
  1718. *scope_id = address.v6.sin6_scope_id;
  1719. ec = boost::system::error_code();
  1720. }
  1721. }
  1722. // Windows may not set an error code on failure.
  1723. if (result == socket_error_retval && !ec)
  1724. ec = boost::asio::error::invalid_argument;
  1725. if (result != socket_error_retval)
  1726. ec = boost::system::error_code();
  1727. return result == socket_error_retval ? -1 : 1;
  1728. #else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1729. int result = error_wrapper(::inet_pton(af, src, dest), ec);
  1730. if (result <= 0 && !ec)
  1731. ec = boost::asio::error::invalid_argument;
  1732. if (result > 0 && af == AF_INET6 && scope_id)
  1733. {
  1734. using namespace std; // For strchr and atoi.
  1735. *scope_id = 0;
  1736. if (const char* if_name = strchr(src, '%'))
  1737. {
  1738. in6_addr_type* ipv6_address = static_cast<in6_addr_type*>(dest);
  1739. bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
  1740. && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
  1741. if (is_link_local)
  1742. *scope_id = if_nametoindex(if_name + 1);
  1743. if (*scope_id == 0)
  1744. *scope_id = atoi(if_name + 1);
  1745. }
  1746. }
  1747. return result;
  1748. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1749. }
  1750. int gethostname(char* name, int namelen, boost::system::error_code& ec)
  1751. {
  1752. clear_last_error();
  1753. int result = error_wrapper(::gethostname(name, namelen), ec);
  1754. #if defined(BOOST_WINDOWS)
  1755. if (result == 0)
  1756. ec = boost::system::error_code();
  1757. #endif
  1758. return result;
  1759. }
  1760. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__) \
  1761. || defined(__MACH__) && defined(__APPLE__)
  1762. // The following functions are only needed for emulation of getaddrinfo and
  1763. // getnameinfo.
  1764. inline boost::system::error_code translate_netdb_error(int error)
  1765. {
  1766. switch (error)
  1767. {
  1768. case 0:
  1769. return boost::system::error_code();
  1770. case HOST_NOT_FOUND:
  1771. return boost::asio::error::host_not_found;
  1772. case TRY_AGAIN:
  1773. return boost::asio::error::host_not_found_try_again;
  1774. case NO_RECOVERY:
  1775. return boost::asio::error::no_recovery;
  1776. case NO_DATA:
  1777. return boost::asio::error::no_data;
  1778. default:
  1779. BOOST_ASSERT(false);
  1780. return boost::asio::error::invalid_argument;
  1781. }
  1782. }
  1783. inline hostent* gethostbyaddr(const char* addr, int length, int af,
  1784. hostent* result, char* buffer, int buflength, boost::system::error_code& ec)
  1785. {
  1786. clear_last_error();
  1787. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1788. (void)(buffer);
  1789. (void)(buflength);
  1790. hostent* retval = error_wrapper(::gethostbyaddr(addr, length, af), ec);
  1791. if (!retval)
  1792. return 0;
  1793. ec = boost::system::error_code();
  1794. *result = *retval;
  1795. return retval;
  1796. #elif defined(__sun) || defined(__QNX__)
  1797. int error = 0;
  1798. hostent* retval = error_wrapper(::gethostbyaddr_r(addr, length, af, result,
  1799. buffer, buflength, &error), ec);
  1800. if (error)
  1801. ec = translate_netdb_error(error);
  1802. return retval;
  1803. #elif defined(__MACH__) && defined(__APPLE__)
  1804. (void)(buffer);
  1805. (void)(buflength);
  1806. int error = 0;
  1807. hostent* retval = error_wrapper(::getipnodebyaddr(
  1808. addr, length, af, &error), ec);
  1809. if (error)
  1810. ec = translate_netdb_error(error);
  1811. if (!retval)
  1812. return 0;
  1813. *result = *retval;
  1814. return retval;
  1815. #else
  1816. hostent* retval = 0;
  1817. int error = 0;
  1818. error_wrapper(::gethostbyaddr_r(addr, length, af, result, buffer,
  1819. buflength, &retval, &error), ec);
  1820. if (error)
  1821. ec = translate_netdb_error(error);
  1822. return retval;
  1823. #endif
  1824. }
  1825. inline hostent* gethostbyname(const char* name, int af, struct hostent* result,
  1826. char* buffer, int buflength, int ai_flags, boost::system::error_code& ec)
  1827. {
  1828. clear_last_error();
  1829. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  1830. (void)(buffer);
  1831. (void)(buflength);
  1832. (void)(ai_flags);
  1833. if (af != AF_INET)
  1834. {
  1835. ec = boost::asio::error::address_family_not_supported;
  1836. return 0;
  1837. }
  1838. hostent* retval = error_wrapper(::gethostbyname(name), ec);
  1839. if (!retval)
  1840. return 0;
  1841. ec = boost::system::error_code();
  1842. *result = *retval;
  1843. return result;
  1844. #elif defined(__sun) || defined(__QNX__)
  1845. (void)(ai_flags);
  1846. if (af != AF_INET)
  1847. {
  1848. ec = boost::asio::error::address_family_not_supported;
  1849. return 0;
  1850. }
  1851. int error = 0;
  1852. hostent* retval = error_wrapper(::gethostbyname_r(name, result, buffer,
  1853. buflength, &error), ec);
  1854. if (error)
  1855. ec = translate_netdb_error(error);
  1856. return retval;
  1857. #elif defined(__MACH__) && defined(__APPLE__)
  1858. (void)(buffer);
  1859. (void)(buflength);
  1860. int error = 0;
  1861. hostent* retval = error_wrapper(::getipnodebyname(
  1862. name, af, ai_flags, &error), ec);
  1863. if (error)
  1864. ec = translate_netdb_error(error);
  1865. if (!retval)
  1866. return 0;
  1867. *result = *retval;
  1868. return retval;
  1869. #else
  1870. (void)(ai_flags);
  1871. if (af != AF_INET)
  1872. {
  1873. ec = boost::asio::error::address_family_not_supported;
  1874. return 0;
  1875. }
  1876. hostent* retval = 0;
  1877. int error = 0;
  1878. error_wrapper(::gethostbyname_r(name, result,
  1879. buffer, buflength, &retval, &error), ec);
  1880. if (error)
  1881. ec = translate_netdb_error(error);
  1882. return retval;
  1883. #endif
  1884. }
  1885. inline void freehostent(hostent* h)
  1886. {
  1887. #if defined(__MACH__) && defined(__APPLE__)
  1888. if (h)
  1889. ::freehostent(h);
  1890. #else
  1891. (void)(h);
  1892. #endif
  1893. }
  1894. // Emulation of getaddrinfo based on implementation in:
  1895. // Stevens, W. R., UNIX Network Programming Vol. 1, 2nd Ed., Prentice-Hall 1998.
  1896. struct gai_search
  1897. {
  1898. const char* host;
  1899. int family;
  1900. };
  1901. inline int gai_nsearch(const char* host,
  1902. const addrinfo_type* hints, gai_search (&search)[2])
  1903. {
  1904. int search_count = 0;
  1905. if (host == 0 || host[0] == '\0')
  1906. {
  1907. if (hints->ai_flags & AI_PASSIVE)
  1908. {
  1909. // No host and AI_PASSIVE implies wildcard bind.
  1910. switch (hints->ai_family)
  1911. {
  1912. case AF_INET:
  1913. search[search_count].host = "0.0.0.0";
  1914. search[search_count].family = AF_INET;
  1915. ++search_count;
  1916. break;
  1917. case AF_INET6:
  1918. search[search_count].host = "0::0";
  1919. search[search_count].family = AF_INET6;
  1920. ++search_count;
  1921. break;
  1922. case AF_UNSPEC:
  1923. search[search_count].host = "0::0";
  1924. search[search_count].family = AF_INET6;
  1925. ++search_count;
  1926. search[search_count].host = "0.0.0.0";
  1927. search[search_count].family = AF_INET;
  1928. ++search_count;
  1929. break;
  1930. default:
  1931. break;
  1932. }
  1933. }
  1934. else
  1935. {
  1936. // No host and not AI_PASSIVE means connect to local host.
  1937. switch (hints->ai_family)
  1938. {
  1939. case AF_INET:
  1940. search[search_count].host = "localhost";
  1941. search[search_count].family = AF_INET;
  1942. ++search_count;
  1943. break;
  1944. case AF_INET6:
  1945. search[search_count].host = "localhost";
  1946. search[search_count].family = AF_INET6;
  1947. ++search_count;
  1948. break;
  1949. case AF_UNSPEC:
  1950. search[search_count].host = "localhost";
  1951. search[search_count].family = AF_INET6;
  1952. ++search_count;
  1953. search[search_count].host = "localhost";
  1954. search[search_count].family = AF_INET;
  1955. ++search_count;
  1956. break;
  1957. default:
  1958. break;
  1959. }
  1960. }
  1961. }
  1962. else
  1963. {
  1964. // Host is specified.
  1965. switch (hints->ai_family)
  1966. {
  1967. case AF_INET:
  1968. search[search_count].host = host;
  1969. search[search_count].family = AF_INET;
  1970. ++search_count;
  1971. break;
  1972. case AF_INET6:
  1973. search[search_count].host = host;
  1974. search[search_count].family = AF_INET6;
  1975. ++search_count;
  1976. break;
  1977. case AF_UNSPEC:
  1978. search[search_count].host = host;
  1979. search[search_count].family = AF_INET6;
  1980. ++search_count;
  1981. search[search_count].host = host;
  1982. search[search_count].family = AF_INET;
  1983. ++search_count;
  1984. break;
  1985. default:
  1986. break;
  1987. }
  1988. }
  1989. return search_count;
  1990. }
  1991. template <typename T>
  1992. inline T* gai_alloc(std::size_t size = sizeof(T))
  1993. {
  1994. using namespace std;
  1995. T* p = static_cast<T*>(::operator new(size, std::nothrow));
  1996. if (p)
  1997. memset(p, 0, size);
  1998. return p;
  1999. }
  2000. inline void gai_free(void* p)
  2001. {
  2002. ::operator delete(p);
  2003. }
  2004. inline void gai_strcpy(char* target, const char* source, std::size_t max_size)
  2005. {
  2006. using namespace std;
  2007. #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(UNDER_CE)
  2008. strcpy_s(target, max_size, source);
  2009. #else
  2010. *target = 0;
  2011. strncat(target, source, max_size);
  2012. #endif
  2013. }
  2014. enum { gai_clone_flag = 1 << 30 };
  2015. inline int gai_aistruct(addrinfo_type*** next, const addrinfo_type* hints,
  2016. const void* addr, int family)
  2017. {
  2018. using namespace std;
  2019. addrinfo_type* ai = gai_alloc<addrinfo_type>();
  2020. if (ai == 0)
  2021. return EAI_MEMORY;
  2022. ai->ai_next = 0;
  2023. **next = ai;
  2024. *next = &ai->ai_next;
  2025. ai->ai_canonname = 0;
  2026. ai->ai_socktype = hints->ai_socktype;
  2027. if (ai->ai_socktype == 0)
  2028. ai->ai_flags |= gai_clone_flag;
  2029. ai->ai_protocol = hints->ai_protocol;
  2030. ai->ai_family = family;
  2031. switch (ai->ai_family)
  2032. {
  2033. case AF_INET:
  2034. {
  2035. sockaddr_in4_type* sinptr = gai_alloc<sockaddr_in4_type>();
  2036. if (sinptr == 0)
  2037. return EAI_MEMORY;
  2038. sinptr->sin_family = AF_INET;
  2039. memcpy(&sinptr->sin_addr, addr, sizeof(in4_addr_type));
  2040. ai->ai_addr = reinterpret_cast<sockaddr*>(sinptr);
  2041. ai->ai_addrlen = sizeof(sockaddr_in4_type);
  2042. break;
  2043. }
  2044. case AF_INET6:
  2045. {
  2046. sockaddr_in6_type* sin6ptr = gai_alloc<sockaddr_in6_type>();
  2047. if (sin6ptr == 0)
  2048. return EAI_MEMORY;
  2049. sin6ptr->sin6_family = AF_INET6;
  2050. memcpy(&sin6ptr->sin6_addr, addr, sizeof(in6_addr_type));
  2051. ai->ai_addr = reinterpret_cast<sockaddr*>(sin6ptr);
  2052. ai->ai_addrlen = sizeof(sockaddr_in6_type);
  2053. break;
  2054. }
  2055. default:
  2056. break;
  2057. }
  2058. return 0;
  2059. }
  2060. inline addrinfo_type* gai_clone(addrinfo_type* ai)
  2061. {
  2062. using namespace std;
  2063. addrinfo_type* new_ai = gai_alloc<addrinfo_type>();
  2064. if (new_ai == 0)
  2065. return new_ai;
  2066. new_ai->ai_next = ai->ai_next;
  2067. ai->ai_next = new_ai;
  2068. new_ai->ai_flags = 0;
  2069. new_ai->ai_family = ai->ai_family;
  2070. new_ai->ai_socktype = ai->ai_socktype;
  2071. new_ai->ai_protocol = ai->ai_protocol;
  2072. new_ai->ai_canonname = 0;
  2073. new_ai->ai_addrlen = ai->ai_addrlen;
  2074. new_ai->ai_addr = gai_alloc<sockaddr>(ai->ai_addrlen);
  2075. memcpy(new_ai->ai_addr, ai->ai_addr, ai->ai_addrlen);
  2076. return new_ai;
  2077. }
  2078. inline int gai_port(addrinfo_type* aihead, int port, int socktype)
  2079. {
  2080. int num_found = 0;
  2081. for (addrinfo_type* ai = aihead; ai; ai = ai->ai_next)
  2082. {
  2083. if (ai->ai_flags & gai_clone_flag)
  2084. {
  2085. if (ai->ai_socktype != 0)
  2086. {
  2087. ai = gai_clone(ai);
  2088. if (ai == 0)
  2089. return -1;
  2090. // ai now points to newly cloned entry.
  2091. }
  2092. }
  2093. else if (ai->ai_socktype != socktype)
  2094. {
  2095. // Ignore if mismatch on socket type.
  2096. continue;
  2097. }
  2098. ai->ai_socktype = socktype;
  2099. switch (ai->ai_family)
  2100. {
  2101. case AF_INET:
  2102. {
  2103. sockaddr_in4_type* sinptr =
  2104. reinterpret_cast<sockaddr_in4_type*>(ai->ai_addr);
  2105. sinptr->sin_port = port;
  2106. ++num_found;
  2107. break;
  2108. }
  2109. case AF_INET6:
  2110. {
  2111. sockaddr_in6_type* sin6ptr =
  2112. reinterpret_cast<sockaddr_in6_type*>(ai->ai_addr);
  2113. sin6ptr->sin6_port = port;
  2114. ++num_found;
  2115. break;
  2116. }
  2117. default:
  2118. break;
  2119. }
  2120. }
  2121. return num_found;
  2122. }
  2123. inline int gai_serv(addrinfo_type* aihead,
  2124. const addrinfo_type* hints, const char* serv)
  2125. {
  2126. using namespace std;
  2127. int num_found = 0;
  2128. if (
  2129. #if defined(AI_NUMERICSERV)
  2130. (hints->ai_flags & AI_NUMERICSERV) ||
  2131. #endif
  2132. isdigit(static_cast<unsigned char>(serv[0])))
  2133. {
  2134. int port = htons(atoi(serv));
  2135. if (hints->ai_socktype)
  2136. {
  2137. // Caller specifies socket type.
  2138. int rc = gai_port(aihead, port, hints->ai_socktype);
  2139. if (rc < 0)
  2140. return EAI_MEMORY;
  2141. num_found += rc;
  2142. }
  2143. else
  2144. {
  2145. // Caller does not specify socket type.
  2146. int rc = gai_port(aihead, port, SOCK_STREAM);
  2147. if (rc < 0)
  2148. return EAI_MEMORY;
  2149. num_found += rc;
  2150. rc = gai_port(aihead, port, SOCK_DGRAM);
  2151. if (rc < 0)
  2152. return EAI_MEMORY;
  2153. num_found += rc;
  2154. }
  2155. }
  2156. else
  2157. {
  2158. // Try service name with TCP first, then UDP.
  2159. if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_STREAM)
  2160. {
  2161. servent* sptr = getservbyname(serv, "tcp");
  2162. if (sptr != 0)
  2163. {
  2164. int rc = gai_port(aihead, sptr->s_port, SOCK_STREAM);
  2165. if (rc < 0)
  2166. return EAI_MEMORY;
  2167. num_found += rc;
  2168. }
  2169. }
  2170. if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_DGRAM)
  2171. {
  2172. servent* sptr = getservbyname(serv, "udp");
  2173. if (sptr != 0)
  2174. {
  2175. int rc = gai_port(aihead, sptr->s_port, SOCK_DGRAM);
  2176. if (rc < 0)
  2177. return EAI_MEMORY;
  2178. num_found += rc;
  2179. }
  2180. }
  2181. }
  2182. if (num_found == 0)
  2183. {
  2184. if (hints->ai_socktype == 0)
  2185. {
  2186. // All calls to getservbyname() failed.
  2187. return EAI_NONAME;
  2188. }
  2189. else
  2190. {
  2191. // Service not supported for socket type.
  2192. return EAI_SERVICE;
  2193. }
  2194. }
  2195. return 0;
  2196. }
  2197. inline int gai_echeck(const char* host, const char* service,
  2198. int flags, int family, int socktype, int protocol)
  2199. {
  2200. (void)(flags);
  2201. (void)(protocol);
  2202. // Host or service must be specified.
  2203. if (host == 0 || host[0] == '\0')
  2204. if (service == 0 || service[0] == '\0')
  2205. return EAI_NONAME;
  2206. // Check combination of family and socket type.
  2207. switch (family)
  2208. {
  2209. case AF_UNSPEC:
  2210. break;
  2211. case AF_INET:
  2212. case AF_INET6:
  2213. if (service != 0 && service[0] != '\0')
  2214. if (socktype != 0 && socktype != SOCK_STREAM && socktype != SOCK_DGRAM)
  2215. return EAI_SOCKTYPE;
  2216. break;
  2217. default:
  2218. return EAI_FAMILY;
  2219. }
  2220. return 0;
  2221. }
  2222. inline void freeaddrinfo_emulation(addrinfo_type* aihead)
  2223. {
  2224. addrinfo_type* ai = aihead;
  2225. while (ai)
  2226. {
  2227. gai_free(ai->ai_addr);
  2228. gai_free(ai->ai_canonname);
  2229. addrinfo_type* ainext = ai->ai_next;
  2230. gai_free(ai);
  2231. ai = ainext;
  2232. }
  2233. }
  2234. inline int getaddrinfo_emulation(const char* host, const char* service,
  2235. const addrinfo_type* hintsp, addrinfo_type** result)
  2236. {
  2237. // Set up linked list of addrinfo structures.
  2238. addrinfo_type* aihead = 0;
  2239. addrinfo_type** ainext = &aihead;
  2240. char* canon = 0;
  2241. // Supply default hints if not specified by caller.
  2242. addrinfo_type hints = addrinfo_type();
  2243. hints.ai_family = AF_UNSPEC;
  2244. if (hintsp)
  2245. hints = *hintsp;
  2246. // If the resolution is not specifically for AF_INET6, remove the AI_V4MAPPED
  2247. // and AI_ALL flags.
  2248. #if defined(AI_V4MAPPED)
  2249. if (hints.ai_family != AF_INET6)
  2250. hints.ai_flags &= ~AI_V4MAPPED;
  2251. #endif
  2252. #if defined(AI_ALL)
  2253. if (hints.ai_family != AF_INET6)
  2254. hints.ai_flags &= ~AI_ALL;
  2255. #endif
  2256. // Basic error checking.
  2257. int rc = gai_echeck(host, service, hints.ai_flags, hints.ai_family,
  2258. hints.ai_socktype, hints.ai_protocol);
  2259. if (rc != 0)
  2260. {
  2261. freeaddrinfo_emulation(aihead);
  2262. return rc;
  2263. }
  2264. gai_search search[2];
  2265. int search_count = gai_nsearch(host, &hints, search);
  2266. for (gai_search* sptr = search; sptr < search + search_count; ++sptr)
  2267. {
  2268. // Check for IPv4 dotted decimal string.
  2269. in4_addr_type inaddr;
  2270. boost::system::error_code ec;
  2271. if (socket_ops::inet_pton(AF_INET, sptr->host, &inaddr, 0, ec) == 1)
  2272. {
  2273. if (hints.ai_family != AF_UNSPEC && hints.ai_family != AF_INET)
  2274. {
  2275. freeaddrinfo_emulation(aihead);
  2276. gai_free(canon);
  2277. return EAI_FAMILY;
  2278. }
  2279. if (sptr->family == AF_INET)
  2280. {
  2281. rc = gai_aistruct(&ainext, &hints, &inaddr, AF_INET);
  2282. if (rc != 0)
  2283. {
  2284. freeaddrinfo_emulation(aihead);
  2285. gai_free(canon);
  2286. return rc;
  2287. }
  2288. }
  2289. continue;
  2290. }
  2291. // Check for IPv6 hex string.
  2292. in6_addr_type in6addr;
  2293. if (socket_ops::inet_pton(AF_INET6, sptr->host, &in6addr, 0, ec) == 1)
  2294. {
  2295. if (hints.ai_family != AF_UNSPEC && hints.ai_family != AF_INET6)
  2296. {
  2297. freeaddrinfo_emulation(aihead);
  2298. gai_free(canon);
  2299. return EAI_FAMILY;
  2300. }
  2301. if (sptr->family == AF_INET6)
  2302. {
  2303. rc = gai_aistruct(&ainext, &hints, &in6addr, AF_INET6);
  2304. if (rc != 0)
  2305. {
  2306. freeaddrinfo_emulation(aihead);
  2307. gai_free(canon);
  2308. return rc;
  2309. }
  2310. }
  2311. continue;
  2312. }
  2313. // Look up hostname.
  2314. hostent hent;
  2315. char hbuf[8192] = "";
  2316. hostent* hptr = socket_ops::gethostbyname(sptr->host,
  2317. sptr->family, &hent, hbuf, sizeof(hbuf), hints.ai_flags, ec);
  2318. if (hptr == 0)
  2319. {
  2320. if (search_count == 2)
  2321. {
  2322. // Failure is OK if there are multiple searches.
  2323. continue;
  2324. }
  2325. freeaddrinfo_emulation(aihead);
  2326. gai_free(canon);
  2327. if (ec == boost::asio::error::host_not_found)
  2328. return EAI_NONAME;
  2329. if (ec == boost::asio::error::host_not_found_try_again)
  2330. return EAI_AGAIN;
  2331. if (ec == boost::asio::error::no_recovery)
  2332. return EAI_FAIL;
  2333. if (ec == boost::asio::error::no_data)
  2334. return EAI_NONAME;
  2335. return EAI_NONAME;
  2336. }
  2337. // Check for address family mismatch if one was specified.
  2338. if (hints.ai_family != AF_UNSPEC && hints.ai_family != hptr->h_addrtype)
  2339. {
  2340. freeaddrinfo_emulation(aihead);
  2341. gai_free(canon);
  2342. socket_ops::freehostent(hptr);
  2343. return EAI_FAMILY;
  2344. }
  2345. // Save canonical name first time.
  2346. if (host != 0 && host[0] != '\0' && hptr->h_name && hptr->h_name[0]
  2347. && (hints.ai_flags & AI_CANONNAME) && canon == 0)
  2348. {
  2349. std::size_t canon_len = strlen(hptr->h_name) + 1;
  2350. canon = gai_alloc<char>(canon_len);
  2351. if (canon == 0)
  2352. {
  2353. freeaddrinfo_emulation(aihead);
  2354. socket_ops::freehostent(hptr);
  2355. return EAI_MEMORY;
  2356. }
  2357. gai_strcpy(canon, hptr->h_name, canon_len);
  2358. }
  2359. // Create an addrinfo structure for each returned address.
  2360. for (char** ap = hptr->h_addr_list; *ap; ++ap)
  2361. {
  2362. rc = gai_aistruct(&ainext, &hints, *ap, hptr->h_addrtype);
  2363. if (rc != 0)
  2364. {
  2365. freeaddrinfo_emulation(aihead);
  2366. gai_free(canon);
  2367. socket_ops::freehostent(hptr);
  2368. return EAI_FAMILY;
  2369. }
  2370. }
  2371. socket_ops::freehostent(hptr);
  2372. }
  2373. // Check if we found anything.
  2374. if (aihead == 0)
  2375. {
  2376. gai_free(canon);
  2377. return EAI_NONAME;
  2378. }
  2379. // Return canonical name in first entry.
  2380. if (host != 0 && host[0] != '\0' && (hints.ai_flags & AI_CANONNAME))
  2381. {
  2382. if (canon)
  2383. {
  2384. aihead->ai_canonname = canon;
  2385. canon = 0;
  2386. }
  2387. else
  2388. {
  2389. std::size_t canonname_len = strlen(search[0].host) + 1;
  2390. aihead->ai_canonname = gai_alloc<char>(canonname_len);
  2391. if (aihead->ai_canonname == 0)
  2392. {
  2393. freeaddrinfo_emulation(aihead);
  2394. return EAI_MEMORY;
  2395. }
  2396. gai_strcpy(aihead->ai_canonname, search[0].host, canonname_len);
  2397. }
  2398. }
  2399. gai_free(canon);
  2400. // Process the service name.
  2401. if (service != 0 && service[0] != '\0')
  2402. {
  2403. rc = gai_serv(aihead, &hints, service);
  2404. if (rc != 0)
  2405. {
  2406. freeaddrinfo_emulation(aihead);
  2407. return rc;
  2408. }
  2409. }
  2410. // Return result to caller.
  2411. *result = aihead;
  2412. return 0;
  2413. }
  2414. inline boost::system::error_code getnameinfo_emulation(
  2415. const socket_addr_type* sa, std::size_t salen, char* host,
  2416. std::size_t hostlen, char* serv, std::size_t servlen, int flags,
  2417. boost::system::error_code& ec)
  2418. {
  2419. using namespace std;
  2420. const char* addr;
  2421. size_t addr_len;
  2422. unsigned short port;
  2423. switch (sa->sa_family)
  2424. {
  2425. case AF_INET:
  2426. if (salen != sizeof(sockaddr_in4_type))
  2427. {
  2428. return ec = boost::asio::error::invalid_argument;
  2429. }
  2430. addr = reinterpret_cast<const char*>(
  2431. &reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_addr);
  2432. addr_len = sizeof(in4_addr_type);
  2433. port = reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_port;
  2434. break;
  2435. case AF_INET6:
  2436. if (salen != sizeof(sockaddr_in6_type))
  2437. {
  2438. return ec = boost::asio::error::invalid_argument;
  2439. }
  2440. addr = reinterpret_cast<const char*>(
  2441. &reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_addr);
  2442. addr_len = sizeof(in6_addr_type);
  2443. port = reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_port;
  2444. break;
  2445. default:
  2446. return ec = boost::asio::error::address_family_not_supported;
  2447. }
  2448. if (host && hostlen > 0)
  2449. {
  2450. if (flags & NI_NUMERICHOST)
  2451. {
  2452. if (socket_ops::inet_ntop(sa->sa_family, addr, host, hostlen, 0, ec) == 0)
  2453. {
  2454. return ec;
  2455. }
  2456. }
  2457. else
  2458. {
  2459. hostent hent;
  2460. char hbuf[8192] = "";
  2461. hostent* hptr = socket_ops::gethostbyaddr(addr,
  2462. static_cast<int>(addr_len), sa->sa_family,
  2463. &hent, hbuf, sizeof(hbuf), ec);
  2464. if (hptr && hptr->h_name && hptr->h_name[0] != '\0')
  2465. {
  2466. if (flags & NI_NOFQDN)
  2467. {
  2468. char* dot = strchr(hptr->h_name, '.');
  2469. if (dot)
  2470. {
  2471. *dot = 0;
  2472. }
  2473. }
  2474. gai_strcpy(host, hptr->h_name, hostlen);
  2475. socket_ops::freehostent(hptr);
  2476. }
  2477. else
  2478. {
  2479. socket_ops::freehostent(hptr);
  2480. if (flags & NI_NAMEREQD)
  2481. {
  2482. return ec = boost::asio::error::host_not_found;
  2483. }
  2484. if (socket_ops::inet_ntop(sa->sa_family,
  2485. addr, host, hostlen, 0, ec) == 0)
  2486. {
  2487. return ec;
  2488. }
  2489. }
  2490. }
  2491. }
  2492. if (serv && servlen > 0)
  2493. {
  2494. if (flags & NI_NUMERICSERV)
  2495. {
  2496. if (servlen < 6)
  2497. {
  2498. return ec = boost::asio::error::no_buffer_space;
  2499. }
  2500. #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(UNDER_CE)
  2501. sprintf_s(serv, servlen, "%u", ntohs(port));
  2502. #else
  2503. sprintf(serv, "%u", ntohs(port));
  2504. #endif
  2505. }
  2506. else
  2507. {
  2508. #if defined(BOOST_HAS_THREADS) && defined(BOOST_HAS_PTHREADS) \
  2509. && !defined(BOOST_ASIO_DISABLE_THREADS)
  2510. static ::pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2511. ::pthread_mutex_lock(&mutex);
  2512. #endif // defined(BOOST_HAS_THREADS) && defined(BOOST_HAS_PTHREADS)
  2513. // && !defined(BOOST_ASIO_DISABLE_THREADS)
  2514. servent* sptr = ::getservbyport(port, (flags & NI_DGRAM) ? "udp" : 0);
  2515. if (sptr && sptr->s_name && sptr->s_name[0] != '\0')
  2516. {
  2517. gai_strcpy(serv, sptr->s_name, servlen);
  2518. }
  2519. else
  2520. {
  2521. if (servlen < 6)
  2522. {
  2523. return ec = boost::asio::error::no_buffer_space;
  2524. }
  2525. #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(UNDER_CE)
  2526. sprintf_s(serv, servlen, "%u", ntohs(port));
  2527. #else
  2528. sprintf(serv, "%u", ntohs(port));
  2529. #endif
  2530. }
  2531. #if defined(BOOST_HAS_THREADS) && defined(BOOST_HAS_PTHREADS) \
  2532. && !defined(BOOST_ASIO_DISABLE_THREADS)
  2533. ::pthread_mutex_unlock(&mutex);
  2534. #endif // defined(BOOST_HAS_THREADS) && defined(BOOST_HAS_PTHREADS)
  2535. // && !defined(BOOST_ASIO_DISABLE_THREADS)
  2536. }
  2537. }
  2538. ec = boost::system::error_code();
  2539. return ec;
  2540. }
  2541. #endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  2542. // || defined(__MACH__) && defined(__APPLE__)
  2543. inline boost::system::error_code translate_addrinfo_error(int error)
  2544. {
  2545. switch (error)
  2546. {
  2547. case 0:
  2548. return boost::system::error_code();
  2549. case EAI_AGAIN:
  2550. return boost::asio::error::host_not_found_try_again;
  2551. case EAI_BADFLAGS:
  2552. return boost::asio::error::invalid_argument;
  2553. case EAI_FAIL:
  2554. return boost::asio::error::no_recovery;
  2555. case EAI_FAMILY:
  2556. return boost::asio::error::address_family_not_supported;
  2557. case EAI_MEMORY:
  2558. return boost::asio::error::no_memory;
  2559. case EAI_NONAME:
  2560. #if defined(EAI_ADDRFAMILY)
  2561. case EAI_ADDRFAMILY:
  2562. #endif
  2563. #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
  2564. case EAI_NODATA:
  2565. #endif
  2566. return boost::asio::error::host_not_found;
  2567. case EAI_SERVICE:
  2568. return boost::asio::error::service_not_found;
  2569. case EAI_SOCKTYPE:
  2570. return boost::asio::error::socket_type_not_supported;
  2571. default: // Possibly the non-portable EAI_SYSTEM.
  2572. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  2573. return boost::system::error_code(
  2574. WSAGetLastError(), boost::asio::error::get_system_category());
  2575. #else
  2576. return boost::system::error_code(
  2577. errno, boost::asio::error::get_system_category());
  2578. #endif
  2579. }
  2580. }
  2581. boost::system::error_code getaddrinfo(const char* host,
  2582. const char* service, const addrinfo_type& hints,
  2583. addrinfo_type** result, boost::system::error_code& ec)
  2584. {
  2585. host = (host && *host) ? host : 0;
  2586. service = (service && *service) ? service : 0;
  2587. clear_last_error();
  2588. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  2589. # if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) || defined(UNDER_CE)
  2590. // Building for Windows XP, Windows Server 2003, or later.
  2591. int error = ::getaddrinfo(host, service, &hints, result);
  2592. return ec = translate_addrinfo_error(error);
  2593. # else
  2594. // Building for Windows 2000 or earlier.
  2595. typedef int (WSAAPI *gai_t)(const char*,
  2596. const char*, const addrinfo_type*, addrinfo_type**);
  2597. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  2598. {
  2599. if (gai_t gai = (gai_t)::GetProcAddress(winsock_module, "getaddrinfo"))
  2600. {
  2601. int error = gai(host, service, &hints, result);
  2602. return ec = translate_addrinfo_error(error);
  2603. }
  2604. }
  2605. int error = getaddrinfo_emulation(host, service, &hints, result);
  2606. return ec = translate_addrinfo_error(error);
  2607. # endif
  2608. #elif defined(__MACH__) && defined(__APPLE__)
  2609. int error = getaddrinfo_emulation(host, service, &hints, result);
  2610. return ec = translate_addrinfo_error(error);
  2611. #else
  2612. int error = ::getaddrinfo(host, service, &hints, result);
  2613. return ec = translate_addrinfo_error(error);
  2614. #endif
  2615. }
  2616. boost::system::error_code background_getaddrinfo(
  2617. const weak_cancel_token_type& cancel_token, const char* host,
  2618. const char* service, const addrinfo_type& hints,
  2619. addrinfo_type** result, boost::system::error_code& ec)
  2620. {
  2621. if (cancel_token.expired())
  2622. ec = boost::asio::error::operation_aborted;
  2623. else
  2624. socket_ops::getaddrinfo(host, service, hints, result, ec);
  2625. return ec;
  2626. }
  2627. void freeaddrinfo(addrinfo_type* ai)
  2628. {
  2629. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  2630. # if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) || defined(UNDER_CE)
  2631. // Building for Windows XP, Windows Server 2003, or later.
  2632. ::freeaddrinfo(ai);
  2633. # else
  2634. // Building for Windows 2000 or earlier.
  2635. typedef int (WSAAPI *fai_t)(addrinfo_type*);
  2636. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  2637. {
  2638. if (fai_t fai = (fai_t)::GetProcAddress(winsock_module, "freeaddrinfo"))
  2639. {
  2640. fai(ai);
  2641. return;
  2642. }
  2643. }
  2644. freeaddrinfo_emulation(ai);
  2645. # endif
  2646. #elif defined(__MACH__) && defined(__APPLE__)
  2647. freeaddrinfo_emulation(ai);
  2648. #else
  2649. ::freeaddrinfo(ai);
  2650. #endif
  2651. }
  2652. boost::system::error_code getnameinfo(const socket_addr_type* addr,
  2653. std::size_t addrlen, char* host, std::size_t hostlen,
  2654. char* serv, std::size_t servlen, int flags, boost::system::error_code& ec)
  2655. {
  2656. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  2657. # if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) || defined(UNDER_CE)
  2658. // Building for Windows XP, Windows Server 2003, or later.
  2659. clear_last_error();
  2660. int error = ::getnameinfo(addr, static_cast<socklen_t>(addrlen),
  2661. host, static_cast<DWORD>(hostlen),
  2662. serv, static_cast<DWORD>(servlen), flags);
  2663. return ec = translate_addrinfo_error(error);
  2664. # else
  2665. // Building for Windows 2000 or earlier.
  2666. typedef int (WSAAPI *gni_t)(const socket_addr_type*,
  2667. int, char*, DWORD, char*, DWORD, int);
  2668. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  2669. {
  2670. if (gni_t gni = (gni_t)::GetProcAddress(winsock_module, "getnameinfo"))
  2671. {
  2672. clear_last_error();
  2673. int error = gni(addr, static_cast<int>(addrlen),
  2674. host, static_cast<DWORD>(hostlen),
  2675. serv, static_cast<DWORD>(servlen), flags);
  2676. return ec = translate_addrinfo_error(error);
  2677. }
  2678. }
  2679. clear_last_error();
  2680. return getnameinfo_emulation(addr, addrlen,
  2681. host, hostlen, serv, servlen, flags, ec);
  2682. # endif
  2683. #elif defined(__MACH__) && defined(__APPLE__)
  2684. using namespace std; // For memcpy.
  2685. sockaddr_storage_type tmp_addr;
  2686. memcpy(&tmp_addr, addr, addrlen);
  2687. tmp_addr.ss_len = addrlen;
  2688. addr = reinterpret_cast<socket_addr_type*>(&tmp_addr);
  2689. clear_last_error();
  2690. return getnameinfo_emulation(addr, addrlen,
  2691. host, hostlen, serv, servlen, flags, ec);
  2692. #else
  2693. clear_last_error();
  2694. int error = ::getnameinfo(addr, addrlen, host, hostlen, serv, servlen, flags);
  2695. return ec = translate_addrinfo_error(error);
  2696. #endif
  2697. }
  2698. boost::system::error_code sync_getnameinfo(
  2699. const socket_addr_type* addr, std::size_t addrlen,
  2700. char* host, std::size_t hostlen, char* serv,
  2701. std::size_t servlen, int sock_type, boost::system::error_code& ec)
  2702. {
  2703. // First try resolving with the service name. If that fails try resolving
  2704. // but allow the service to be returned as a number.
  2705. int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
  2706. socket_ops::getnameinfo(addr, addrlen, host,
  2707. hostlen, serv, servlen, flags, ec);
  2708. if (ec)
  2709. {
  2710. socket_ops::getnameinfo(addr, addrlen, host, hostlen,
  2711. serv, servlen, flags | NI_NUMERICSERV, ec);
  2712. }
  2713. return ec;
  2714. }
  2715. boost::system::error_code background_getnameinfo(
  2716. const weak_cancel_token_type& cancel_token,
  2717. const socket_addr_type* addr, std::size_t addrlen,
  2718. char* host, std::size_t hostlen, char* serv,
  2719. std::size_t servlen, int sock_type, boost::system::error_code& ec)
  2720. {
  2721. if (cancel_token.expired())
  2722. {
  2723. ec = boost::asio::error::operation_aborted;
  2724. }
  2725. else
  2726. {
  2727. // First try resolving with the service name. If that fails try resolving
  2728. // but allow the service to be returned as a number.
  2729. int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
  2730. socket_ops::getnameinfo(addr, addrlen, host,
  2731. hostlen, serv, servlen, flags, ec);
  2732. if (ec)
  2733. {
  2734. socket_ops::getnameinfo(addr, addrlen, host, hostlen,
  2735. serv, servlen, flags | NI_NUMERICSERV, ec);
  2736. }
  2737. }
  2738. return ec;
  2739. }
  2740. u_long_type network_to_host_long(u_long_type value)
  2741. {
  2742. return ntohl(value);
  2743. }
  2744. u_long_type host_to_network_long(u_long_type value)
  2745. {
  2746. return htonl(value);
  2747. }
  2748. u_short_type network_to_host_short(u_short_type value)
  2749. {
  2750. return ntohs(value);
  2751. }
  2752. u_short_type host_to_network_short(u_short_type value)
  2753. {
  2754. return htons(value);
  2755. }
  2756. } // namespace socket_ops
  2757. } // namespace detail
  2758. } // namespace asio
  2759. } // namespace boost
  2760. #include <boost/asio/detail/pop_options.hpp>
  2761. #endif // BOOST_ASIO_DETAIL_SOCKET_OPS_IPP