Botan  2.4.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_TYPE_IS_UNIX)
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_TYPE_IS_WINDOWS) && !defined(BOTAN_TARGET_OS_IS_MINGW)
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 Exception("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) { printf("wrote %d\n", 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_TYPE_IS_UNIX) || (defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS) && !defined(BOTAN_TARGET_OS_IS_MINGW))
140 
141 class BSD_Socket final : public OS::Socket
142  {
143  private:
144 #if defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
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 Exception("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
170  }
171 
172  if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
173  {
174  ::WSACleanup();
175  throw Exception("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 Exception("Setting socket to non-blocking state failed");
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  ::memset(&hints, 0, sizeof(addrinfo));
211  hints.ai_family = AF_UNSPEC;
212  hints.ai_socktype = SOCK_STREAM;
213  addrinfo* res;
214 
215  if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
216  {
217  throw Exception("Name resolution failed for " + hostname);
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, 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  FD_SET(m_socket, &write_set);
246 
247  active = ::select(m_socket + 1, nullptr, &write_set, nullptr, &timeout_tv);
248 
249  if(active)
250  {
251  int socket_error = 0;
252  socklen_t len = sizeof(socket_error);
253 
254  if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) < 0)
255  throw Exception("Error calling getsockopt");
256 
257  if(socket_error != 0)
258  {
259  active = 0;
260  }
261  }
262  }
263 
264  if(active == 0)
265  {
266  close_socket(m_socket);
267  m_socket = invalid_socket();
268  continue;
269  }
270  }
271  }
272 
273  ::freeaddrinfo(res);
274 
275  if(m_socket == invalid_socket())
276  {
277  throw Exception("Connecting to " + hostname +
278  " for service " + service + " failed");
279  }
280  }
281 
282  ~BSD_Socket()
283  {
284  close_socket(m_socket);
285  m_socket = invalid_socket();
286  socket_fini();
287  }
288 
289  void write(const uint8_t buf[], size_t len) override
290  {
291  fd_set write_set;
292  FD_ZERO(&write_set);
293  FD_SET(m_socket, &write_set);
294 
295  size_t sent_so_far = 0;
296  while(sent_so_far != len)
297  {
298  struct timeval timeout = make_timeout_tv();
299  int active = ::select(m_socket + 1, nullptr, &write_set, nullptr, &timeout);
300 
301  if(active == 0)
302  throw Exception("Timeout during socket write");
303 
304  const size_t left = len - sent_so_far;
305  socket_op_ret_type sent = ::send(m_socket, cast_uint8_ptr_to_char(&buf[sent_so_far]), left, 0);
306  if(sent < 0)
307  throw Exception("Socket write failed with error '" +
308  std::string(::strerror(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(m_socket + 1, &read_set, nullptr, nullptr, &timeout);
322 
323  if(active == 0)
324  throw Exception("Timeout during socket read");
325 
326  socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf), len, 0);
327 
328  if(got < 0)
329  throw Exception("Socket read failed with error '" +
330  std::string(::strerror(errno)) + "'");
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 = m_timeout.count() / 1000000;
339  tv.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_TYPE_IS_UNIX) || (defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS) && !defined(BOTAN_TARGET_OS_IS_MINGW))
360  return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service, timeout));
361 
362 #else
363  // No sockets for you
364  return std::unique_ptr<Socket>();
365 #endif
366  }
367 
368 }
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
#define O_NONBLOCK
std::string to_string(const BER_Object &obj)
Definition: asn1_obj.cpp:108
T select(T mask, T from0, T from1)
Definition: ct_utils.h:106
Definition: alg_id.cpp:13
const char * cast_uint8_ptr_to_char(const uint8_t *b)
Definition: mem_ops.h:125