Botan 2.13.0 Crypto and TLS for C++11

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

socket_udp.cpp
Go to the documentation of this file.
1 /*
2 * (C) 2015,2016,2017 Jack Lloyd
3 * (C) 2016 Daniel Neus
4 * (C) 2019 Nuno Goncalves <nunojpg@gmail.com>
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 */
8
9 #include <botan/internal/socket_udp.h>
10 #include <botan/internal/uri.h>
11 #include <botan/exceptn.h>
12 #include <botan/mem_ops.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
18 * causes macro conflicts with Darwin's termios.h when this
19 * file is included in the amalgamation. GH #350
20 */
21 #define BOOST_ASIO_DISABLE_SERIAL_PORT
22 #include <boost/asio.hpp>
23 #include <boost/asio/system_timer.hpp>
24 #elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
25 #include <sys/socket.h>
26 #include <sys/time.h>
27 #include <netinet/in.h>
28 #include <netdb.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <fcntl.h>
33
34 #elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
35 #include <ws2tcpip.h>
36 #endif
37
38 namespace Botan {
39
40 namespace {
41
42 #if defined(BOTAN_HAS_BOOST_ASIO)
43 class Asio_SocketUDP final : public OS::SocketUDP
44 {
45 public:
46 Asio_SocketUDP(const std::string& hostname,
47 const std::string& service,
48 std::chrono::microseconds timeout) :
49 m_timeout(timeout), m_timer(m_io), m_udp(m_io)
50 {
51 m_timer.expires_from_now(m_timeout);
52 check_timeout();
53
54 boost::asio::ip::udp::resolver resolver(m_io);
55 boost::asio::ip::udp::resolver::query query(hostname, service);
56 boost::asio::ip::udp::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::udp::resolver::iterator) { ec = e; };
62
63 boost::asio::async_connect(m_udp, 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_udp.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_udp.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)
86 {
87 m_io.run_one();
88 }
89
90 if(ec)
91 {
92 throw boost::system::system_error(ec);
93 }
94 }
95
96 size_t read(uint8_t buf[], size_t len) override
97 {
98 m_timer.expires_from_now(m_timeout);
99
100 boost::system::error_code ec = boost::asio::error::would_block;
101 size_t got = 0;
102
103 m_udp.async_receive(boost::asio::buffer(buf, len),
104 [&](boost::system::error_code cb_ec, size_t cb_got) { ec = cb_ec; got = cb_got; });
105
106 while(ec == boost::asio::error::would_block)
107 {
108 m_io.run_one();
109 }
110
111 if(ec)
112 {
113 if(ec == boost::asio::error::eof)
114 { return 0; }
115 throw boost::system::system_error(ec); // Some other error.
116 }
117
118 return got;
119 }
120
121 private:
122 void check_timeout()
123 {
124 if(m_udp.is_open() && m_timer.expires_at() < std::chrono::system_clock::now())
125 {
126 boost::system::error_code err;
127 m_udp.close(err);
128 }
129
130 m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout, this));
131 }
132
133 const std::chrono::microseconds m_timeout;
134 boost::asio::io_service m_io;
135 boost::asio::system_timer m_timer;
136 boost::asio::ip::udp::socket m_udp;
137 };
138 #elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
139 class BSD_SocketUDP final : public OS::SocketUDP
140 {
141 public:
142 BSD_SocketUDP(const std::string& hostname,
143 const std::string& service,
144 std::chrono::microseconds timeout) : m_timeout(timeout)
145 {
146 socket_init();
147
148 m_socket = invalid_socket();
149
150 addrinfo* res;
151 addrinfo hints;
152 clear_mem(&hints, 1);
153 hints.ai_family = AF_UNSPEC;
154 hints.ai_socktype = SOCK_DGRAM;
155
156 int rc = ::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res);
157
158 if(rc != 0)
159 {
160 throw System_Error("Name resolution failed for " + hostname, rc);
161 }
162
163 for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next)
164 {
165 if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6)
166 { continue; }
167
168 m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
169
170 if(m_socket == invalid_socket())
171 {
172 // unsupported socket type?
173 continue;
174 }
175
176 set_nonblocking(m_socket);
177 memcpy(&sa, res->ai_addr, res->ai_addrlen);
178 salen = static_cast<socklen_t>(res->ai_addrlen);
179 }
180
181 ::freeaddrinfo(res);
182
183 if(m_socket == invalid_socket())
184 {
185 throw System_Error("Connecting to " + hostname +
186 " for service " + service + " failed", errno);
187 }
188 }
189
190 ~BSD_SocketUDP()
191 {
192 close_socket(m_socket);
193 m_socket = invalid_socket();
194 socket_fini();
195 }
196
197 void write(const uint8_t buf[], size_t len) override
198 {
199 fd_set write_set;
200 FD_ZERO(&write_set);
201 FD_SET(m_socket, &write_set);
202
203 size_t sent_so_far = 0;
204 while(sent_so_far != len)
205 {
206 struct timeval timeout = make_timeout_tv();
207 int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
208
209 if(active == 0)
210 { throw System_Error("Timeout during socket write"); }
211
212 const size_t left = len - sent_so_far;
213 socket_op_ret_type sent = ::sendto(m_socket, cast_uint8_ptr_to_char(buf + sent_so_far), static_cast<sendrecv_len_type>(left), 0, (sockaddr*)&sa, salen);
214 if(sent < 0)
215 { throw System_Error("Socket write failed", errno); }
216 else
217 { sent_so_far += static_cast<size_t>(sent); }
218 }
219 }
220
221 size_t read(uint8_t buf[], size_t len) override
222 {
223 fd_set read_set;
224 FD_ZERO(&read_set);
225 FD_SET(m_socket, &read_set);
226
227 struct timeval timeout = make_timeout_tv();
228 int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
229
230 if(active == 0)
231 { throw System_Error("Timeout during socket read"); }
232
233 socket_op_ret_type got = ::recvfrom(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0, nullptr, nullptr);
234
235 if(got < 0)
236 { throw System_Error("Socket read failed", errno); }
237
238 return static_cast<size_t>(got);
239 }
240
241 private:
242 #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
243 typedef SOCKET socket_type;
244 typedef int socket_op_ret_type;
245 typedef int sendrecv_len_type;
246 static socket_type invalid_socket() { return INVALID_SOCKET; }
247 static void close_socket(socket_type s) { ::closesocket(s); }
248 static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
249
250 static bool nonblocking_connect_in_progress()
251 {
252 return (::WSAGetLastError() == WSAEWOULDBLOCK);
253 }
254
255 static void set_nonblocking(socket_type s)
256 {
257 u_long nonblocking = 1;
258 ::ioctlsocket(s, FIONBIO, &nonblocking);
259 }
260
261 static void socket_init()
262 {
263 WSAData wsa_data;
264 WORD wsa_version = MAKEWORD(2, 2);
265
266 if(::WSAStartup(wsa_version, &wsa_data) != 0)
267 {
268 throw System_Error("WSAStartup() failed", WSAGetLastError());
269 }
270
271 if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
272 {
273 ::WSACleanup();
274 throw System_Error("Could not find a usable version of Winsock.dll");
275 }
276 }
277
278 static void socket_fini()
279 {
280 ::WSACleanup();
281 }
282 #else
283 typedef int socket_type;
284 typedef ssize_t socket_op_ret_type;
285 typedef size_t sendrecv_len_type;
286 static socket_type invalid_socket() { return -1; }
287 static void close_socket(socket_type s) { ::close(s); }
288 static std::string get_last_socket_error() { return ::strerror(errno); }
289 static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
290 static void set_nonblocking(socket_type s)
291 {
292 if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0)
293 { throw System_Error("Setting socket to non-blocking state failed", errno); }
294 }
295
296 static void socket_init() {}
297 static void socket_fini() {}
298 #endif
299 sockaddr_storage sa;
300 socklen_t salen;
301 struct timeval make_timeout_tv() const
302 {
303 struct timeval tv;
304 tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
305 tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);;
306 return tv;
307 }
308
309 const std::chrono::microseconds m_timeout;
310 socket_type m_socket;
311 };
312 #endif
313 }
314
315 std::unique_ptr<OS::SocketUDP>
316 OS::open_socket_udp(const std::string& hostname,
317 const std::string& service,
318 std::chrono::microseconds timeout)
319 {
320 #if defined(BOTAN_HAS_BOOST_ASIO)
321 return std::unique_ptr<OS::SocketUDP>(new Asio_SocketUDP(hostname, service, timeout));
322 #elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
323 return std::unique_ptr<OS::SocketUDP>(new BSD_SocketUDP(hostname, service, timeout));
324 #else
325 BOTAN_UNUSED(hostname);
326 BOTAN_UNUSED(service);
327 BOTAN_UNUSED(timeout);
328 return std::unique_ptr<OS::SocketUDP>();
329 #endif
330 }
331
332 std::unique_ptr<OS::SocketUDP>
333 OS::open_socket_udp(const std::string& uri_string,
334 std::chrono::microseconds timeout)
335 {
336 const auto uri = URI::fromAny(uri_string);
337 if(uri.port == 0)
338 { throw Invalid_Argument("UDP port not specified"); }
339 return open_socket_udp(uri.host, std::to_string(uri.port), timeout);
340 }
341
342 }
Botan::OS::open_socket_udp
std::unique_ptr< SocketUDP > BOTAN_TEST_API open_socket_udp(const std::string &hostname, const std::string &service, std::chrono::microseconds timeout)
Definition: socket_udp.cpp:316
Botan::Invalid_Argument
Definition: exceptn.h:136
Botan::clear_mem
void clear_mem(T *ptr, size_t n)
Definition: mem_ops.h:112
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_udp.cpp:134
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_udp.cpp:135
m_timeout
const std::chrono::microseconds m_timeout
Definition: socket_udp.cpp:133
m_udp
boost::asio::ip::udp::socket m_udp
Definition: socket_udp.cpp:136
Botan::URI::fromAny
static URI fromAny(const std::string &uri)
Definition: uri.cpp:184