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

randombit / botan / 24053024312

06 Apr 2026 09:51PM UTC coverage: 91.831% (+2.4%) from 89.454%
24053024312

Pull #5521

github

web-flow
Merge 89fecf072 into 417709dd7
Pull Request #5521: Rollup of small fixes

108699 of 118368 relevant lines covered (91.83%)

11266117.12 hits per line

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

83.64
/src/lib/utils/socket/socket_udp.cpp
1
/*
2
* (C) 2015,2016,2017 Jack Lloyd
3
* (C) 2016 Daniel Neus
4
* (C) 2019 Nuno Goncalves <nunojpg@gmail.com>
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include <botan/internal/socket_udp.h>
10

11
#include <botan/exceptn.h>
12
#include <botan/mem_ops.h>
13
#include <botan/internal/fmt.h>
14
#include <botan/internal/stl_util.h>
15
#include <botan/internal/target_info.h>
16
#include <botan/internal/uri.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
22
   * causes macro conflicts with Darwin's termios.h when this
23
   * file is included in the amalgamation. GH #350
24
   */
25
   #define BOOST_ASIO_DISABLE_SERIAL_PORT
26
   #include <boost/asio.hpp>
27
   #include <boost/asio/system_timer.hpp>
28
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
29
   #include <errno.h>
30
   #include <fcntl.h>
31
   #include <netdb.h>
32
   #include <netinet/in.h>
33
   #include <string.h>
34
   #include <sys/socket.h>
35
   #include <sys/time.h>
36
   #include <unistd.h>
37

38
#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
39
   #include <ws2tcpip.h>
40
#endif
41

42
namespace Botan {
43

44
namespace {
45

46
#if defined(BOTAN_HAS_BOOST_ASIO)
47
class Asio_SocketUDP final : public OS::SocketUDP {
×
48
   public:
49
      Asio_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
6✔
50
            m_timeout(timeout), m_timer(m_io), m_udp(m_io) {
12✔
51
         m_timer.expires_after(m_timeout);
6✔
52
         check_timeout();
6✔
53

54
         boost::asio::ip::udp::resolver resolver(m_io);
6✔
55
         const boost::asio::ip::udp::resolver::results_type dns_iter =
6✔
56
            resolver.resolve(std::string{hostname}, std::string{service});
18✔
57

58
         boost::system::error_code ec = boost::asio::error::would_block;
6✔
59

60
         auto connect_cb = [&ec](const boost::system::error_code& e,
12✔
61
                                 const boost::asio::ip::udp::resolver::results_type::iterator&) { ec = e; };
6✔
62

63
         boost::asio::async_connect(m_udp, dns_iter.begin(), dns_iter.end(), connect_cb);
12✔
64

65
         while(ec == boost::asio::error::would_block) {
12✔
66
            m_io.run_one();
6✔
67
         }
68

69
         if(ec) {
6✔
70
            throw boost::system::system_error(ec);
×
71
         }
72
         if(!m_udp.is_open()) {
6✔
73
            throw System_Error(fmt("Connection to host {} failed", hostname));
×
74
         }
75
      }
6✔
76

77
      void write(const uint8_t buf[], size_t len) override {
6✔
78
         m_timer.expires_after(m_timeout);
6✔
79

80
         boost::system::error_code ec = boost::asio::error::would_block;
6✔
81

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

84
         while(ec == boost::asio::error::would_block) {
18✔
85
            m_io.run_one();
12✔
86
         }
87

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

93
      size_t read(uint8_t buf[], size_t len) override {
6✔
94
         m_timer.expires_after(m_timeout);
6✔
95

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

99
         m_udp.async_receive(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
6✔
100
            ec = cb_ec;
6✔
101
            got = cb_got;
6✔
102
         });
103

104
         while(ec == boost::asio::error::would_block) {
22✔
105
            m_io.run_one();
16✔
106
         }
107

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

115
         return got;
6✔
116
      }
117

118
   private:
119
      void check_timeout() {
18✔
120
         if(m_udp.is_open() && m_timer.expiry() < std::chrono::system_clock::now()) {
18✔
121
            boost::system::error_code err;
×
122

123
            // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
124
            m_udp.close(err);
×
125
         }
126

127
         // NOLINTNEXTLINE(*-avoid-bind) FIXME - unclear why we can't use a lambda here
128
         m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout, this));
18✔
129
      }
18✔
130

131
      const std::chrono::microseconds m_timeout;
132
      boost::asio::io_context m_io;
133
      boost::asio::system_timer m_timer;
134
      boost::asio::ip::udp::socket m_udp;
135
};
136
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
137
class BSD_SocketUDP final : public OS::SocketUDP {
138
   public:
139
      BSD_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
140
            m_timeout(timeout), m_socket(invalid_socket()) {
141
         socket_init();
142

143
         const std::string hostname_str(hostname);
144
         const std::string service_str(service);
145

146
         addrinfo hints{};
147
         hints.ai_family = AF_UNSPEC;
148
         hints.ai_socktype = SOCK_DGRAM;
149

150
         unique_addr_info_ptr res = nullptr;
151

152
         const int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, Botan::out_ptr(res));
153
         if(rc != 0) {
154
            throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
155
         }
156

157
         for(const addrinfo* rp = res.get(); (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
158
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
159
               continue;
160
            }
161

162
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
163

164
            if(m_socket == invalid_socket()) [[unlikely]] {
165
               // unsupported socket type?
166
               continue;
167
            }
168

169
            set_nonblocking(m_socket);
170
            memcpy(&sa, res->ai_addr, res->ai_addrlen);
171
            salen = static_cast<socklen_t>(res->ai_addrlen);  // NOLINT(*-redundant-casting)
172
         }
173

174
         if(m_socket == invalid_socket()) {
175
            throw System_Error(
176
               fmt("Connecting to {} for service {} failed with errno {}", hostname, service, last_socket_error()),
177
               last_socket_error());
178
         }
179
      }
