• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 5111374265

29 May 2023 11:19AM UTC coverage: 92.227% (+0.5%) from 91.723%
5111374265

push

github

randombit
Next release will be 3.1.0. Update release notes

75588 of 81959 relevant lines covered (92.23%)

11886470.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.54
/src/lib/utils/socket/socket.cpp
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

10
#include <botan/exceptn.h>
11
#include <botan/mem_ops.h>
12
#include <botan/internal/fmt.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 causes
18
  * macro conflicts with termios.h when this file is included in the
19
  * amalgamation.
20
  */
21
   #define BOOST_ASIO_DISABLE_SERIAL_PORT
22
   #include <boost/asio.hpp>
23
   #include <boost/asio/system_timer.hpp>
24

25
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
26
   #include <errno.h>
27
   #include <fcntl.h>
28
   #include <netdb.h>
29
   #include <netinet/in.h>
30
   #include <string.h>
31
   #include <sys/socket.h>
32
   #include <sys/time.h>
33
   #include <unistd.h>
34

35
#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
36
   #include <ws2tcpip.h>
37
#endif
38

39
namespace Botan {
40

41
namespace {
42

43
#if defined(BOTAN_HAS_BOOST_ASIO)
44

45
class Asio_Socket final : public OS::Socket {
×
46
   public:
47
      Asio_Socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout) :
1✔
48
            m_timeout(timeout), m_timer(m_io), m_tcp(m_io) {
2✔
49
         m_timer.expires_from_now(m_timeout);
1✔
50
         check_timeout();
1✔
51

52
         boost::asio::ip::tcp::resolver resolver(m_io);
1✔
53
         boost::asio::ip::tcp::resolver::query query(std::string{hostname}, std::string{service});
4✔
54
         boost::asio::ip::tcp::resolver::iterator dns_iter = resolver.resolve(query);
1✔
55

56
         boost::system::error_code ec = boost::asio::error::would_block;
1✔
57

58
         auto connect_cb = [&ec](const boost::system::error_code& e, boost::asio::ip::tcp::resolver::iterator) {
2✔
59
            ec = e;
1✔
60
         };
1✔
61

62
         boost::asio::async_connect(m_tcp, dns_iter, connect_cb);
1✔
63

64
         while(ec == boost::asio::error::would_block) {
2✔
65
            m_io.run_one();
1✔
66
         }
67

68
         if(ec)
1✔
69
            throw boost::system::system_error(ec);
×
70
         if(m_tcp.is_open() == false)
1✔
71
            throw System_Error(fmt("Connection to host {} failed", hostname));
×
72
      }
1✔
73

74
      void write(const uint8_t buf[], size_t len) override {
1✔
75
         m_timer.expires_from_now(m_timeout);
1✔
76

77
         boost::system::error_code ec = boost::asio::error::would_block;
1✔
78

79
         m_tcp.async_send(boost::asio::buffer(buf, len), [&ec](boost::system::error_code e, size_t) { ec = e; });
2✔
80

81
         while(ec == boost::asio::error::would_block) {
3✔
82
            m_io.run_one();
2✔
83
         }
84

85
         if(ec) {
1✔
86
            throw boost::system::system_error(ec);
×
87
         }
88
      }
1✔
89

90
      size_t read(uint8_t buf[], size_t len) override {
2✔
91
         m_timer.expires_from_now(m_timeout);
2✔
92

93
         boost::system::error_code ec = boost::asio::error::would_block;
2✔
94
         size_t got = 0;
2✔
95

96
         m_tcp.async_read_some(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
2✔
97
            ec = cb_ec;
2✔
98
            got = cb_got;
2✔
99
         });
100

101
         while(ec == boost::asio::error::would_block) {
6✔
102
            m_io.run_one();
4✔
103
         }
104

105
         if(ec) {
2✔
106
            if(ec == boost::asio::error::eof)
1✔
107
               return 0;
1✔
108
            throw boost::system::system_error(ec);  // Some other error.
×
109
         }
110

111
         return got;
1✔
112
      }
1✔
113

114
   private:
115
      void check_timeout() {
4✔
116
         if(m_tcp.is_open() && m_timer.expires_at() < std::chrono::system_clock::now()) {
7✔
117
            boost::system::error_code err;
×
118
            m_tcp.close(err);
×
119
         }
120

121
         m_timer.async_wait(std::bind(&Asio_Socket::check_timeout, this));
4✔
122
      }
4✔
123

124
      const std::chrono::milliseconds m_timeout;
125
      boost::asio::io_service m_io;
126
      boost::asio::system_timer m_timer;
127
      boost::asio::ip::tcp::socket m_tcp;
128
};
129

130
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
131

132
class BSD_Socket final : public OS::Socket {
133
   private:
134
   #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
135
      typedef SOCKET socket_type;
136
      typedef int socket_op_ret_type;
137
      typedef int socklen_type;
138
      typedef int sendrecv_len_type;
139

140
      static socket_type invalid_socket() { return INVALID_SOCKET; }
141

142
      static void close_socket(socket_type s) { ::closesocket(s); }
143

144
      static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
145

146
      static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
147

148
      static void set_nonblocking(socket_type s) {
149
         u_long nonblocking = 1;
150
         ::ioctlsocket(s, FIONBIO, &nonblocking);
151
      }
152

153
      static void socket_init() {
154
         WSAData wsa_data;
155
         WORD wsa_version = MAKEWORD(2, 2);
156

157
         if(::WSAStartup(wsa_version, &wsa_data) != 0) {
158
            throw System_Error("WSAStartup() failed", WSAGetLastError());
159
         }
160

161
         if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
162
            ::WSACleanup();
163
            throw System_Error("Could not find a usable version of Winsock.dll");
164
         }
165
      }
