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