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

randombit / botan / 17011479145

16 Aug 2025 06:17PM UTC coverage: 90.648% (-0.004%) from 90.652%
17011479145

Pull #4660

github

web-flow
Merge 1b0477060 into a2a0b43c3
Pull Request #4660: Consolidation and Enhancement of BSD Socket Layer

100083 of 110409 relevant lines covered (90.65%)

12305774.18 hits per line

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

85.71
/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

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

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

30
namespace Botan {
31
namespace {
32

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

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

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

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

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

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

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

63
      void write(std::span<const uint8_t> buf) override {
1✔
64
         m_timer.expires_after(m_timeout);
1✔
65

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

68
         // Some versions of asio don't know about span...
69
         m_tcp.async_send(boost::asio::buffer(buf.data(), buf.size()),
2✔
70
                          [&ec](boost::system::error_code e, size_t) { ec = e; });
2✔
71

72
         while(ec == boost::asio::error::would_block) {
3✔
73
            m_io.run_one();
2✔
74
         }
75

76
         if(ec) {
1✔
77
            throw boost::system::system_error(ec);
×
78
         }
79
      }
1✔
80

81
      size_t read(uint8_t buf[], size_t len) override {
2✔
82
         m_timer.expires_after(m_timeout);
2✔
83

84
         boost::system::error_code ec = boost::asio::error::would_block;
2✔
85
         size_t got = 0;
2✔
86

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

92
         while(ec == boost::asio::error::would_block) {
6✔
93
            m_io.run_one();
4✔
94
         }
95

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

103
         return got;
1✔
104
      }
105

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

111
            // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
112
            m_tcp.close(err);
×
113
         }
114

115
         // NOLINTNEXTLINE(*-avoid-bind) FIXME - unclear why we can't use a lambda here
116
         m_timer.async_wait(std::bind(&Asio_Socket::check_timeout, this));
4✔
117
      }
4✔
118

119
      const std::chrono::milliseconds m_timeout;
120
      boost::asio::io_context m_io;
121
      boost::asio::system_timer m_timer;
122
      boost::asio::ip::tcp::socket m_tcp;
123
};
124

125
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
126

127
class BSD_Socket final : public OS::Socket {
128
   public:
129
      BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
130
            m_timeout(timeout) {
131
         Botan::OS::Socket_Platform::socket_init();
132
         m_socket = Botan::OS::Socket_Platform::invalid_socket();
133

134
         addrinfo hints{};
135
         Botan::clear_mem(&hints, 1);
136
         hints.ai_family = AF_UNSPEC;
137
         hints.ai_socktype = SOCK_STREAM;
138

139
         Botan::OS::Socket_Platform::unique_addrinfo_ptr res = nullptr;
140
         int rc =
141
            ::getaddrinfo(std::string(hostname).c_str(), std::string(service).c_str(), &hints, Botan::out_ptr(res));
142

143
         if(rc != 0) {
144
            throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
145
         }
146

147
         for(addrinfo* rp = res.get(); (m_socket == Botan::OS::Socket_Platform::invalid_socket()) && rp != nullptr;
148
             rp = rp->ai_next) {
149
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
150
               continue;
151
            }
152

153
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
154

155
            if(m_socket == Botan::OS::Socket_Platform::invalid_socket()) {
156
               // unsupported socket type?
157
               continue;
158
            }
159

160
            Botan::OS::Socket_Platform::set_nonblocking(m_socket);
161

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

164
            if(err == -1) {
165
               int active = 0;
166
               if(Botan::OS::Socket_Platform::nonblocking_connect_in_progress()) {
167
                  struct timeval timeout_tv = make_timeout_tv();
168
                  fd_set write_set;
169
                  FD_ZERO(&write_set);
170
                  FD_SET(m_socket, &write_set);
171

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

174
                  if(active > 0) {
175
                     int socket_error = 0;
176
                     socklen_t len = sizeof(socket_error);
177

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

183
                     if(socket_error != 0) {
184
                        active = 0;
185
                     }
186
                  }
187
               }
188

189
               if(active == 0) {
190
                  Botan::OS::Socket_Platform::close_socket(m_socket);
191
                  m_socket = Botan::OS::Socket_Platform::invalid_socket();
192
                  continue;
193
               }
194
            }
195
         }
196

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

203
      ~BSD_Socket() override {
204
         Botan::OS::Socket_Platform::close_socket(m_socket);
205
         m_socket = Botan::OS::Socket_Platform::invalid_socket();
206
         Botan::OS::Socket_Platform::socket_fini();
207
      }
208

209
      BSD_Socket(const BSD_Socket& other) = delete;
210
      BSD_Socket(BSD_Socket&& other) = delete;
211
      BSD_Socket& operator=(const BSD_Socket& other) = delete;
212
      BSD_Socket& operator=(BSD_Socket&& other) = delete;
213

214
      void write(std::span<const uint8_t> buf) override {
215
         fd_set write_set;
216
         FD_ZERO(&write_set);
217
         FD_SET(m_socket, &write_set);
218

219
         size_t len = buf.size();
220

221
         size_t sent_so_far = 0;
222
         while(sent_so_far != len) {
223
            struct timeval timeout = make_timeout_tv();
224
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
225

226
            if(active == 0) {
227
               throw System_Error("Timeout during socket write");
228
            }
229

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

241
      size_t read(uint8_t buf[], size_t len) override {
242
         fd_set read_set;
243
         FD_ZERO(&read_set);
244
         FD_SET(m_socket, &read_set);
245

246
         struct timeval timeout = make_timeout_tv();
247
         int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
248

249
         if(active == 0) {
250
            throw System_Error("Timeout during socket read");
251
         }
252

253
         socket_op_ret_type got = ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);
254
         if(got < 0) {
255
            throw System_Error("Socket read failed", errno);
256
         }
257

258
         return static_cast<size_t>(got);
259
      }
260

261
   private:
262
      // Import socket operation types from Socket_Platform namespace
263
      using socket_type = Botan::OS::Socket_Platform::socket_type;
264
      using socket_op_ret_type = Botan::OS::Socket_Platform::socket_op_ret_type;
265
      using socklen_type = Botan::OS::Socket_Platform::socklen_type;
266
      using sendrecv_len_type = Botan::OS::Socket_Platform::sendrecv_len_type;
267

268
      const std::chrono::microseconds m_timeout;
269
      socket_type m_socket;
270

271
      struct timeval make_timeout_tv() const {
272
         struct timeval tv {};
273

274
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
275
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
276
         return tv;
277
      }
278
};
279

280
#endif
281

282
}  // namespace
283

284
std::unique_ptr<OS::Socket> OS::open_socket(std::string_view hostname,
1✔
285
                                            std::string_view service,
286
                                            std::chrono::milliseconds timeout) {
287
#if defined(BOTAN_HAS_BOOST_ASIO)
288
   return std::make_unique<Asio_Socket>(hostname, service, timeout);
1✔
289

290
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
291
   return std::make_unique<BSD_Socket>(hostname, service, timeout);
292

293
#else
294
   BOTAN_UNUSED(hostname, service, timeout);
295
   // No sockets for you
296
   return std::unique_ptr<Socket>();
297
#endif
298
}
299

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