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

randombit / botan / 11631334564

01 Nov 2024 02:54PM UTC coverage: 91.031% (-0.04%) from 91.072%
11631334564

Pull #4422

github

web-flow
Merge c66020351 into bd045b1a0
Pull Request #4422: Chore: Centralize some Repository Config

90350 of 99252 relevant lines covered (91.03%)

9489034.7 hits per line

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

90.0
/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, const 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
         }
71
         if(m_tcp.is_open() == false) {
1✔
72
            throw System_Error(fmt("Connection to host {} failed", hostname));
×
73
         }
74
      }
2✔
75

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

79
         boost::system::error_code ec = boost::asio::error::would_block;
1✔
80

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

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

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

92
      size_t read(uint8_t buf[], size_t len) override {
1✔
93
         m_timer.expires_from_now(m_timeout);
1✔
94

95
         boost::system::error_code ec = boost::asio::error::would_block;
1✔
96
         size_t got = 0;
1✔
97

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

103
         while(ec == boost::asio::error::would_block) {
4✔
104
            m_io.run_one();
3✔
105
         }
106

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

114
         return got;
×
115
      }
116

117
   private:
118
      void check_timeout() {
4✔
119
         if(m_tcp.is_open() && m_timer.expires_at() < std::chrono::system_clock::now()) {
4✔
120
            boost::system::error_code err;
1✔
121

122
            // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
123
            m_tcp.close(err);
1✔
124
         }
125

126
         m_timer.async_wait(std::bind(&Asio_Socket::check_timeout, this));
4✔
127
      }
4✔
128

129
      const std::chrono::milliseconds m_timeout;
130
      boost::asio::io_service m_io;
131
      boost::asio::system_timer m_timer;
132
      boost::asio::ip::tcp::socket m_tcp;
133
};
134

135
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
136

137
class BSD_Socket final : public OS::Socket {
138
   private:
139
   #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
140
      typedef SOCKET socket_type;
141
      typedef int socket_op_ret_type;
142
      typedef int socklen_type;
143
      typedef int sendrecv_len_type;
144

145
      static socket_type invalid_socket() { return INVALID_SOCKET; }
146

147
      static void close_socket(socket_type s) { ::closesocket(s); }
148

149
      static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
150

151
      static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
152

153
      static void set_nonblocking(socket_type s) {
154
         u_long nonblocking = 1;
155
         ::ioctlsocket(s, FIONBIO, &nonblocking);
156
      }
157

158
      static void socket_init() {
159
         WSAData wsa_data;
160
         WORD wsa_version = MAKEWORD(2, 2);
161

162
         if(::WSAStartup(wsa_version, &wsa_data) != 0) {
163
            throw System_Error("WSAStartup() failed", WSAGetLastError());
164
         }
165

166
         if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
167
            ::WSACleanup();
168
            throw System_Error("Could not find a usable version of Winsock.dll");
169
         }
170
      }
171

172
      static void socket_fini() { ::WSACleanup(); }
173
   #else
174
      typedef int socket_type;
175
      typedef ssize_t socket_op_ret_type;
176
      typedef socklen_t socklen_type;
177
      typedef size_t sendrecv_len_type;
178

179
      static socket_type invalid_socket() { return -1; }
180

181
      static void close_socket(socket_type s) { ::close(s); }
182

183
      static std::string get_last_socket_error() { return ::strerror(errno); }
184

185
      static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
186

187
      static void set_nonblocking(socket_type s) {
188
         if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
189
            throw System_Error("Setting socket to non-blocking state failed", errno);
190
         }
191
      }
192

193
      static void socket_init() {}
194

195
      static void socket_fini() {}
196
   #endif
197

198
   public:
199
      BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
