Botan 3.14.1
Crypto and TLS for C&
socket.cpp
Go to the documentation of this file.
1/*
2* (C) 2015,2016,2017 Jack Lloyd
3* (C) 2016 Daniel Neus
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/internal/socket.h>
9
10#include <botan/exceptn.h>
11#include <botan/mem_ops.h>
12#include <botan/internal/fmt.h>
13#include <botan/internal/stl_util.h>
14#include <botan/internal/target_info.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 causes
20 * macro conflicts with termios.h when this file is included in the
21 * amalgamation.
22 */
23 #define BOOST_ASIO_DISABLE_SERIAL_PORT
24 #include <boost/asio.hpp>
25 #include <boost/asio/steady_timer.hpp>
26
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)
46
47class Asio_Socket final : public OS::Socket {
48 public:
49 Asio_Socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout) :
50 m_timer(m_io), m_tcp(m_io) {
51 m_timer.expires_after(timeout);
52 check_timeout();
53
54 // Resolve asynchronously so the timer covers DNS as well as connect.
55 // check_timeout() only closes m_tcp, which isn't open yet during the
56 // resolve, so cancel the resolver inline if the deadline passes; that
57 // delivers operation_aborted to the callback and breaks the loop.
58 boost::asio::ip::tcp::resolver resolver(m_io);
59 boost::asio::ip::tcp::resolver::results_type dns_iter;
60 boost::system::error_code resolve_ec = boost::asio::error::would_block;
61 resolver.async_resolve(hostname, service, [&](const boost::system::error_code& e, auto results) {
62 resolve_ec = e;
63 dns_iter = std::move(results);
64 });
65 while(resolve_ec == boost::asio::error::would_block) {
66 if(m_timer.expiry() < decltype(m_timer)::clock_type::now()) {
67 resolver.cancel();
68 }
69 m_io.run_one();
70 }
71 if(resolve_ec) {
72 throw boost::system::system_error(resolve_ec);
73 }
74
75 boost::system::error_code ec = boost::asio::error::would_block;
76
77 auto connect_cb = [&ec](const boost::system::error_code& e, const auto&) { ec = e; };
78
79 boost::asio::async_connect(m_tcp, 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_tcp.is_open()) {
89 throw System_Error(fmt("Connection to host {} failed", hostname));
90 }
91 }
92
93 void write(std::span<const uint8_t> buf) override {
94 boost::system::error_code ec = boost::asio::error::would_block;
95
96 boost::asio::async_write(m_tcp,
97 boost::asio::buffer(buf.data(), buf.size()),
98 [&ec](const 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 == boost::asio::error::operation_aborted) {
105 // check_timeout closed the socket
106 throw System_Error("Timeout during socket write");
107 }
108 if(ec) {
109 throw boost::system::system_error(ec);
110 }
111 }
112
113 size_t read(uint8_t buf[], size_t len) override {
114 boost::system::error_code ec = boost::asio::error::would_block;
115 size_t got = 0;
116
117 m_tcp.async_read_some(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
118 ec = cb_ec;
119 got = cb_got;
120 });
121
122 while(ec == boost::asio::error::would_block) {
123 m_io.run_one();
124 }
125
126 if(ec) {
127 if(ec == boost::asio::error::eof) {
128 return 0;
129 }
130 if(ec == boost::asio::error::operation_aborted) {
131 // check_timeout closed the socket
132 throw System_Error("Timeout during socket read");
133 }
134 throw boost::system::system_error(ec); // Some other error.
135 }
136
137 return got;
138 }
139
140 private:
141 void check_timeout() {
142 if(m_tcp.is_open() && m_timer.expiry() < decltype(m_timer)::clock_type::now()) {
143 boost::system::error_code err;
144
145 // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
146 m_tcp.close(err);
147 }
148
149 // NOLINTNEXTLINE(*-avoid-bind) FIXME - unclear why we can't use a lambda here
150 m_timer.async_wait(std::bind(&Asio_Socket::check_timeout, this));
151 }
152
153 boost::asio::io_context m_io;
154 boost::asio::steady_timer m_timer;
155 boost::asio::ip::tcp::socket m_tcp;
156};
157
158#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
159
160namespace {
161
162// MSG_NOSIGNAL on the send call prevents SIGPIPE when the peer has gone away
163// (Linux, the BSDs, Cygwin). macOS doesn't define it; we set SO_NOSIGPIPE on
164// the socket instead. Windows has no SIGPIPE.
165 #if defined(MSG_NOSIGNAL)
166constexpr int botan_send_flags = MSG_NOSIGNAL;
167 #else
168constexpr int botan_send_flags = 0;
169 #endif
170
171} // namespace
172
173class BSD_Socket final : public OS::Socket {
174 private:
175 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
176 typedef SOCKET socket_type;
177 typedef int socket_op_ret_type;
178 typedef int socklen_type;
179 typedef int sendrecv_len_type;
180
181 static socket_type invalid_socket() { return INVALID_SOCKET; }
182
183 static void close_socket(socket_type s) { ::closesocket(s); }
184
185 static int last_socket_error() { return ::WSAGetLastError(); }
186
187 static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
188
189 static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
190
191 static bool last_error_is_retryable() { return (::WSAGetLastError() == WSAEINTR); }
192
193 static void set_nonblocking(socket_type s) {
194 u_long nonblocking = 1;
195 ::ioctlsocket(s, FIONBIO, &nonblocking);
196 }
197
198 static void socket_init() {
199 WSAData wsa_data;
200 WORD wsa_version = MAKEWORD(2, 2);
201
202 if(::WSAStartup(wsa_version, &wsa_data) != 0) {
203 throw System_Error("WSAStartup() failed", WSAGetLastError());
204 }
205
206 if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
207 ::WSACleanup();
208 throw System_Error("Could not find a usable version of Winsock.dll");
209 }
210 }
211
212 static void socket_fini() { ::WSACleanup(); }
213 #else
214 typedef int socket_type;
215 typedef ssize_t socket_op_ret_type;
216 typedef socklen_t socklen_type;
217 typedef size_t sendrecv_len_type;
218
219 static socket_type invalid_socket() { return -1; }
220
221 static void close_socket(socket_type s) { ::close(s); }
222
223 static int last_socket_error() { return errno; }
224
225 static std::string get_last_socket_error() { return ::strerror(errno); }
226
227 static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
228
229 static bool last_error_is_retryable() { return (errno == EINTR); }
230
231 static void set_nonblocking(socket_type s) {
232 // NOLINTNEXTLINE(*-vararg)
233 if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
234 throw System_Error("Setting socket to non-blocking state failed", errno);
235 }
236 }
237
238 static void socket_init() {}
239
240 static void socket_fini() {}
241 #endif
242
243 public:
244 BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
245 m_deadline(std::chrono::steady_clock::now() + timeout), m_socket(invalid_socket()) {
246 socket_init();
247
248 // A constructor that throws does not run its destructor, so do
249 // cleanup explicitly on any failure between socket_init() above and
250 // the end of construction below.
251 try {
252 do_connect(hostname, service);
253 } catch(...) {
254 if(m_socket != invalid_socket()) {
255 close_socket(m_socket);
256 m_socket = invalid_socket();
257 }
258 socket_fini();
259 throw;
260 }
261 }
262
263 private:
264 void do_connect(std::string_view hostname, std::string_view service) {
265 const std::string hostname_str(hostname);
266 const std::string service_str(service);
267
268 addrinfo hints{};
269 hints.ai_family = AF_UNSPEC;
270 hints.ai_socktype = SOCK_STREAM;
271
272 unique_addr_info_ptr res = nullptr;
273
274 // getaddrinfo blocks; POSIX has no portable way to time-bound it
275 // without spinning up a thread. Time spent here is still deducted
276 // from the socket's overall deadline.
277 const int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, Botan::out_ptr(res));
278 if(rc != 0) {
279 throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
280 }
281
282 for(const addrinfo* rp = res.get(); (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
283 if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
284 continue;
285 }
286
287 // Bound the total connect phase by the deadline, regardless of
288 // how many candidate addresses getaddrinfo returns.
289 const auto remaining = remaining_time();
290 if(remaining <= std::chrono::microseconds::zero()) {
291 break;
292 }
293
294 m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
295
296 if(m_socket == invalid_socket()) {
297 // unsupported socket type?
298 continue;
299 }
300
301 #if !defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
302 // POSIX fd_set is a bitfield indexed by fd value, so FD_SET(fd, ...)
303 // with fd >= FD_SETSIZE writes past the end of the structure. Refuse
304 // up front rather than corrupt memory in the select() path below.
305 // (Windows fd_set is an array of SOCKET handles, not vulnerable.)
306 if(m_socket >= FD_SETSIZE) {
307 close_socket(m_socket);
308 m_socket = invalid_socket();
309 throw System_Error("Socket descriptor exceeds FD_SETSIZE; select() would be unsafe");
310 }
311 #endif
312
313 #if defined(SO_NOSIGPIPE)
314 // macOS doesn't have MSG_NOSIGNAL; set the socket option instead so
315 // ::send() on a peer-closed socket returns EPIPE rather than
316 // delivering SIGPIPE to the process. Ignore failures (best-effort).
317 {
318 const int on = 1;
319 (void)::setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
320 }
321 #endif
322
323 set_nonblocking(m_socket);
324
325 const int err = ::connect(m_socket, rp->ai_addr, static_cast<socklen_type>(rp->ai_addrlen));
326
327 if(err == -1) {
328 int active = 0;
329 if(nonblocking_connect_in_progress()) {
330 struct timeval timeout_tv = make_timeout_tv_from(remaining);
331 fd_set write_set;
332 FD_ZERO(&write_set);
333 FD_SET(m_socket, &write_set);
334
335 active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout_tv);
336
337 if(active > 0) {
338 int socket_error = 0;
339 socklen_t len = sizeof(socket_error);
340
341 if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) <
342 0) {
343 throw System_Error("Error calling getsockopt", last_socket_error());
344 }
345
346 if(socket_error != 0) {
347 active = 0;
348 }
349 }
350 }
351
352 // 0 = select timeout, < 0 = select error: both indicate the
353 // connect attempt failed and the socket is not usable.
354 if(active <= 0) {
355 close_socket(m_socket);
356 m_socket = invalid_socket();
357 continue;
358 }
359 }
360 }
361
362 if(m_socket == invalid_socket()) {
363 throw System_Error(
364 fmt("Connecting to {} for service {} failed with errno {}", hostname, service, last_socket_error()),
365 last_socket_error());
366 }
367 }
368
369 public:
370 ~BSD_Socket() override {
371 close_socket(m_socket);
372 m_socket = invalid_socket();
373 socket_fini();
374 }
375
376 BSD_Socket(const BSD_Socket& other) = delete;
377 BSD_Socket(BSD_Socket&& other) = delete;
378 BSD_Socket& operator=(const BSD_Socket& other) = delete;
379 BSD_Socket& operator=(BSD_Socket&& other) = delete;
380
381 void write(std::span<const uint8_t> buf) override {
382 const size_t len = buf.size();
383
384 size_t sent_so_far = 0;
385 while(sent_so_far != len) {
386 fd_set write_set;
387 FD_ZERO(&write_set);
388 FD_SET(m_socket, &write_set);
389
390 const auto remaining = remaining_time();
391 if(remaining <= std::chrono::microseconds::zero()) {
392 throw System_Error("Timeout during socket write");
393 }
394
395 struct timeval timeout = make_timeout_tv_from(remaining);
396 const int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
397
398 if(active < 0) {
399 if(last_error_is_retryable()) {
400 continue;
401 }
402 throw System_Error("Socket select failed", last_socket_error());
403 }
404
405 if(active == 0) {
406 throw System_Error("Timeout during socket write");
407 }
408
409 const size_t left = len - sent_so_far;
410 const socket_op_ret_type sent = ::send(m_socket,
411 cast_uint8_ptr_to_char(&buf[sent_so_far]),
412 static_cast<sendrecv_len_type>(left),
413 botan_send_flags);
414 if(sent < 0) {
415 if(last_error_is_retryable()) {
416 continue;
417 }
418 throw System_Error("Socket write failed", last_socket_error());
419 } else {
420 sent_so_far += static_cast<size_t>(sent);
421 }
422 }
423 }
424
425 size_t read(uint8_t buf[], size_t len) override {
426 for(;;) {
427 fd_set read_set;
428 FD_ZERO(&read_set);
429 FD_SET(m_socket, &read_set);
430
431 const auto remaining = remaining_time();
432 if(remaining <= std::chrono::microseconds::zero()) {
433 throw System_Error("Timeout during socket read");
434 }
435
436 struct timeval timeout = make_timeout_tv_from(remaining);
437 const int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
438
439 if(active < 0) {
440 if(last_error_is_retryable()) {
441 continue;
442 }
443 throw System_Error("Socket select failed", last_socket_error());
444 }
445
446 if(active == 0) {
447 throw System_Error("Timeout during socket read");
448 }
449
450 const socket_op_ret_type got =
451 ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);
452
453 if(got < 0) {
454 if(last_error_is_retryable()) {
455 continue;
456 }
457 throw System_Error("Socket read failed", last_socket_error());
458 }
459
460 return static_cast<size_t>(got);
461 }
462 }
463
464 private:
465 std::chrono::microseconds remaining_time() const {
466 return std::chrono::duration_cast<std::chrono::microseconds>(m_deadline - std::chrono::steady_clock::now());
467 }
468
469 static struct timeval make_timeout_tv_from(std::chrono::microseconds us) {
470 struct timeval tv {};
471
472 tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(us.count() / 1000000);
473 tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(us.count() % 1000000);
474 return tv;
475 }
476
477 const std::chrono::steady_clock::time_point m_deadline;
478 socket_type m_socket;
479
480 using unique_addr_info_ptr = std::unique_ptr<addrinfo, decltype([](addrinfo* p) {
481 if(p != nullptr) {
482 ::freeaddrinfo(p);
483 }
484 })>;
485};
486
487#endif
488
489} // namespace
490
491std::unique_ptr<OS::Socket> OS::open_socket(std::string_view hostname,
492 std::string_view service,
493 std::chrono::milliseconds timeout) {
494#if defined(BOTAN_HAS_BOOST_ASIO)
495 return std::make_unique<Asio_Socket>(hostname, service, timeout);
496
497#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
498 return std::make_unique<BSD_Socket>(hostname, service, timeout);
499
500#else
501 BOTAN_UNUSED(hostname, service, timeout);
502 // No sockets for you
503 return std::unique_ptr<Socket>();
504#endif
505}
506
507} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:151
std::unique_ptr< Socket > BOTAN_TEST_API open_socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout)
Definition socket.cpp:491
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