180

181
      ~BSD_SocketUDP() override {
182
         close_socket(m_socket);
183
         m_socket = invalid_socket();
184
         socket_fini();
185
      }
186

187
      BSD_SocketUDP(const BSD_SocketUDP& other) = delete;
188
      BSD_SocketUDP(BSD_SocketUDP&& other) = delete;
189
      BSD_SocketUDP& operator=(const BSD_SocketUDP& other) = delete;
190
      BSD_SocketUDP& operator=(BSD_SocketUDP&& other) = delete;
191

192
      void write(const uint8_t buf[], size_t len) override {
193
         size_t sent_so_far = 0;
194
         while(sent_so_far != len) {
195
            fd_set write_set;
196
            FD_ZERO(&write_set);
197
            FD_SET(m_socket, &write_set);
198

199
            struct timeval timeout = make_timeout_tv();
200
            const int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
201

202
            if(active < 0) {
203
               if(select_error_is_retryable()) {
204
                  continue;
205
               }
206
               throw System_Error("Socket select failed", last_socket_error());
207
            }
208

209
            if(active == 0) {
210
               throw System_Error("Timeout during socket write");
211
            }
212

213
            const size_t left = len - sent_so_far;
214
            const socket_op_ret_type sent = ::sendto(m_socket,
215
                                                     cast_uint8_ptr_to_char(buf + sent_so_far),
216
                                                     static_cast<sendrecv_len_type>(left),
217
                                                     0,
218
                                                     reinterpret_cast<sockaddr*>(&sa),
219
                                                     salen);
220
            if(sent < 0) {
221
               throw System_Error("Socket write failed", last_socket_error());
222
            } else {
223
               sent_so_far += static_cast<size_t>(sent);
224
            }
225
         }
226
      }
227

228
      size_t read(uint8_t buf[], size_t len) override {
229
         for(;;) {
230
            fd_set read_set;
231
            FD_ZERO(&read_set);
232
            FD_SET(m_socket, &read_set);
233

234
            struct timeval timeout = make_timeout_tv();
235
            const int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
236

237
            if(active < 0) {
238
               if(select_error_is_retryable()) {
239
                  continue;
240
               }
241
               throw System_Error("Socket select failed", last_socket_error());
242
            }
243

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

248
            const socket_op_ret_type got = ::recvfrom(
249
               m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0, nullptr, nullptr);
250

251
            if(got < 0) {
252
               throw System_Error("Socket read failed", last_socket_error());
253
            }
254

255
            return static_cast<size_t>(got);
256
         }
257
      }
