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