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