8#include <botan/internal/socket.h>
10#include <botan/exceptn.h>
11#include <botan/mem_ops.h>
12#include <botan/internal/fmt.h>
15#if defined(BOTAN_HAS_BOOST_ASIO)
21 #define BOOST_ASIO_DISABLE_SERIAL_PORT
22 #include <boost/asio.hpp>
23 #include <boost/asio/system_timer.hpp>
25#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
29 #include <netinet/in.h>
31 #include <sys/socket.h>
35#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
43#if defined(BOTAN_HAS_BOOST_ASIO)
45class Asio_Socket
final :
public OS::Socket {
47 Asio_Socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout) :
48 m_timeout(timeout), m_timer(m_io), m_tcp(m_io) {
49 m_timer.expires_from_now(m_timeout);
52 boost::asio::ip::tcp::resolver resolver(m_io);
53 boost::asio::ip::tcp::resolver::query query(std::string{hostname}, std::string{service});
54 boost::asio::ip::tcp::resolver::iterator dns_iter = resolver.resolve(query);
56 boost::system::error_code ec = boost::asio::error::would_block;
58 auto connect_cb = [&ec](
const boost::system::error_code& e,
const boost::asio::ip::tcp::resolver::iterator&) {
62 boost::asio::async_connect(m_tcp, dns_iter, connect_cb);
64 while(ec == boost::asio::error::would_block) {
69 throw boost::system::system_error(ec);
71 if(m_tcp.is_open() ==
false) {
72 throw System_Error(
fmt(
"Connection to host {} failed", hostname));
76 void write(
const uint8_t buf[],
size_t len)
override {
77 m_timer.expires_from_now(m_timeout);
79 boost::system::error_code ec = boost::asio::error::would_block;
81 m_tcp.async_send(boost::asio::buffer(buf, len), [&ec](boost::system::error_code e,
size_t) { ec = e; });
83 while(ec == boost::asio::error::would_block) {
88 throw boost::system::system_error(ec);
92 size_t read(uint8_t buf[],
size_t len)
override {
93 m_timer.expires_from_now(m_timeout);
95 boost::system::error_code ec = boost::asio::error::would_block;
98 m_tcp.async_read_some(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec,
size_t cb_got) {
103 while(ec == boost::asio::error::would_block) {
108 if(ec == boost::asio::error::eof) {
111 throw boost::system::system_error(ec);
118 void check_timeout() {
119 if(m_tcp.is_open() && m_timer.expires_at() < std::chrono::system_clock::now()) {
120 boost::system::error_code err;
126 m_timer.async_wait(std::bind(&Asio_Socket::check_timeout,
this));
129 const std::chrono::milliseconds m_timeout;
130 boost::asio::io_service m_io;
131 boost::asio::system_timer m_timer;
132 boost::asio::ip::tcp::socket m_tcp;
135#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
137class BSD_Socket
final :
public OS::Socket {
139 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
140 typedef SOCKET socket_type;
141 typedef int socket_op_ret_type;
142 typedef int socklen_type;
143 typedef int sendrecv_len_type;
145 static socket_type invalid_socket() {
return INVALID_SOCKET; }
147 static void close_socket(socket_type s) { ::closesocket(s); }
149 static std::string get_last_socket_error() {
return std::to_string(::WSAGetLastError()); }
151 static bool nonblocking_connect_in_progress() {
return (::WSAGetLastError() == WSAEWOULDBLOCK); }
153 static void set_nonblocking(socket_type s) {
154 u_long nonblocking = 1;
155 ::ioctlsocket(s, FIONBIO, &nonblocking);
158 static void socket_init() {
160 WORD wsa_version = MAKEWORD(2, 2);
162 if(::WSAStartup(wsa_version, &wsa_data) != 0) {
163 throw System_Error(
"WSAStartup() failed", WSAGetLastError());
166 if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
168 throw System_Error(
"Could not find a usable version of Winsock.dll");
172 static void socket_fini() { ::WSACleanup(); }
174 typedef int socket_type;
175 typedef ssize_t socket_op_ret_type;
176 typedef socklen_t socklen_type;
177 typedef size_t sendrecv_len_type;
179 static socket_type invalid_socket() {
return -1; }
181 static void close_socket(socket_type s) { ::close(s); }
183 static std::string get_last_socket_error() { return ::strerror(errno); }
185 static bool nonblocking_connect_in_progress() {
return (errno == EINPROGRESS); }
187 static void set_nonblocking(socket_type s) {
188 if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
189 throw System_Error(
"Setting socket to non-blocking state failed", errno);
193 static void socket_init() {}
195 static void socket_fini() {}
199 BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
203 m_socket = invalid_socket();
206 clear_mem(&hints, 1);
207 hints.ai_family = AF_UNSPEC;
208 hints.ai_socktype = SOCK_STREAM;
211 const std::string hostname_str(hostname);
212 const std::string service_str(service);
214 int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, &res);
217 throw System_Error(fmt(
"Name resolution failed for {}", hostname), rc);
220 for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp !=
nullptr); rp = rp->ai_next) {
221 if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
225 m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
227 if(m_socket == invalid_socket()) {
232 set_nonblocking(m_socket);
234 int err = ::connect(m_socket, rp->ai_addr,
static_cast<socklen_type
>(rp->ai_addrlen));
238 if(nonblocking_connect_in_progress()) {
239 struct timeval timeout_tv = make_timeout_tv();
243 FD_SET(
static_cast<int>(m_socket), &write_set);
245 active = ::select(
static_cast<int>(m_socket + 1),
nullptr, &write_set,
nullptr, &timeout_tv);
248 int socket_error = 0;
249 socklen_t len =
sizeof(socket_error);
251 if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char*
>(&socket_error), &len) <
253 throw System_Error(
"Error calling getsockopt", errno);
256 if(socket_error != 0) {
263 close_socket(m_socket);
264 m_socket = invalid_socket();
272 if(m_socket == invalid_socket()) {
273 throw System_Error(fmt(
"Connecting to {} for service {} failed with errno {}", hostname, service, errno),
278 ~BSD_Socket()
override {
279 close_socket(m_socket);
280 m_socket = invalid_socket();
284 BSD_Socket(
const BSD_Socket& other) =
delete;
285 BSD_Socket(BSD_Socket&& other) =
delete;
286 BSD_Socket& operator=(
const BSD_Socket& other) =
delete;
287 BSD_Socket& operator=(BSD_Socket&& other) =
delete;
289 void write(
const uint8_t buf[],
size_t len)
override {
292 FD_SET(m_socket, &write_set);
294 size_t sent_so_far = 0;
295 while(sent_so_far != len) {
296 struct timeval timeout = make_timeout_tv();
297 int active = ::select(
static_cast<int>(m_socket + 1),
nullptr, &write_set,
nullptr, &timeout);
300 throw System_Error(
"Timeout during socket write");
303 const size_t left = len - sent_so_far;
304 socket_op_ret_type sent =
305 ::send(m_socket, cast_uint8_ptr_to_char(&buf[sent_so_far]),
static_cast<sendrecv_len_type
>(left), 0);
307 throw System_Error(
"Socket write failed", errno);
309 sent_so_far +=
static_cast<size_t>(sent);
314 size_t read(uint8_t buf[],
size_t len)
override {
317 FD_SET(m_socket, &read_set);
319 struct timeval timeout = make_timeout_tv();
320 int active = ::select(
static_cast<int>(m_socket + 1), &read_set,
nullptr,
nullptr, &timeout);
323 throw System_Error(
"Timeout during socket read");
326 socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf),
static_cast<sendrecv_len_type
>(len), 0);
329 throw System_Error(
"Socket read failed", errno);
332 return static_cast<size_t>(got);
336 struct timeval make_timeout_tv() const {
338 tv.tv_sec =
static_cast<decltype(timeval::tv_sec)
>(m_timeout.count() / 1000000);
339 tv.tv_usec =
static_cast<decltype(timeval::tv_usec)
>(m_timeout.count() % 1000000);
343 const std::chrono::microseconds m_timeout;
344 socket_type m_socket;
352 std::string_view service,
353 std::chrono::milliseconds timeout) {
354#if defined(BOTAN_HAS_BOOST_ASIO)
355 return std::make_unique<Asio_Socket>(hostname, service, timeout);
357#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
358 return std::make_unique<BSD_Socket>(hostname, service, timeout);
365 return std::unique_ptr<Socket>();
int(* final)(unsigned char *, CTX *)
std::unique_ptr< Socket > BOTAN_TEST_API open_socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout)
std::string fmt(std::string_view format, const T &... args)