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