Coverage Report

Created: 2021-01-13 07:05

/src/botan/src/lib/utils/socket/socket.cpp
Line
Count
Source (jump to first uncovered line)
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
0
      static socket_type invalid_socket() { return -1; }
185
0
      static void close_socket(socket_type s) { ::close(s); }
186
0
      static std::string get_last_socket_error() { return ::strerror(errno); }
187
0
      static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
188
      static void set_nonblocking(socket_type s)
189
0
         {
190
0
         if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0)
191
0
            throw System_Error("Setting socket to non-blocking state failed", errno);
192
0
         }
193
194
0
      static void socket_init() {}
195
0
      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
0
         {
203
0
         socket_init();
204
205
0
         m_socket = invalid_socket();
206
207
0
         addrinfo hints;
208
0
         clear_mem(&hints, 1);
209
0
         hints.ai_family = AF_UNSPEC;
210
0
         hints.ai_socktype = SOCK_STREAM;
211
0
         addrinfo* res;
212
213
0
         int rc = ::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res);
214
215
0
         if(rc != 0)
216
0
            {
217
0
            throw System_Error("Name resolution failed for " + hostname, rc);
218
0
            }
219
220
0
         for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next)
221
0
            {
222
0
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6)
223
0
               continue;
224
225
0
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
226
227
0
            if(m_socket == invalid_socket())
228
0
               {
229
               // unsupported socket type?
230
0
               continue;
231
0
               }
232
233
0
            set_nonblocking(m_socket);
234
235
0
            int err = ::connect(m_socket, rp->ai_addr, static_cast<socklen_type>(rp->ai_addrlen));
236
237
0
            if(err == -1)
238
0
               {
239
0
               int active = 0;
240
0
               if(nonblocking_connect_in_progress())
241
0
                  {
242
0
                  struct timeval timeout_tv = make_timeout_tv();
243
0
                  fd_set write_set;
244
0
                  FD_ZERO(&write_set);
245
                  // Weirdly, Winsock uses a SOCKET type but wants FD_SET to get an int instead
246
0
                  FD_SET(static_cast<int>(m_socket), &write_set);
247
248
0
                  active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout_tv);
249
250
0
                  if(active)
251
0
                     {
252
0
                     int socket_error = 0;
253
0
                     socklen_t len = sizeof(socket_error);
254
255
0
                     if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) < 0)
256
0
                        throw System_Error("Error calling getsockopt", errno);
257
258
0
                     if(socket_error != 0)
259
0
                        {
260
0
                        active = 0;
261
0
                        }
262
0
                     }
263
0
                  }
264
265
0
               if(active == 0)
266
0
                  {
267
0
                  close_socket(m_socket);
268
0
                  m_socket = invalid_socket();
269
0
                  continue;
270
0
                  }
271
0
               }
272
0
            }
273
274
0
         ::freeaddrinfo(res);
275
276
0
         if(m_socket == invalid_socket())
277
0
            {
278
0
            throw System_Error("Connecting to " + hostname +
279
0
                                " for service " + service + " failed", errno);
280
0
            }
281
0
         }
282
283
      ~BSD_Socket()
284
0
         {
285
0
         close_socket(m_socket);
286
0
         m_socket = invalid_socket();
287
0
         socket_fini();
288
0
         }
289
290
      void write(const uint8_t buf[], size_t len) override
291
0
         {
292
0
         fd_set write_set;
293
0
         FD_ZERO(&write_set);
294
0
         FD_SET(m_socket, &write_set);
295
296
0
         size_t sent_so_far = 0;
297
0
         while(sent_so_far != len)
298
0
            {
299
0
            struct timeval timeout = make_timeout_tv();
300
0
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
301
302
0
            if(active == 0)
303
0
               throw System_Error("Timeout during socket write");
304
305
0
            const size_t left = len - sent_so_far;
306
0
            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
0
            if(sent < 0)
308
0
               throw System_Error("Socket write failed", errno);
309
0
            else
310
0
               sent_so_far += static_cast<size_t>(sent);
311
0
            }
312
0
         }
313
314
      size_t read(uint8_t buf[], size_t len) override
315
0
         {
316
0
         fd_set read_set;
317
0
         FD_ZERO(&read_set);
318
0
         FD_SET(m_socket, &read_set);
319
320
0
         struct timeval timeout = make_timeout_tv();
321
0
         int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
322
323
0
         if(active == 0)
324
0
            throw System_Error("Timeout during socket read");
325
326
0
         socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);
327
328
0
         if(got < 0)
329
0
            throw System_Error("Socket read failed", errno);
330
331
0
         return static_cast<size_t>(got);
332
0
         }
333
334
   private:
335
      struct timeval make_timeout_tv() const
336
0
         {
337
0
         struct timeval tv;
338
0
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
339
0
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);;
340
0
         return tv;
341
0
         }
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
0
   {
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
0
   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
0
   }
370
371
}