258

259
   private:
260
   #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
261
      typedef SOCKET socket_type;
262
      typedef int socket_op_ret_type;
263
      typedef int sendrecv_len_type;
264

265
      static socket_type invalid_socket() { return INVALID_SOCKET; }
266

267
      static void close_socket(socket_type s) { ::closesocket(s); }
268

269
      static int last_socket_error() { return ::WSAGetLastError(); }
270

271
      static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
272

273
      static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
274

275
      static bool select_error_is_retryable() { return (::WSAGetLastError() == WSAEINTR); }
276

277
      static void set_nonblocking(socket_type s) {
278
         u_long nonblocking = 1;
279
         ::ioctlsocket(s, FIONBIO, &nonblocking);
280
      }
281

282
      static void socket_init() {
283
         WSAData wsa_data;
284
         WORD wsa_version = MAKEWORD(2, 2);
285

286
         if(::WSAStartup(wsa_version, &wsa_data) != 0) {
287
            throw System_Error("WSAStartup() failed", WSAGetLastError());
288
         }
289

290
         if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
291
            ::WSACleanup();
292
            throw System_Error("Could not find a usable version of Winsock.dll");
293
         }
294
      }
295

296
      static void socket_fini() { ::WSACleanup(); }
297
   #else
298
      typedef int socket_type;
299
      typedef ssize_t socket_op_ret_type;
300
      typedef size_t sendrecv_len_type;
301

302
      static socket_type invalid_socket() { return -1; }
303

304
      static void close_socket(socket_type s) { ::close(s); }
305

306
      static int last_socket_error() { return errno; }
307

308
      static std::string get_last_socket_error() { return ::strerror(errno); }
309

310
      static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
311

312
      static bool select_error_is_retryable() { return (errno == EINTR); }
313

314
      static void set_nonblocking(socket_type s) {
315
         // NOLINTNEXTLINE(*-vararg)
316
         if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
317
            throw System_Error("Setting socket to non-blocking state failed", errno);
318
         }
319
      }
320

321
      static void socket_init() {}
322

323
      static void socket_fini() {}
324
   #endif
325
      sockaddr_storage sa = {};
326
      socklen_t salen;
327

328
      struct timeval make_timeout_tv() const {
329
         struct timeval tv {};
330

331
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
332
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
333
         return tv;
334
      }
335

336
      const std::chrono::microseconds m_timeout;
337
      socket_type m_socket;
338

339
      using unique_addr_info_ptr = std::unique_ptr<addrinfo, decltype([](addrinfo* p) {
340
                                                      if(p != nullptr) {
341
                                                         ::freeaddrinfo(p);
342
                                                      }
343
                                                   })>;
344
};
345
#endif
346
}  // namespace
347

348
std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view hostname,
6✔
349
                                                   std::string_view service,
350
                                                   std::chrono::microseconds timeout) {
351
#if defined(BOTAN_HAS_BOOST_ASIO)
352
   return std::make_unique<Asio_SocketUDP>(hostname, service, timeout);
6✔
353
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
354
   return std::make_unique<BSD_SocketUDP>(hostname, service, timeout);
355
#else
356
   BOTAN_UNUSED(hostname);
357
   BOTAN_UNUSED(service);
358
   BOTAN_UNUSED(timeout);
359
   return std::unique_ptr<OS::SocketUDP>();
360
#endif
361
}
362

363
std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view uri_string, std::chrono::microseconds timeout) {
6✔
364
   const auto uri = URI::from_any(uri_string);
6✔
365
   if(uri.port() == 0) {
6✔
366
      throw Invalid_Argument("UDP port not specified");
×
367
   }
368
   return open_socket_udp(uri.host(), std::to_string(uri.port()), timeout);
12✔
369
}
6✔
370

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