166

167
      static void socket_fini() { ::WSACleanup(); }
168
   #else
169
      typedef int socket_type;
170
      typedef ssize_t socket_op_ret_type;
171
      typedef socklen_t socklen_type;
172
      typedef size_t sendrecv_len_type;
173

174
      static socket_type invalid_socket() { return -1; }
175

176
      static void close_socket(socket_type s) { ::close(s); }
177

178
      static std::string get_last_socket_error() { return ::strerror(errno); }
179

180
      static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
181

182
      static void set_nonblocking(socket_type s) {
183
         if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0)
184
            throw System_Error("Setting socket to non-blocking state failed", errno);
185
      }
186

187
      static void socket_init() {}
188

189
      static void socket_fini() {}
190
   #endif
191

192
   public:
193
      BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
194
            m_timeout(timeout) {
195
         socket_init();
196

197
         m_socket = invalid_socket();
198

199
         addrinfo hints;
200
         clear_mem(&hints, 1);
201
         hints.ai_family = AF_UNSPEC;
202
         hints.ai_socktype = SOCK_STREAM;
203
         addrinfo* res;
204

205
         const std::string hostname_str(hostname);
206
         const std::string service_str(service);
207

208
         int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, &res);
209

210
         if(rc != 0) {
211
            throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
212
         }
213

214
         for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
215
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6)
216
               continue;
217

218
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
219

220
            if(m_socket == invalid_socket()) {
221
               // unsupported socket type?
222
               continue;
223
            }
224

225
            set_nonblocking(m_socket);
226

227
            int err = ::connect(m_socket, rp->ai_addr, static_cast<socklen_type>(rp->ai_addrlen));
228

229
            if(err == -1) {
230
               int active = 0;
231
               if(nonblocking_connect_in_progress()) {
232
                  struct timeval timeout_tv = make_timeout_tv();
233
                  fd_set write_set;
234
                  FD_ZERO(&write_set);
235
                  // Weirdly, Winsock uses a SOCKET type but wants FD_SET to get an int instead
236
                  FD_SET(static_cast<int>(m_socket), &write_set);
237

238
                  active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout_tv);
239

240
                  if(active) {
241
                     int socket_error = 0;
242
                     socklen_t len = sizeof(socket_error);
243

244
                     if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) < 0)
245
                        throw System_Error("Error calling getsockopt", errno);
246

247
                     if(socket_error != 0) {
248
                        active = 0;
249
                     }
250
                  }
251
               }
252

253
               if(active == 0) {
254
                  close_socket(m_socket);
255
                  m_socket = invalid_socket();
256
                  continue;
257
               }
258
            }
259
         }
260

261
         ::freeaddrinfo(res);
262

263
         if(m_socket == invalid_socket()) {
264
            throw System_Error(fmt("Connecting to {} for service {} failed with errno {}", hostname, service, errno),
265
                               errno);
266
         }
267
      }
268

269
      ~BSD_Socket() override {
270
         close_socket(m_socket);
271
         m_socket = invalid_socket();
272
         socket_fini();
273
      }
274

275
      BSD_Socket(const BSD_Socket& other) = delete;
276
      BSD_Socket(BSD_Socket&& other) = delete;
277
      BSD_Socket& operator=(const BSD_Socket& other) = delete;
278
      BSD_Socket& operator=(BSD_Socket&& other) = delete;
279

280
      void write(const uint8_t buf[], size_t len) override {
281
         fd_set write_set;
282
         FD_ZERO(&write_set);
283
         FD_SET(m_socket, &write_set);
284

285
         size_t sent_so_far = 0;
286
         while(sent_so_far != len) {
287
            struct timeval timeout = make_timeout_tv();
288
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
289

290
            if(active == 0)
291
               throw System_Error("Timeout during socket write");
292

293
            const size_t left = len - sent_so_far;
294
            socket_op_ret_type sent =
295
               ::send(m_socket, cast_uint8_ptr_to_char(&buf[sent_so_far]), static_cast<sendrecv_len_type>(left), 0);
296
            if(sent < 0)
297
               throw System_Error("Socket write failed", errno);
298
            else
299
               sent_so_far += static_cast<size_t>(sent);
300
         }
301
      }
302

303
      size_t read(uint8_t buf[], size_t len) override {
304
         fd_set read_set;
305
         FD_ZERO(&read_set);
306
         FD_SET(m_socket, &read_set);
307

308
         struct timeval timeout = make_timeout_tv();
309
         int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
310

311
         if(active == 0)
312
            throw System_Error("Timeout during socket read");
313

314
         socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);
315

316
         if(got < 0)
317
            throw System_Error("Socket read failed", errno);
318

319
         return static_cast<size_t>(got);
320
      }
321

322
   private:
323
      struct timeval make_timeout_tv() const {
324
         struct timeval tv;
325
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
326
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
327
         return tv;
328
      }
329

330
      const std::chrono::microseconds m_timeout;
331
      socket_type m_socket;
332
};
333

334
#endif
335

336
}  // namespace
337

338
std::unique_ptr<OS::Socket> OS::open_socket(std::string_view hostname,
1✔
339
                                            std::string_view service,
340
                                            std::chrono::milliseconds timeout) {
341
#if defined(BOTAN_HAS_BOOST_ASIO)
342
   return std::make_unique<Asio_Socket>(hostname, service, timeout);
1✔
343

344
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
345
   return std::make_unique<BSD_Socket>(hostname, service, timeout);
346

347
#else
348
   BOTAN_UNUSED(hostname);
349
   BOTAN_UNUSED(service);
350
   BOTAN_UNUSED(timeout);
351
   // No sockets for you
352
   return std::unique_ptr<Socket>();
353
#endif
354
}
355

356
}  // namespace Botan
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc