Botan 2.13.0 Crypto and TLS for C++11

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

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