Botan 3.14.1
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/uri.h>
14#include <botan/internal/fmt.h>
15#include <botan/internal/stl_util.h>
16#include <botan/internal/target_info.h>
17#include <chrono>
18
19#if defined(BOTAN_HAS_BOOST_ASIO)
20 /*
21 * We don't need serial port support anyway, and asking for it
22 * causes macro conflicts with Darwin's termios.h when this
23 * file is included in the amalgamation. GH #350
24 */
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)
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <netdb.h>
32 #include <netinet/in.h>
33 #include <string.h>
34 #include <sys/socket.h>
35 #include <sys/time.h>
36 #include <unistd.h>
37
38#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
39 #include <ws2tcpip.h>
40#endif
41
42namespace Botan {
43
44namespace {
45
46#if defined(BOTAN_HAS_BOOST_ASIO)
47class Asio_SocketUDP final : public OS::SocketUDP {
48 public:
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);
52 check_timeout();
53
54 // Resolve asynchronously so the timer covers DNS as well as connect.
55 // check_timeout() only closes m_udp, which isn't open yet during the
56 // resolve, so cancel the resolver inline if the deadline passes.
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(hostname, service, [&](const boost::system::error_code& e, auto results) {
61 resolve_ec = e;
62 dns_iter = std::move(results);
63 });
64 while(resolve_ec == boost::asio::error::would_block) {
65 if(m_timer.expiry() < decltype(m_timer)::clock_type::now()) {
66 resolver.cancel();
67 }
68 m_io.run_one();
69 }
70 if(resolve_ec) {
71 throw boost::system::system_error(resolve_ec);
72 }
73
74 boost::system::error_code ec = boost::asio::error::would_block;
75
76 auto connect_cb = [&ec](const boost::system::error_code& e,
77 const boost::asio::ip::udp::resolver::results_type::iterator&) { ec = e; };
78
79 boost::asio::async_connect(m_udp, dns_iter.begin(), dns_iter.end(), connect_cb);
80
81 while(ec == boost::asio::error::would_block) {
82 m_io.run_one();
83 }
84
85 if(ec) {
86 throw boost::system::system_error(ec);
87 }
88 if(!m_udp.is_open()) {
89 throw System_Error(fmt("Connection to host {} failed", hostname));
90 }
91 }
92
93 void write(const uint8_t buf[], size_t len) override {
94 m_timer.expires_after(m_timeout);
95
96 boost::system::error_code ec = boost::asio::error::would_block;
97
98 m_udp.async_send(boost::asio::buffer(buf, len), [&ec](boost::system::error_code e, size_t) { ec = e; });
99
100 while(ec == boost::asio::error::would_block) {
101 m_io.run_one();
102 }
103
104 if(ec) {
105 throw boost::system::system_error(ec);
106 }
107 }
108
109 size_t read(uint8_t buf[], size_t len) override {
110 m_timer.expires_after(m_timeout);
111
112 boost::system::error_code ec = boost::asio::error::would_block;
113 size_t got = 0;
114
115 m_udp.async_receive(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
116 ec = cb_ec;
117 got = cb_got;
118 });
119
120 while(ec == boost::asio::error::would_block) {
121 m_io.run_one();
122 }
123
124 if(ec) {
125 if(ec == boost::asio::error::eof) {
126 return 0;
127 }
128 throw boost::system::system_error(ec); // Some other error.
129 }
130
131 return got;
132 }
133
134 private:
135 void check_timeout() {
136 if(m_udp.is_open() && m_timer.expiry() < decltype(m_timer)::clock_type::now()) {
137 boost::system::error_code err;
138
139 // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
140 m_udp.close(err);
141 }
142
143 // NOLINTNEXTLINE(*-avoid-bind) FIXME - unclear why we can't use a lambda here
144 m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout, this));
145 }
146
147 const std::chrono::microseconds m_timeout;
148 boost::asio::io_context m_io;
149 boost::asio::system_timer m_timer;
150 boost::asio::ip::udp::socket m_udp;
151};
152#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
153class BSD_SocketUDP final : public OS::SocketUDP {
154 public:
155 BSD_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
156 m_timeout(timeout), m_socket(invalid_socket()) {
157 socket_init();
158
159 // A constructor that throws does not run its destructor, so do
160 // cleanup explicitly on any failure between socket_init() above and
161 // the end of construction below.
162 try {
163 do_connect(hostname, service);
164 } catch(...) {
165 if(m_socket != invalid_socket()) {
166 close_socket(m_socket);
167 m_socket = invalid_socket();
168 }
169 socket_fini();
170 throw;
171 }
172 }
173
174 private:
175 void do_connect(std::string_view hostname, std::string_view service) {
176 const std::string hostname_str(hostname);
177 const std::string service_str(service);
178
179 addrinfo hints{};
180 hints.ai_family = AF_UNSPEC;
181 hints.ai_socktype = SOCK_DGRAM;
182
183 unique_addr_info_ptr res = nullptr;
184
185 const int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, Botan::out_ptr(res));
186 if(rc != 0) {
187 throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
188 }
189
190 for(const addrinfo* rp = res.get(); (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
191 if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
192 continue;
193 }
194
195 m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
196
197 if(m_socket == invalid_socket()) [[unlikely]] {
198 // unsupported socket type?
199 continue;
200 }
201
202 #if !defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
203 // Windows fd_set is an array of sockets and doesn't have this limitation
204 if(m_socket >= FD_SETSIZE) {
205 close_socket(m_socket);
206 m_socket = invalid_socket();
207 throw System_Error("Socket descriptor exceeds FD_SETSIZE; select() would be unsafe");
208 }
209 #endif
210
211 set_nonblocking(m_socket);
212
213 // Connect the UDP socket to the selected peer so the kernel drops
214 // datagrams arriving from anyone else. Without this a stray or
215 // spoofed datagram could be accepted as the response.
216 //
217 // ::connect on a UDP socket only records the peer address in the
218 // kernel; it does not produce or consume traffic. It is effectively
219 // non-blocking on every supported platform, so we don't wrap this
220 // in the select() pattern used by the TCP path.
221 if(::connect(m_socket, rp->ai_addr, static_cast<socklen_t>(rp->ai_addrlen)) != 0) {
222 close_socket(m_socket);
223 m_socket = invalid_socket();
224 continue;
225 }
226 }
227
228 if(m_socket == invalid_socket()) {
229 throw System_Error(
230 fmt("Connecting to {} for service {} failed with errno {}", hostname, service, last_socket_error()),
231 last_socket_error());
232 }
233 }
234
235 public:
236 ~BSD_SocketUDP() override {
237 close_socket(m_socket);
238 m_socket = invalid_socket();
239 socket_fini();
240 }
241
242 BSD_SocketUDP(const BSD_SocketUDP& other) = delete;
243 BSD_SocketUDP(BSD_SocketUDP&& other) = delete;
244 BSD_SocketUDP& operator=(const BSD_SocketUDP& other) = delete;
245 BSD_SocketUDP& operator=(BSD_SocketUDP&& other) = delete;
246
247 void write(const uint8_t buf[], size_t len) override {
248 size_t sent_so_far = 0;
249 while(sent_so_far != len) {
250 fd_set write_set;
251 FD_ZERO(&write_set);
252 FD_SET(m_socket, &write_set);
253
254 struct timeval timeout = make_timeout_tv();
255 const int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
256
257 if(active < 0) {
258 if(last_error_is_retryable()) {
259 continue;
260 }
261 throw System_Error("Socket select failed", last_socket_error());
262 }
263
264 if(active == 0) {
265 throw System_Error("Timeout during socket write");
266 }
267
268 const size_t left = len - sent_so_far;
269 const socket_op_ret_type sent =
270 ::send(m_socket, cast_uint8_ptr_to_char(buf + sent_so_far), static_cast<sendrecv_len_type>(left), 0);
271 if(sent < 0) {
272 if(last_error_is_retryable()) {
273 continue;
274 }
275 throw System_Error("Socket write failed", last_socket_error());
276 } else {
277 sent_so_far += static_cast<size_t>(sent);
278 }
279 }
280 }
281
282 size_t read(uint8_t buf[], size_t len) override {
283 for(;;) {
284 fd_set read_set;
285 FD_ZERO(&read_set);
286 FD_SET(m_socket, &read_set);
287
288 struct timeval timeout = make_timeout_tv();
289 const int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
290
291 if(active < 0) {
292 if(last_error_is_retryable()) {
293 continue;
294 }
295 throw System_Error("Socket select failed", last_socket_error());
296 }
297
298 if(active == 0) {
299 throw System_Error("Timeout during socket read");
300 }
301
302 // Socket is connected, so recv() filters out datagrams from any
303 // sender other than the configured peer.
304 const socket_op_ret_type got =
305 ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);
306
307 if(got < 0) {
308 if(last_error_is_retryable()) {
309 continue;
310 }
311 throw System_Error("Socket read failed", last_socket_error());
312 }
313
314 return static_cast<size_t>(got);
315 }
316 }
317
318 private:
319 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
320 typedef SOCKET socket_type;
321 typedef int socket_op_ret_type;
322 typedef int sendrecv_len_type;
323
324 static socket_type invalid_socket() { return INVALID_SOCKET; }
325
326 static void close_socket(socket_type s) { ::closesocket(s); }
327
328 static int last_socket_error() { return ::WSAGetLastError(); }
329
330 static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
331
332 static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
333
334 static bool last_error_is_retryable() { return (::WSAGetLastError() == WSAEINTR); }
335
336 static void set_nonblocking(socket_type s) {
337 u_long nonblocking = 1;
338 ::ioctlsocket(s, FIONBIO, &nonblocking);
339 }
340
341 static void socket_init() {
342 WSAData wsa_data;
343 WORD wsa_version = MAKEWORD(2, 2);
344
345 if(::WSAStartup(wsa_version, &wsa_data) != 0) {
346 throw System_Error("WSAStartup() failed", WSAGetLastError());
347 }
348
349 if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
350 ::WSACleanup();
351 throw System_Error("Could not find a usable version of Winsock.dll");
352 }
353 }
354
355 static void socket_fini() { ::WSACleanup(); }
356 #else
357 typedef int socket_type;
358 typedef ssize_t socket_op_ret_type;
359 typedef size_t sendrecv_len_type;
360
361 static socket_type invalid_socket() { return -1; }
362
363 static void close_socket(socket_type s) { ::close(s); }
364
365 static int last_socket_error() { return errno; }
366
367 static std::string get_last_socket_error() { return ::strerror(errno); }
368
369 static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
370
371 static bool last_error_is_retryable() { return (errno == EINTR); }
372
373 static void set_nonblocking(socket_type s) {
374 // NOLINTNEXTLINE(*-vararg)
375 if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
376 throw System_Error("Setting socket to non-blocking state failed", errno);
377 }
378 }
379
380 static void socket_init() {}
381
382 static void socket_fini() {}
383 #endif
384 struct timeval make_timeout_tv() const {
385 struct timeval tv {};
386
387 tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
388 tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
389 return tv;
390 }
391
392 const std::chrono::microseconds m_timeout;
393 socket_type m_socket;
394
395 using unique_addr_info_ptr = std::unique_ptr<addrinfo, decltype([](addrinfo* p) {
396 if(p != nullptr) {
397 ::freeaddrinfo(p);
398 }
399 })>;
400};
401#endif
402} // namespace
403
404std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view hostname,
405 std::string_view service,
406 std::chrono::microseconds timeout) {
407#if defined(BOTAN_HAS_BOOST_ASIO)
408 return std::make_unique<Asio_SocketUDP>(hostname, service, timeout);
409#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
410 return std::make_unique<BSD_SocketUDP>(hostname, service, timeout);
411#else
412 BOTAN_UNUSED(hostname);
413 BOTAN_UNUSED(service);
414 BOTAN_UNUSED(timeout);
415 return std::unique_ptr<OS::SocketUDP>();
416#endif
417}
418
419std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view uri_string, std::chrono::microseconds timeout) {
420 const auto authority = URI::Authority::from_string(uri_string);
421 if(!authority.has_value() || !authority->port().has_value()) {
422 throw Invalid_Argument("UDP port not specified");
423 }
424 return open_socket_udp(authority->host_to_string(), std::to_string(*authority->port()), timeout);
425}
426
427} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:151
static std::optional< Authority > from_string(std::string_view raw)
Definition uri.cpp:247
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
Definition stl_util.h:164
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53