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

randombit / botan / 13429216726

20 Feb 2025 06:22AM UTC coverage: 91.647% (+0.003%) from 91.644%
13429216726

Pull #4660

github

web-flow
Merge b720e7b81 into a2981b3c6
Pull Request #4660: Consolidation and Enhancement of BSD Socket Layer

95032 of 103694 relevant lines covered (91.65%)

11432150.21 hits per line

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

85.42
/src/lib/utils/socket/socket.cpp
1
/*
2
* (C) 2015,2016,2017 Jack Lloyd
3
* (C) 2016 Daniel Neus
4
*     2025 Kagan Can Sit
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include <botan/internal/socket.h>
10
#include <botan/internal/socket_platform.h>
11

12
#include <botan/exceptn.h>
13
#include <botan/mem_ops.h>
14
#include <botan/internal/fmt.h>
15
#include <botan/internal/target_info.h>
16
#include <chrono>
17

18
#if defined(BOTAN_HAS_BOOST_ASIO)
19
   /*
20
  * We don't need serial port support anyway, and asking for it causes
21
  * macro conflicts with termios.h when this file is included in the
22
  * amalgamation.
23
  */
24
   #define BOOST_ASIO_DISABLE_SERIAL_PORT
25
   #include <boost/asio.hpp>
26
   #include <boost/asio/system_timer.hpp>
27
#endif
28

29
namespace Botan {
30
namespace {
31

32
#if defined(BOTAN_HAS_BOOST_ASIO)
33
class Asio_Socket final : public OS::Socket {
×
34
   public:
35
      Asio_Socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout) :
1✔
36
            m_timeout(timeout), m_timer(m_io), m_tcp(m_io) {
2✔
37
         m_timer.expires_after(m_timeout);
1✔
38
         check_timeout();
1✔
39

40
         boost::asio::ip::tcp::resolver resolver(m_io);
1✔
41
         boost::asio::ip::tcp::resolver::results_type dns_iter =
1✔
42
            resolver.resolve(std::string{hostname}, std::string{service});
3✔
43

44
         boost::system::error_code ec = boost::asio::error::would_block;
1✔
45

46
         auto connect_cb = [&ec](const boost::system::error_code& e, const auto&) { ec = e; };
1✔
47

48
         boost::asio::async_connect(m_tcp, dns_iter.begin(), dns_iter.end(), connect_cb);
2✔
49

50
         while(ec == boost::asio::error::would_block) {
2✔
51
            m_io.run_one();
1✔
52
         }
53

54
         if(ec) {
1✔
55
            throw boost::system::system_error(ec);
×
56
         }
57
         if(m_tcp.is_open() == false) {
1✔
58
            throw System_Error(fmt("Connection to host {} failed", hostname));
×
59
         }
60
      }
1✔
61

62
      void write(const uint8_t buf[], size_t len) override {
1✔
63
         m_timer.expires_after(m_timeout);
1✔
64

65
         boost::system::error_code ec = boost::asio::error::would_block;
1✔
66

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

69
         while(ec == boost::asio::error::would_block) {
3✔
70
            m_io.run_one();
2✔
71
         }
72

73
         if(ec) {
1✔
74
            throw boost::system::system_error(ec);
×
75
         }
76
      }
1✔
77

78
      size_t read(uint8_t buf[], size_t len) override {
2✔
79
         m_timer.expires_after(m_timeout);
2✔
80

81
         boost::system::error_code ec = boost::asio::error::would_block;
2✔
82
         size_t got = 0;
2✔
83

84
         m_tcp.async_read_some(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
2✔
85
            ec = cb_ec;
2✔
86
            got = cb_got;
2✔
87
         });
88

89
         while(ec == boost::asio::error::would_block) {
6✔
90
            m_io.run_one();
4✔
91
         }
92

93
         if(ec) {
2✔
94
            if(ec == boost::asio::error::eof) {
1✔
95
               return 0;
96
            }
97
            throw boost::system::system_error(ec);  // Some other error.
×
98
         }
99

100
         return got;
1✔
101
      }
102

103
   private:
104
      void check_timeout() {
4✔
105
         if(m_tcp.is_open() && m_timer.expiry() < std::chrono::system_clock::now()) {
4✔
106
            boost::system::error_code err;
×
107

108
            // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
109
            m_tcp.close(err);
×
110
         }
111

112
         m_timer.async_wait(std::bind(&Asio_Socket::check_timeout, this));
4✔
113
      }
4✔
114

115
      const std::chrono::milliseconds m_timeout;
116
      boost::asio::io_context m_io;
117
      boost::asio::system_timer m_timer;
118
      boost::asio::ip::tcp::socket m_tcp;
119
};
120

121
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
122