200
            m_timeout(timeout) {
201
         socket_init();
202

203
         m_socket = invalid_socket();
204

205
         addrinfo hints;
206
         clear_mem(&hints, 1);
207
         hints.ai_family = AF_UNSPEC;
208
         hints.ai_socktype = SOCK_STREAM;
209
         addrinfo* res;
210

211
         const std::string hostname_str(hostname);
212
         const std::string service_str(service);
213

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

216
         if(rc != 0) {
217
            throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
218
         }
219

220
         for(addrinfo* rp = res; (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
221
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
222
               continue;
223
            }
224

225
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
226

227
            if(m_socket == invalid_socket()) {
228
               // unsupported socket type?
229
               continue;
230
            }
231

232
            set_nonblocking(m_socket);
233

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

236
            if(err == -1) {
237
               int active = 0;
238
               if(nonblocking_connect_in_progress()) {
239
                  struct timeval timeout_tv = make_timeout_tv();
240
                  fd_set write_set;
241
                  FD_ZERO(&write_set);
242
                  // Weirdly, Winsock uses a SOCKET type but wants FD_SET to get an int instead
243
                  FD_SET(static_cast<int>(m_socket), &write_set);
244

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

247
                  if(active) {
248
                     int socket_error = 0;
249
                     socklen_t len = sizeof(socket_error);
250

251
                     if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) <
252
                        0) {
253
                        throw System_Error("Error calling getsockopt", errno);
254
                     }
255

256
                     if(socket_error != 0) {
257
                        active = 0;
258
                     }
259
                  }
260
               }
261

262
               if(active == 0) {
263
                  close_socket(m_socket);
264
                  m_socket = invalid_socket();
265
                  continue;
266
               }
267
            }
268
         }
269

270
         ::freeaddrinfo(res);
271

272
         if(m_socket == invalid_socket()) {
273
            throw System_Error(fmt("Connecting to {} for service {} failed with errno {}", hostname, service, errno),
274
                               errno);
275
         }
276
      }
277

278
      ~BSD_Socket() override {
279
         close_socket(m_socket);
280
         m_socket = invalid_socket();
281
         socket_fini();
282
      }
283

284
      BSD_Socket(const BSD_Socket& other) = delete;
285
      BSD_Socket(BSD_Socket&& other) = delete;
286
      BSD_Socket& operator=(const BSD_Socket& other) = delete;
287
      BSD_Socket& operator=(BSD_Socket&& other) = delete;
288

289
      void write(const uint8_t buf[], size_t len) override {
290
         fd_set write_set;
291
         FD_ZERO(&write_set);
292
         FD_SET(m_socket, &write_set);
293

294
         size_t sent_so_far = 0;
295
         while(sent_so_far != len) {
296
            struct timeval timeout = make_timeout_tv();
297
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
298

299
            if(active == 0) {
300
               throw System_Error("Timeout during socket write");
301
            }
302

303
            const size_t left = len - sent_so_far;
304
            socket_op_ret_type sent =
305
               ::send(m_socket, cast_uint8_ptr_to_char(&buf[sent_so_far]), static_cast<sendrecv_len_type>(left), 0);
306
            if(sent < 0) {
307
               throw System_Error("Socket write failed", errno);
308
            } else {
309
               sent_so_far += static_cast<size_t>(sent);
310
            }
311
         }
312
      }
313

314
      size_t read(uint8_t buf[], size_t len) override {
315
         fd_set read_set;
316
         FD_ZERO(&read_set);
317
         FD_SET(m_socket, &read_set);
318

319
         struct timeval timeout = make_timeout_tv();
320
         int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
321

322
         if(active == 0) {
323
            throw System_Error("Timeout during socket read");
324
         }
325

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

328
         if(got < 0) {
329
            throw System_Error("Socket read failed", errno);
330
         }
331

332
         return static_cast<size_t>(got);
333
      }
334

335
   private:
336
      struct timeval make_timeout_tv() const {
337
         struct timeval tv;
338
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
339
         tv.tv_usec = static_cast<decltype(timeval::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
}  // namespace
350

351
std::unique_ptr<OS::Socket> OS::open_socket(std::string_view hostname,
1✔
352
                                            std::string_view service,
353
                                            std::chrono::milliseconds timeout) {
354
#if defined(BOTAN_HAS_BOOST_ASIO)
355
   return std::make_unique<Asio_Socket>(hostname, service, timeout);
1✔
356

357
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
358
   return std::make_unique<BSD_Socket>(hostname, service, timeout);
359

360
#else
361
   BOTAN_UNUSED(hostname);
362
   BOTAN_UNUSED(service);
363
   BOTAN_UNUSED(timeout);
364
   // No sockets for you
365
   return std::unique_ptr<Socket>();
366
#endif
367
}
368

369
}  // 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

© 2026 Coveralls, Inc