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