Botan 3.9.0
Crypto and TLS for C&
socket_udp.cpp
Go to the documentation of this file.
1/*
2* (C) 2015,2016,2017 Jack Lloyd
3* (C) 2016 Daniel Neus
4* (C) 2019 Nuno Goncalves <nunojpg@gmail.com>
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/internal/socket_udp.h>
10
11#include <botan/exceptn.h>
12#include <botan/mem_ops.h>
13#include <botan/internal/fmt.h>
14#include <botan/internal/target_info.h>
15#include <botan/internal/uri.h>
16#include <chrono>
17
18#if defined(BOTAN_HAS_BOOST_ASIO)
19 /*
20 * We don't need serial port support anyway, and asking for it
21 * causes macro conflicts with Darwin's termios.h when this
22 * file is included in the amalgamation. GH #350
23 */
24 #define BOOST_ASIO_DISABLE_SERIAL_PORT
25 #include <boost/asio.hpp>
26 #include <boost/asio/system_timer.hpp>
27#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #include <string.h>
33 #include <sys/socket.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36
37#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
38 #include <ws2tcpip.h>
39#endif
40
41namespace Botan {
42
43namespace {
44
45#if defined(BOTAN_HAS_BOOST_ASIO)
46class Asio_SocketUDP final : public OS::SocketUDP {
47 public:
48 Asio_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
49 m_timeout(timeout), m_timer(m_io), m_udp(m_io) {
50 m_timer.expires_after(m_timeout);
51 check_timeout();
52
53 boost::asio::ip::udp::resolver resolver(m_io);
54 boost::asio::ip::udp::resolver::results_type dns_iter =
55 resolver.resolve(std::string{hostname}, std::string{service});
56
57 boost::system::error_code ec = boost::asio::error::would_block;
58
59 auto connect_cb = [&ec](const boost::system::error_code& e,
60 const boost::asio::ip::udp::resolver::results_type::iterator&) { ec = e; };
61
62 boost::asio::async_connect(m_udp, dns_iter.begin(), dns_iter.end(), connect_cb);
63
64 while(ec == boost::asio::error::would_block) {
65 m_io.run_one();
66 }
67
68 if(ec) {
69 throw boost::system::system_error(ec);
70 }
71 if(!m_udp.is_open()) {
72 throw System_Error(fmt("Connection to host {} failed", hostname));
73 }
74 }
75
76 void write(const uint8_t buf[], size_t len) override {
77 m_timer.expires_after(m_timeout);
78
79 boost::system::error_code ec = boost::asio::error::would_block;
80
81 m_udp.async_send(boost::asio::buffer(buf, len), [&ec](boost::system::error_code e, size_t) { ec = e; });
82
83 while(ec == boost::asio::error::would_block) {
84 m_io.run_one();
85 }
86
87 if(ec) {
88 throw boost::system::system_error(ec);
89 }
90 }
91
92 size_t read(uint8_t buf[], size_t len) override {
93 m_timer.expires_after(m_timeout);
94
95 boost::system::error_code ec = boost::asio::error::would_block;
96 size_t got = 0;
97
98 m_udp.async_receive(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
99 ec = cb_ec;
100 got = cb_got;
101 });
102
103 while(ec == boost::asio::error::would_block) {
104 m_io.run_one();
105 }
106
107 if(ec) {
108 if(ec == boost::asio::error::eof) {
109 return 0;
110 }
111 throw boost::system::system_error(ec); // Some other error.
112 }
113
114 return got;
115 }
116
117 private:
118 void check_timeout() {
119 if(m_udp.is_open() && m_timer.expiry() < std::chrono::system_clock::now()) {
120 boost::system::error_code err;
121
122 // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
123 m_udp.close(err);
124 }
125
126 // NOLINTNEXTLINE(*-avoid-bind) FIXME - unclear why we can't use a lambda here
127 m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout, this));
128 }
129
130 const std::chrono::microseconds m_timeout;
131 boost::asio::io_context m_io;
132 boost::asio::system_timer m_timer;
133 boost::asio::ip::udp::socket m_udp;
134};
135#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
136class BSD_SocketUDP final : public OS::SocketUDP {
137 public:
138 BSD_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
139 m_timeout(timeout) {
140 socket_init();
141
142 m_socket = invalid_socket();
143
144 addrinfo* res = nullptr;
145 addrinfo hints;
146 clear_mem(&hints, 1);
147 hints.ai_family = AF_UNSPEC;
148 hints.ai_socktype = SOCK_DGRAM;
149
150 const std::string hostname_str(hostname);
151 const std::string service_str(service);
152
153 int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, &res);
154
155 if(rc != 0) {
156 throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
157 }
158
159 for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
160 if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
161 continue;
162 }
163
164 m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
165
166 if(m_socket == invalid_socket()) [[unlikely]] {
167 // unsupported socket type?
168 continue;
169 }
170
171 set_nonblocking(m_socket);
172 memcpy(&sa, res->ai_addr, res->ai_addrlen);
173 salen = static_cast<socklen_t>(res->ai_addrlen); // NOLINT(*-redundant-casting)
174 }
175
176 ::freeaddrinfo(res);
177
178 if(m_socket == invalid_socket()) {
179 throw System_Error(fmt("Connecting to {} for service {} failed with errno {}", hostname, service, errno),
180 errno);
181 }
182 }
183
184 ~BSD_SocketUDP() override {
185 close_socket(m_socket);
186 m_socket = invalid_socket();
187 socket_fini();
188 }
189
190 BSD_SocketUDP(const BSD_SocketUDP& other) = delete;
191 BSD_SocketUDP(BSD_SocketUDP&& other) = delete;
192 BSD_SocketUDP& operator=(const BSD_SocketUDP& other) = delete;
193 BSD_SocketUDP& operator=(BSD_SocketUDP&& other) = delete;
194
195 void write(const uint8_t buf[], size_t len) override {
196 fd_set write_set;
197 FD_ZERO(&write_set);
198 FD_SET(m_socket, &write_set);
199
200 size_t sent_so_far = 0;
201 while(sent_so_far != len) {
202 struct timeval timeout = make_timeout_tv();
203 int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
204
205 if(active == 0) {
206 throw System_Error("Timeout during socket write");
207 }
208
209 const size_t left = len - sent_so_far;
210 socket_op_ret_type sent = ::sendto(m_socket,
211 cast_uint8_ptr_to_char(buf + sent_so_far),
212 static_cast<sendrecv_len_type>(left),
213 0,
214 reinterpret_cast<sockaddr*>(&sa),
215 salen);
216 if(sent < 0) {
217 throw System_Error("Socket write failed", errno);
218 } else {
219 sent_so_far += static_cast<size_t>(sent);
220 }
221 }
222 }
223
224 size_t read(uint8_t buf[], size_t len) override {
225 fd_set read_set;
226 FD_ZERO(&read_set);
227 FD_SET(m_socket, &read_set);
228
229 struct timeval timeout = make_timeout_tv();
230 int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
231
232 if(active == 0) {
233 throw System_Error("Timeout during socket read");
234 }
235
236 socket_op_ret_type got =
237 ::recvfrom(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0, nullptr, nullptr);
238
239 if(got < 0) {
240 throw System_Error("Socket read failed", errno);
241 }
242
243 return static_cast<size_t>(got);
244 }
245
246 private:
247 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
248 typedef SOCKET socket_type;
249 typedef int socket_op_ret_type;
250 typedef int sendrecv_len_type;
251
252 static socket_type invalid_socket() { return INVALID_SOCKET; }
253
254 static void close_socket(socket_type s) { ::closesocket(s); }
255
256 static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
257
258 static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
259
260 static void set_nonblocking(socket_type s) {
261 u_long nonblocking = 1;
262 ::ioctlsocket(s, FIONBIO, &nonblocking);
263 }
264
265 static void socket_init() {
266 WSAData wsa_data;
267 WORD wsa_version = MAKEWORD(2, 2);
268
269 if(::WSAStartup(wsa_version, &wsa_data) != 0) {
270 throw System_Error("WSAStartup() failed", WSAGetLastError());
271 }
272
273 if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
274 ::WSACleanup();
275 throw System_Error("Could not find a usable version of Winsock.dll");
276 }
277 }
278
279 static void socket_fini() { ::WSACleanup(); }
280 #else
281 typedef int socket_type;
282 typedef ssize_t socket_op_ret_type;
283 typedef size_t sendrecv_len_type;
284
285 static socket_type invalid_socket() { return -1; }
286
287 static void close_socket(socket_type s) { ::close(s); }
288
289 static std::string get_last_socket_error() { return ::strerror(errno); }
290
291 static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
292
293 static void set_nonblocking(socket_type s) {
294 if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
295 throw System_Error("Setting socket to non-blocking state failed", errno);
296 }
297 }
298
299 static void socket_init() {}
300
301 static void socket_fini() {}
302 #endif
303 sockaddr_storage sa;
304 socklen_t salen;
305
306 struct timeval make_timeout_tv() const {
307 struct timeval tv;
308 tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
309 tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
310 return tv;
311 }
312
313 const std::chrono::microseconds m_timeout;
314 socket_type m_socket;
315};
316#endif
317} // namespace
318
319std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view hostname,
320 std::string_view service,
321 std::chrono::microseconds timeout) {
322#if defined(BOTAN_HAS_BOOST_ASIO)
323 return std::make_unique<Asio_SocketUDP>(hostname, service, timeout);
324#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
325 return std::make_unique<BSD_SocketUDP>(hostname, service, timeout);
326#else
327 BOTAN_UNUSED(hostname);
328 BOTAN_UNUSED(service);
329 BOTAN_UNUSED(timeout);
330 return std::unique_ptr<OS::SocketUDP>();
331#endif
332}
333
334std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view uri_string, std::chrono::microseconds timeout) {
335 const auto uri = URI::from_any(uri_string);
336 if(uri.port() == 0) {
337 throw Invalid_Argument("UDP port not specified");
338 }
339 return open_socket_udp(uri.host(), std::to_string(uri.port()), timeout);
340}
341
342} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:144
static URI from_any(std::string_view uri)
Definition uri.cpp:180
std::unique_ptr< SocketUDP > BOTAN_TEST_API open_socket_udp(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout)
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53