9#include <botan/internal/socket_udp.h>
11#include <botan/exceptn.h>
12#include <botan/mem_ops.h>
14#include <botan/internal/fmt.h>
15#include <botan/internal/stl_util.h>
16#include <botan/internal/target_info.h>
19#if defined(BOTAN_HAS_BOOST_ASIO)
25 #define BOOST_ASIO_DISABLE_SERIAL_PORT
26 #include <boost/asio.hpp>
27 #include <boost/asio/system_timer.hpp>
28#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
32 #include <netinet/in.h>
34 #include <sys/socket.h>
38#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
46#if defined(BOTAN_HAS_BOOST_ASIO)
47class Asio_SocketUDP final :
public OS::SocketUDP {
49 Asio_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
50 m_timeout(timeout), m_timer(m_io), m_udp(m_io) {
51 m_timer.expires_after(m_timeout);
57 boost::asio::ip::udp::resolver resolver(m_io);
58 boost::asio::ip::udp::resolver::results_type dns_iter;
59 boost::system::error_code resolve_ec = boost::asio::error::would_block;
60 resolver.async_resolve(
61 std::string{hostname}, std::string{service}, [&](
const boost::system::error_code& e,
auto results) {
63 dns_iter = std::move(results);
65 while(resolve_ec == boost::asio::error::would_block) {
66 if(m_timer.expiry() <
decltype(m_timer)::clock_type::now()) {
72 throw boost::system::system_error(resolve_ec);
75 boost::system::error_code ec = boost::asio::error::would_block;
77 auto connect_cb = [&ec](
const boost::system::error_code& e,
78 const boost::asio::ip::udp::resolver::results_type::iterator&) { ec = e; };
80 boost::asio::async_connect(m_udp, dns_iter.begin(), dns_iter.end(), connect_cb);
82 while(ec == boost::asio::error::would_block) {
87 throw boost::system::system_error(ec);
89 if(!m_udp.is_open()) {
90 throw System_Error(
fmt(
"Connection to host {} failed", hostname));
94 void write(
const uint8_t buf[],
size_t len)
override {
95 m_timer.expires_after(m_timeout);
97 boost::system::error_code ec = boost::asio::error::would_block;
99 m_udp.async_send(boost::asio::buffer(buf, len), [&ec](boost::system::error_code e,
size_t) { ec = e; });
101 while(ec == boost::asio::error::would_block) {
106 throw boost::system::system_error(ec);
110 size_t read(uint8_t buf[],
size_t len)
override {
111 m_timer.expires_after(m_timeout);
113 boost::system::error_code ec = boost::asio::error::would_block;
116 m_udp.async_receive(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec,
size_t cb_got) {
121 while(ec == boost::asio::error::would_block) {
126 if(ec == boost::asio::error::eof) {
129 throw boost::system::system_error(ec);
136 void check_timeout() {
137 if(m_udp.is_open() && m_timer.expiry() <
decltype(m_timer)::clock_type::now()) {
138 boost::system::error_code err;
145 m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout,
this));
148 const std::chrono::microseconds m_timeout;
149 boost::asio::io_context m_io;
150 boost::asio::system_timer m_timer;
151 boost::asio::ip::udp::socket m_udp;
153#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
154class BSD_SocketUDP final :
public OS::SocketUDP {
156 BSD_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
157 m_timeout(timeout), m_socket(invalid_socket()) {
164 do_connect(hostname, service);
166 if(m_socket != invalid_socket()) {
167 close_socket(m_socket);
168 m_socket = invalid_socket();
176 void do_connect(std::string_view hostname, std::string_view service) {
177 const std::string hostname_str(hostname);
178 const std::string service_str(service);
181 hints.ai_family = AF_UNSPEC;
182 hints.ai_socktype = SOCK_DGRAM;
184 unique_addr_info_ptr res =
nullptr;
186 const int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints,
Botan::out_ptr(res));
188 throw System_Error(fmt(
"Name resolution failed for {}", hostname), rc);
191 for(
const addrinfo* rp = res.get(); (m_socket == invalid_socket()) && (rp !=
nullptr); rp = rp->ai_next) {
192 if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
196 m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
198 if(m_socket == invalid_socket()) [[unlikely]] {
203 #if !defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
205 if(m_socket >= FD_SETSIZE) {
206 close_socket(m_socket);
207 m_socket = invalid_socket();
208 throw System_Error(
"Socket descriptor exceeds FD_SETSIZE; select() would be unsafe");
212 set_nonblocking(m_socket);
222 if(::connect(m_socket, rp->ai_addr,
static_cast<socklen_t
>(rp->ai_addrlen)) != 0) {
223 close_socket(m_socket);
224 m_socket = invalid_socket();
229 if(m_socket == invalid_socket()) {
231 fmt(
"Connecting to {} for service {} failed with errno {}", hostname, service, last_socket_error()),
232 last_socket_error());
237 ~BSD_SocketUDP()
override {
238 close_socket(m_socket);
239 m_socket = invalid_socket();
243 BSD_SocketUDP(
const BSD_SocketUDP& other) =
delete;
244 BSD_SocketUDP(BSD_SocketUDP&& other) =
delete;
245 BSD_SocketUDP& operator=(
const BSD_SocketUDP& other) =
delete;
246 BSD_SocketUDP& operator=(BSD_SocketUDP&& other) =
delete;
248 void write(
const uint8_t buf[],
size_t len)
override {
249 size_t sent_so_far = 0;
250 while(sent_so_far != len) {
253 FD_SET(m_socket, &write_set);
255 struct timeval timeout = make_timeout_tv();
256 const int active = ::select(
static_cast<int>(m_socket + 1),
nullptr, &write_set,
nullptr, &timeout);
259 if(last_error_is_retryable()) {
262 throw System_Error(
"Socket select failed", last_socket_error());
266 throw System_Error(
"Timeout during socket write");
269 const size_t left = len - sent_so_far;
270 const socket_op_ret_type sent =
271 ::send(m_socket, cast_uint8_ptr_to_char(buf + sent_so_far),
static_cast<sendrecv_len_type
>(left), 0);
273 if(last_error_is_retryable()) {
276 throw System_Error(
"Socket write failed", last_socket_error());
278 sent_so_far +=
static_cast<size_t>(sent);
283 size_t read(uint8_t buf[],
size_t len)
override {
287 FD_SET(m_socket, &read_set);
289 struct timeval timeout = make_timeout_tv();
290 const int active = ::select(
static_cast<int>(m_socket + 1), &read_set,
nullptr,
nullptr, &timeout);
293 if(last_error_is_retryable()) {
296 throw System_Error(
"Socket select failed", last_socket_error());
300 throw System_Error(
"Timeout during socket read");
305 const socket_op_ret_type got =
306 ::recv(m_socket, cast_uint8_ptr_to_char(buf),
static_cast<sendrecv_len_type
>(len), 0);
309 if(last_error_is_retryable()) {
312 throw System_Error(
"Socket read failed", last_socket_error());
315 return static_cast<size_t>(got);
320 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
321 typedef SOCKET socket_type;
322 typedef int socket_op_ret_type;
323 typedef int sendrecv_len_type;
325 static socket_type invalid_socket() {
return INVALID_SOCKET; }
327 static void close_socket(socket_type s) { ::closesocket(s); }
329 static int last_socket_error() { return ::WSAGetLastError(); }
331 static std::string get_last_socket_error() {
return std::to_string(::WSAGetLastError()); }
333 static bool nonblocking_connect_in_progress() {
return (::WSAGetLastError() == WSAEWOULDBLOCK); }
335 static bool last_error_is_retryable() {
return (::WSAGetLastError() == WSAEINTR); }
337 static void set_nonblocking(socket_type s) {
338 u_long nonblocking = 1;
339 ::ioctlsocket(s, FIONBIO, &nonblocking);
342 static void socket_init() {
344 WORD wsa_version = MAKEWORD(2, 2);
346 if(::WSAStartup(wsa_version, &wsa_data) != 0) {
347 throw System_Error(
"WSAStartup() failed", WSAGetLastError());
350 if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
352 throw System_Error(
"Could not find a usable version of Winsock.dll");
356 static void socket_fini() { ::WSACleanup(); }
358 typedef int socket_type;
359 typedef ssize_t socket_op_ret_type;
360 typedef size_t sendrecv_len_type;
362 static socket_type invalid_socket() {
return -1; }
364 static void close_socket(socket_type s) { ::close(s); }
366 static int last_socket_error() {
return errno; }
368 static std::string get_last_socket_error() { return ::strerror(errno); }
370 static bool nonblocking_connect_in_progress() {
return (errno == EINPROGRESS); }
372 static bool last_error_is_retryable() {
return (errno == EINTR); }
374 static void set_nonblocking(socket_type s) {
376 if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
377 throw System_Error(
"Setting socket to non-blocking state failed", errno);
381 static void socket_init() {}
383 static void socket_fini() {}
385 struct timeval make_timeout_tv() const {
386 struct timeval tv {};
388 tv.tv_sec =
static_cast<decltype(timeval::tv_sec)
>(m_timeout.count() / 1000000);
389 tv.tv_usec =
static_cast<decltype(timeval::tv_usec)
>(m_timeout.count() % 1000000);
393 const std::chrono::microseconds m_timeout;
394 socket_type m_socket;
396 using unique_addr_info_ptr = std::unique_ptr<addrinfo,
decltype([](addrinfo* p) {
406 std::string_view service,
407 std::chrono::microseconds timeout) {
408#if defined(BOTAN_HAS_BOOST_ASIO)
409 return std::make_unique<Asio_SocketUDP>(hostname, service, timeout);
410#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
411 return std::make_unique<BSD_SocketUDP>(hostname, service, timeout);
416 return std::unique_ptr<OS::SocketUDP>();
420std::unique_ptr<OS::SocketUDP>
OS::open_socket_udp(std::string_view uri_string, std::chrono::microseconds timeout) {
422 if(!authority.has_value() || !authority->port().has_value()) {
425 return open_socket_udp(authority->host_to_string(), std::to_string(*authority->port()), timeout);
static std::optional< Authority > from_string(std::string_view raw)
std::unique_ptr< SocketUDP > BOTAN_TEST_API open_socket_udp(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout)
constexpr auto out_ptr(T &outptr) noexcept
std::string fmt(std::string_view format, const T &... args)