123
class BSD_Socket final : public OS::Socket {
124
   public:
125
      BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
126
            m_timeout(timeout) {
127
         Botan::OS::Socket_Platform::socket_init();
128
         m_socket = Botan::OS::Socket_Platform::invalid_socket();
129

130
         addrinfo hints;
131
         Botan::clear_mem(&hints, 1);
132
         hints.ai_family = AF_UNSPEC;
133
         hints.ai_socktype = SOCK_STREAM;
134

135
         addrinfo* res = nullptr;
136
         int rc = ::getaddrinfo(std::string(hostname).c_str(), std::string(service).c_str(), &hints, &res);
137

138
         if(rc != 0) {
139
            throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
140
         }
141
         std::unique_ptr<addrinfo, decltype(&::freeaddrinfo)> res_guard(res, ::freeaddrinfo);
142

143
         for(addrinfo* rp = res; (m_socket == Botan::OS::Socket_Platform::invalid_socket()) && rp != nullptr;
144
             rp = rp->ai_next) {
145
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
146
               continue;
147
            }
148

149
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
150

151
            if(m_socket == Botan::OS::Socket_Platform::invalid_socket()) {
152
               // unsupported socket type?
153
               continue;
154
            }
155

156
            Botan::OS::Socket_Platform::set_nonblocking(m_socket);
157

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

160
            if(err == -1) {
161
               int active = 0;
162
               if(Botan::OS::Socket_Platform::nonblocking_connect_in_progress()) {
163
                  struct timeval timeout_tv = make_timeout_tv();
164
                  fd_set write_set;
165
                  FD_ZERO(&write_set);
166
                  // Weirdly, Winsock uses a SOCKET type but wants FD_SET to get an int instead
167
                  FD_SET(static_cast<int>(m_socket), &write_set);
168

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

171
                  if(active) {
172
                     int socket_error = 0;
173
                     socklen_t len = sizeof(socket_error);
174

175
                     if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) <
176
                        0) {
177
                        throw System_Error("Error calling getsockopt", errno);
178
                     }
179

180
                     if(socket_error != 0) {
181
                        active = 0;
182
                     }
183
                  }
184
               }
185

186
               if(active == 0) {
187
                  Botan::OS::Socket_Platform::close_socket(m_socket);
188
                  m_socket = Botan::OS::Socket_Platform::invalid_socket();
189
                  continue;
190
               }
191
            }
192
         }
193

194
         if(m_socket == Botan::OS::Socket_Platform::invalid_socket()) {
195
            throw System_Error(fmt("Connection to {} for service {} failed with errno", hostname, service, errno),
196
                               errno);
197
         }
198
      }
199

200
      ~BSD_Socket() override {
201
         Botan::OS::Socket_Platform::close_socket(m_socket);
202
         m_socket = Botan::OS::Socket_Platform::invalid_socket();
203
         Botan::OS::Socket_Platform::socket_fini();
204
      }
205

206
      BSD_Socket(const BSD_Socket& other) = delete;
207
      BSD_Socket(BSD_Socket&& other) = delete;
208
      BSD_Socket& operator=(const BSD_Socket& other) = delete;
209
      BSD_Socket& operator=(BSD_Socket&& other) = delete;
210

211
      void write(const uint8_t buf[], size_t len) override {
212
         fd_set write_set;
213
         FD_ZERO(&write_set);
214
         FD_SET(m_socket, &write_set);
215

216
         size_t sent_so_far = 0;
217
         while(sent_so_far != len) {
218
            struct timeval timeout = make_timeout_tv();
219
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
220

221
            if(active == 0) {
222
               throw System_Error("Timeout during socket write");
223
            }
224

225
            const size_t left = len - sent_so_far;
226
            socket_op_ret_type sent =
227
               ::send(m_socket, cast_uint8_ptr_to_char(&buf[sent_so_far]), static_cast<sendrecv_len_type>(left), 0);
228
            if(sent < 0) {
229
               throw System_Error("Socket write failed", errno);
230
            } else {
231
               sent_so_far += static_cast<size_t>(sent);
232
            }
233
         }
234
      }
235

236
      size_t read(uint8_t buf[], size_t len) override {
237
         fd_set read_set;
238
         FD_ZERO(&read_set);
239
         FD_SET(m_socket, &read_set);
240

241
         struct timeval timeout = make_timeout_tv();
242
         int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
243

244
         if(active == 0) {
245
            throw System_Error("Timeout during socket read");
246
         }
247

248
         socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);
249
         if(got < 0) {
250
            throw System_Error("Socket read failed", errno);
251
         }
252

253
         return static_cast<size_t>(got);
254
      }
255

256
   private:
257
      // Import socket operation types from Socket_Platform namespace
258
      using socket_type = Botan::OS::Socket_Platform::socket_type;
259
      using socket_op_ret_type = Botan::OS::Socket_Platform::socket_op_ret_type;
260
      using socklen_type = Botan::OS::Socket_Platform::socklen_type;
261
      using sendrecv_len_type = Botan::OS::Socket_Platform::sendrecv_len_type;
262

263
      const std::chrono::microseconds m_timeout;
264
      socket_type m_socket;
265

266
      struct timeval make_timeout_tv() const {
267
         struct timeval tv;
268
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
269
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
270
         return tv;
271
      }
272
};
273

274
#endif
275

276
}  // namespace
277

278
std::unique_ptr<OS::Socket> OS::open_socket(std::string_view hostname,
1✔
279
                                            std::string_view service,
280
                                            std::chrono::milliseconds timeout) {
281
#if defined(BOTAN_HAS_BOOST_ASIO)
282
   return std::make_unique<Asio_Socket>(hostname, service, timeout);
1✔
283

284
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
285
   return std::make_unique<BSD_Socket>(hostname, service, timeout);
286

287
#else
288
   BOTAN_UNUSED(hostname, service, timeout);
289
   // No sockets for you
290
   return std::unique_ptr<Socket>();
291
#endif
292
}
293

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