Botan  2.12.1
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 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  #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) { 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  typedef int socklen_type;
148  static socket_type invalid_socket() { return INVALID_SOCKET; }
149  static void close_socket(socket_type s) { ::closesocket(s); }
150  static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
151 
152  static bool nonblocking_connect_in_progress()
153  {
154  return (::WSAGetLastError() == WSAEWOULDBLOCK);
155  }
156 
157  static void set_nonblocking(socket_type s)
158  {
159  u_long nonblocking = 1;
160  ::ioctlsocket(s, FIONBIO, &nonblocking);
161  }
162 
163  static void socket_init()
164  {
165  WSAData wsa_data;
166  WORD wsa_version = MAKEWORD(2, 2);
167 
168  if (::WSAStartup(wsa_version, &wsa_data) != 0)
169  {
170  throw System_Error("WSAStartup() failed", WSAGetLastError());
171  }
172 
173  if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
174  {
175  ::WSACleanup();
176  throw System_Error("Could not find a usable version of Winsock.dll");
177  }
178  }
179 
180  static void socket_fini()
181  {
182  ::WSACleanup();
183  }
184 #else
185  typedef int socket_type;
186  typedef ssize_t socket_op_ret_type;
187  typedef socklen_t socklen_type;
188  static socket_type invalid_socket() { return -1; }
189  static void close_socket(socket_type s) { ::close(s); }
190  static std::string get_last_socket_error() { return ::strerror(errno); }
191  static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
192  static void set_nonblocking(socket_type s)
193  {
194  if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0)
195  throw System_Error("Setting socket to non-blocking state failed", errno);
196  }
197 
198  static void socket_init() {}
199  static void socket_fini() {}
200 #endif
201 
202  public:
203  BSD_Socket(const std::string& hostname,
204  const std::string& service,
205  std::chrono::microseconds timeout) : m_timeout(timeout)
206  {
207  socket_init();
208 
209  m_socket = invalid_socket();
210 
211  addrinfo hints;
212  clear_mem(&hints, 1);
213  hints.ai_family = AF_UNSPEC;
214  hints.ai_socktype = SOCK_STREAM;
215  addrinfo* res;
216 
217  int rc = ::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res);
218 
219  if(rc != 0)
220  {
221  throw System_Error("Name resolution failed for " + hostname, rc);
222  }
223 
224  for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next)
225  {
226  if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6)
227  continue;
228 
229  m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
230 
231  if(m_socket == invalid_socket())
232  {
233  // unsupported socket type?
234  continue;
235  }
236 
237  set_nonblocking(m_socket);
238 
239  int err = ::connect(m_socket, rp->ai_addr, static_cast<socklen_type>(rp->ai_addrlen));
240 
241  if(err == -1)
242  {
243  int active = 0;
244  if(nonblocking_connect_in_progress())
245  {
246  struct timeval timeout_tv = make_timeout_tv();
247  fd_set write_set;
248  FD_ZERO(&write_set);
249  // Weirdly, Winsock uses a SOCKET type but wants FD_SET to get an int instead
250  FD_SET(static_cast<int>(m_socket), &write_set);
251 
252  active = ::select(m_socket + 1, nullptr, &write_set, nullptr, &timeout_tv);
253 
254  if(active)
255  {
256  int socket_error = 0;
257  socklen_t len = sizeof(socket_error);
258 
259  if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) < 0)
260  throw System_Error("Error calling getsockopt", errno);
261 
262  if(socket_error != 0)
263  {
264  active = 0;
265  }
266  }
267  }
268 
269  if(active == 0)
270  {
271  close_socket(m_socket);
272  m_socket = invalid_socket();
273  continue;
274  }
275  }
276  }
277 
278  ::freeaddrinfo(res);
279 
280  if(m_socket == invalid_socket())
281  {
282  throw System_Error("Connecting to " + hostname +
283  " for service " + service + " failed", errno);
284  }
285  }
286 
287  ~BSD_Socket()
288  {
289  close_socket(m_socket);
290  m_socket = invalid_socket();
291  socket_fini();
292  }
293 
294  void write(const uint8_t buf[], size_t len) override
295  {
296  fd_set write_set;
297  FD_ZERO(&write_set);
298  FD_SET(m_socket, &write_set);
299 
300  size_t sent_so_far = 0;
301  while(sent_so_far != len)
302  {
303  struct timeval timeout = make_timeout_tv();
304  int active = ::select(m_socket + 1, nullptr, &write_set, nullptr, &timeout);
305 
306  if(active == 0)
307  throw System_Error("Timeout during socket write");
308 
309  const size_t left = len - sent_so_far;
310  socket_op_ret_type sent = ::send(m_socket, cast_uint8_ptr_to_char(&buf[sent_so_far]), left, 0);
311  if(sent < 0)
312  throw System_Error("Socket write failed", errno);
313  else
314  sent_so_far += static_cast<size_t>(sent);
315  }
316  }
317 
318  size_t read(uint8_t buf[], size_t len) override
319  {
320  fd_set read_set;
321  FD_ZERO(&read_set);
322  FD_SET(m_socket, &read_set);
323 
324  struct timeval timeout = make_timeout_tv();
325  int active = ::select(m_socket + 1, &read_set, nullptr, nullptr, &timeout);
326 
327  if(active == 0)
328  throw System_Error("Timeout during socket read");
329 
330  socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf), len, 0);
331 
332  if(got < 0)
333  throw System_Error("Socket read failed", errno);
334 
335  return static_cast<size_t>(got);
336  }
337 
338  private:
339  struct timeval make_timeout_tv() const
340  {
341  struct timeval tv;
342  tv.tv_sec = static_cast<time_t>(m_timeout.count() / 1000000);
343  tv.tv_usec = static_cast<long>(m_timeout.count() % 1000000);;
344  return tv;
345  }
346 
347  const std::chrono::microseconds m_timeout;
348  socket_type m_socket;
349  };
350 
351 #endif
352 
353 }
354 
355 std::unique_ptr<OS::Socket>
356 OS::open_socket(const std::string& hostname,
357  const std::string& service,
358  std::chrono::milliseconds timeout)
359  {
360 #if defined(BOTAN_HAS_BOOST_ASIO)
361  return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service, timeout));
362 
363 #elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
364  return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service, timeout));
365 
366 #else
367  // No sockets for you
368  return std::unique_ptr<Socket>();
369 #endif
370  }
371 
372 }
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:356
#define O_NONBLOCK
std::string to_string(const BER_Object &obj)
Definition: asn1_obj.cpp:213
Definition: alg_id.cpp:13
const char * cast_uint8_ptr_to_char(const uint8_t *b)
Definition: mem_ops.h:169