Botan 3.9.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/target_info.h>
14#include <chrono>
15
16#if defined(BOTAN_HAS_BOOST_ASIO)
17 /*
18 * We don't need serial port support anyway, and asking for it causes
19 * macro conflicts with termios.h when this file is included in the
20 * amalgamation.
21 */
22 #define BOOST_ASIO_DISABLE_SERIAL_PORT
23 #include <boost/asio.hpp>
24 #include <boost/asio/system_timer.hpp>
25
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)
45
46class Asio_Socket final : public OS::Socket {
47 public:
48 Asio_Socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout) :
49 m_timeout(timeout), m_timer(m_io), m_tcp(m_io) {
50 m_timer.expires_after(m_timeout);
51 check_timeout();
52
53 boost::asio::ip::tcp::resolver resolver(m_io);
54 boost::asio::ip::tcp::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, const auto&) { ec = e; };
60
61 boost::asio::async_connect(m_tcp, 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_tcp.is_open()) {
71 throw System_Error(fmt("Connection to host {} failed", hostname));
72 }
73 }
74
75 void write(std::span<const uint8_t> buf) override {
76 m_timer.expires_after(m_timeout);
77
78 boost::system::error_code ec = boost::asio::error::would_block;
79
80 // Some versions of asio don't know about span...
81 m_tcp.async_send(boost::asio::buffer(buf.data(), buf.size()),
82 [&ec](boost::system::error_code e, size_t) { ec = e; });
83
84 while(ec == boost::asio::error::would_block) {
85 m_io.run_one();
86 }
87
88 if(ec) {
89 throw boost::system::system_error(ec);
90 }
91 }
92
93 size_t read(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 size_t got = 0;
98
99 m_tcp.async_read_some(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
100 ec = cb_ec;
101 got = cb_got;
102 });
103
104 while(ec == boost::asio::error::would_block) {
105 m_io.run_one();
106 }
107
108 if(ec) {
109 if(ec == boost::asio::error::eof) {
110 return 0;
111 }
112 throw boost::system::system_error(ec); // Some other error.
113 }
114
115 return got;
116 }
117
118 private:
119 void check_timeout() {
120 if(m_tcp.is_open() && m_timer.expiry() < std::chrono::system_clock::now()) {
121 boost::system::error_code err;
122
123 // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
124 m_tcp.close(err);
125 }
126
127 // NOLINTNEXTLINE(*-avoid-bind) FIXME - unclear why we can't use a lambda here
128 m_timer.async_wait(std::bind(&Asio_Socket::check_timeout, this));
129 }
130
131 const std::chrono::milliseconds m_timeout;
132 boost::asio::io_context m_io;
133 boost::asio::system_timer m_timer;
134 boost::asio::ip::tcp::socket m_tcp;
135};
136
137#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
138
139class BSD_Socket final : public OS::Socket {
140 private:
141 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
142 typedef SOCKET socket_type;
143 typedef int socket_op_ret_type;
144 typedef int socklen_type;
145 typedef int sendrecv_len_type;
146
147 static socket_type invalid_socket() { return INVALID_SOCKET; }
148
149 static void close_socket(socket_type s) { ::closesocket(s); }
150
151 static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
152
153 static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
154
155 static void set_nonblocking(socket_type s) {
156 u_long nonblocking = 1;
157 ::ioctlsocket(s, FIONBIO, &nonblocking);
158 }
159
160 static void socket_init() {
161 WSAData wsa_data;
162 WORD wsa_version = MAKEWORD(2, 2);
163
164 if(::WSAStartup(wsa_version, &wsa_data) != 0) {
165 throw System_Error("WSAStartup() failed", WSAGetLastError());
166 }
167
168 if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
169 ::WSACleanup();
170 throw System_Error("Could not find a usable version of Winsock.dll");
171 }
172 }
173
174 static void socket_fini() { ::WSACleanup(); }
175 #else
176 typedef int socket_type;
177 typedef ssize_t socket_op_ret_type;
178 typedef socklen_t socklen_type;
179 typedef size_t sendrecv_len_type;
180
181 static socket_type invalid_socket() { return -1; }
182
183 static void close_socket(socket_type s) { ::close(s); }
184
185 static std::string get_last_socket_error() { return ::strerror(errno); }
186
187 static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
188
189 static void set_nonblocking(socket_type s) {
190 if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
191 throw System_Error("Setting socket to non-blocking state failed", errno);
192 }
193 }
194
195 static void socket_init() {}
196
197 static void socket_fini() {}
198 #endif
199
200 public:
201 BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
202 m_timeout(timeout) {
203 socket_init();
204
205 m_socket = invalid_socket();
206
207 addrinfo hints;
208 clear_mem(&hints, 1);
209 hints.ai_family = AF_UNSPEC;
210 hints.ai_socktype = SOCK_STREAM;
211 addrinfo* res = nullptr;
212
213 const std::string hostname_str(hostname);
214 const std::string service_str(service);
215
216 int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, &res);
217
218 if(rc != 0) {
219 throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
220 }
221
222 for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
223 if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
224 continue;
225 }
226
227 m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
228
229 if(m_socket == invalid_socket()) {
230 // unsupported socket type?
231 continue;
232 }
233
234 set_nonblocking(m_socket);
235
236 int err = ::connect(m_socket, rp->ai_addr, static_cast<socklen_type>(rp->ai_addrlen));
237
238 if(err == -1) {
239 int active = 0;
240 if(nonblocking_connect_in_progress()) {
241 struct timeval timeout_tv = make_timeout_tv();
242 fd_set write_set;
243 FD_ZERO(&write_set);
244 // Weirdly, Winsock uses a SOCKET type but wants FD_SET to get an int instead
245 FD_SET(static_cast<int>(m_socket), &write_set);
246
247 active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout_tv);
248
249 if(active) {
250 int socket_error = 0;
251 socklen_t len = sizeof(socket_error);
252
253 if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) <
254 0) {
255 throw System_Error("Error calling getsockopt", errno);
256 }
257
258 if(socket_error != 0) {
259 active = 0;
260 }
261 }
262 }
263
264 if(active == 0) {
265 close_socket(m_socket);
266 m_socket = invalid_socket();
267 continue;
268 }
269 }
270 }
271
272 ::freeaddrinfo(res);
273
274 if(m_socket == invalid_socket()) {
275 throw System_Error(fmt("Connecting to {} for service {} failed with errno {}", hostname, service, errno),
276 errno);
277 }
278 }
279
280 ~BSD_Socket() override {
281 close_socket(m_socket);
282 m_socket = invalid_socket();
283 socket_fini();
284 }
285
286 BSD_Socket(const BSD_Socket& other) = delete;
287 BSD_Socket(BSD_Socket&& other) = delete;
288 BSD_Socket& operator=(const BSD_Socket& other) = delete;
289 BSD_Socket& operator=(BSD_Socket&& other) = delete;
290
291 void write(std::span<const uint8_t> buf) override {
292 fd_set write_set;
293 FD_ZERO(&write_set);
294 FD_SET(m_socket, &write_set);
295
296 size_t len = buf.size();
297
298 size_t sent_so_far = 0;
299 while(sent_so_far != len) {
300 struct timeval timeout = make_timeout_tv();
301 int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
302
303 if(active == 0) {
304 throw System_Error("Timeout during socket write");
305 }
306
307 const size_t left = len - sent_so_far;
308 socket_op_ret_type sent =
309 ::send(m_socket, cast_uint8_ptr_to_char(&buf[sent_so_far]), static_cast<sendrecv_len_type>(left), 0);
310 if(sent < 0) {
311 throw System_Error("Socket write failed", errno);
312 } else {
313 sent_so_far += static_cast<size_t>(sent);
314 }
315 }
316 }
317
318 size_t read(uint8_t buf[], size_t len) override {
319 fd_set read_set;
320 FD_ZERO(&read_set);
321 FD_SET(m_socket, &read_set);
322
323 struct timeval timeout = make_timeout_tv();
324 int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
325
326 if(active == 0) {
327 throw System_Error("Timeout during socket read");
328 }
329
330 socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);
331
332 if(got < 0) {
333 throw System_Error("Socket read failed", errno);
334 }
335
336 return static_cast<size_t>(got);
337 }
338
339 private:
340 struct timeval make_timeout_tv() const {
341 struct timeval tv;
342 tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
343 tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
344 return tv;
345 }
346
347 const std::chrono::microseconds m_timeout;
348 socket_type m_socket;
349};
350
351#endif
352
353} // namespace
354
355std::unique_ptr<OS::Socket> OS::open_socket(std::string_view hostname,
356 std::string_view service,
357 std::chrono::milliseconds timeout) {
358#if defined(BOTAN_HAS_BOOST_ASIO)
359 return std::make_unique<Asio_Socket>(hostname, service, timeout);
360
361#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
362 return std::make_unique<BSD_Socket>(hostname, service, timeout);
363
364#else
365 BOTAN_UNUSED(hostname, service, timeout);
366 // No sockets for you
367 return std::unique_ptr<Socket>();
368#endif
369}
370
371} // 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:355
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53