• 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

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
* (C) 2025 Kagan Can Sit
6
*
7
* Botan is released under the Simplified BSD License (see license.txt)
8
*/
9

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

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

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

32
namespace Botan {
33

34
namespace {
35

36
#if defined(BOTAN_HAS_BOOST_ASIO)
37
class Asio_SocketUDP final : public OS::SocketUDP {
×
38
   public:
39
      Asio_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
6✔
40
            m_timeout(timeout), m_timer(m_io), m_udp(m_io) {
12✔
41
         m_timer.expires_after(m_timeout);
6✔
42
         check_timeout();
6✔
43

44
         boost::asio::ip::udp::resolver resolver(m_io);
6✔
45
         boost::asio::ip::udp::resolver::results_type dns_iter =
6✔
46
            resolver.resolve(std::string{hostname}, std::string{service});
18✔
47

48
         boost::system::error_code ec = boost::asio::error::would_block;
6✔
49

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

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

55
         while(ec == boost::asio::error::would_block) {
12✔
56
            m_io.run_one();
6✔
57
         }
58

59
         if(ec) {
6✔
60
            throw boost::system::system_error(ec);
×
61
         }
62
         if(!m_udp.is_open()) {
6✔
63
            throw System_Error(fmt("Connection to host {} failed", hostname));
×
64
         }
65
      }
6✔
66

67
      void write(const uint8_t buf[], size_t len) override {
6✔
68
         m_timer.expires_after(m_timeout);
6✔
69

70
         boost::system::error_code ec = boost::asio::error::would_block;
6✔
71

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

74
         while(ec == boost::asio::error::would_block) {
18✔
75
            m_io.run_one();
12✔
76
         }
77

78
         if(ec) {
6✔
79
            throw boost::system::system_error(ec);
×
80
         }
81
      }
6✔
82

83
      size_t read(uint8_t buf[], size_t len) override {
6✔
84
         m_timer.expires_after(m_timeout);
6✔
85

86
         boost::system::error_code ec = boost::asio::error::would_block;
6✔
87
         size_t got = 0;
6✔
88

89
         m_udp.async_receive(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
6✔
90
            ec = cb_ec;
6✔
91
            got = cb_got;
6✔
92
         });
93

94
         while(ec == boost::asio::error::would_block) {
20✔
95
            m_io.run_one();
14✔
96
         }
97

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

105
         return got;
6✔
106
      }
107

108
   private:
109
      void check_timeout() {
18✔
110
         if(m_udp.is_open() && m_timer.expiry() < std::chrono::system_clock::now()) {
18✔
111
            boost::system::error_code err;
×
112

113
            // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
114
            m_udp.close(err);
×
115
         }
116

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

121
      const std::chrono::microseconds m_timeout;
122
      boost::asio::io_context m_io;
123
      boost::asio::system_timer m_timer;
124
      boost::asio::ip::udp::socket m_udp;
125
};
126
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
127
class BSD_SocketUDP final : public OS::SocketUDP {
128
   public:
129
      BSD_SocketUDP(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
         clear_mem(&hints, 1);
136
         hints.ai_family = AF_UNSPEC;
137
         hints.ai_socktype = SOCK_DGRAM;
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()) [[unlikely]] {
156
               // unsupported socket type?
157
               continue;
158
            }
159

160
            Botan::OS::Socket_Platform::set_nonblocking(m_socket);
161
            memcpy(&m_sa, res->ai_addr, res->ai_addrlen);
162
            m_salen = static_cast<socklen_t>(res->ai_addrlen);  // NOLINT(*-redundant-casting)
163
         }
164

165
         if(m_socket == Botan::OS::Socket_Platform::invalid_socket()) {
166
            throw System_Error(fmt("Connecting to {} for service {} failed with errno {}", hostname, service, errno),
167
                               errno);
168
         }
169
      }
170

171
      ~BSD_SocketUDP() override {
172
         Botan::OS::Socket_Platform::close_socket(m_socket);
173
         m_socket = Botan::OS::Socket_Platform::invalid_socket();
174
         Botan::OS::Socket_Platform::socket_fini();
175
      }
176

177
      BSD_SocketUDP(const BSD_SocketUDP& other) = delete;
178
      BSD_SocketUDP(BSD_SocketUDP&& other) = delete;
179
      BSD_SocketUDP& operator=(const BSD_SocketUDP& other) = delete;
180
      BSD_SocketUDP& operator=(BSD_SocketUDP&& other) = delete;
181

182
      void write(const uint8_t buf[], size_t len) override {
183
         fd_set write_set;
184
         FD_ZERO(&write_set);
185
         FD_SET(m_socket, &write_set);
186

187
         size_t sent_so_far = 0;
188
         while(sent_so_far != len) {
189
            struct timeval timeout = make_timeout_tv();
190
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
191

192
            if(active == 0) {
193
               throw System_Error("Timeout during socket write");
194
            }
195

196
            const size_t left = len - sent_so_far;
197
            socket_op_ret_type sent = ::sendto(m_socket,
198
                                               cast_uint8_ptr_to_char(buf + sent_so_far),
199
                                               static_cast<sendrecv_len_type>(left),
200
                                               0,
201
                                               reinterpret_cast<sockaddr*>(&m_sa),
202
                                               m_salen);
203
            if(sent < 0) {
204
               throw System_Error("Socket write failed", errno);
205
            } else {
206
               sent_so_far += static_cast<size_t>(sent);
207
            }
208
         }
209
      }
210

211
      size_t read(uint8_t buf[], size_t len) override {
212
         fd_set read_set;
213
         FD_ZERO(&read_set);
214
         FD_SET(m_socket, &read_set);
215

216
         struct timeval timeout = make_timeout_tv();
217
         int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
218
         if(active == 0) {
219
            throw System_Error("Timeout during socket read");
220
         }
221

222
         socket_op_ret_type got =
223
            ::recv(m_socket, reinterpret_cast<char*>(buf), static_cast<sendrecv_len_type>(len), 0);
224
         if(got < 0) {
225
            throw System_Error("Socket read failed", errno);
226
         }
227

228
         return static_cast<size_t>(got);
229
      }
230

231
   private:
232
      // Import socket operation types from Socket_Platform namespace
233
      using socket_type = Botan::OS::Socket_Platform::socket_type;
234
      using socket_op_ret_type = Botan::OS::Socket_Platform::socket_op_ret_type;
235
      using socklen_type = Botan::OS::Socket_Platform::socklen_type;
236
      using sendrecv_len_type = Botan::OS::Socket_Platform::sendrecv_len_type;
237

238
      sockaddr_storage m_sa;
239
      socklen_t m_salen;
240

241
      struct timeval make_timeout_tv() const {
242
         struct timeval tv {};
243

244
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
245
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
246
         return tv;
247
      }
248

249
      const std::chrono::microseconds m_timeout;
250
      socket_type m_socket;
251
};
252
#endif
253
}  // namespace
254

255
std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view hostname,
6✔
256
                                                   std::string_view service,
257
                                                   std::chrono::microseconds timeout) {
258
#if defined(BOTAN_HAS_BOOST_ASIO)
259
   return std::make_unique<Asio_SocketUDP>(hostname, service, timeout);
6✔
260
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
261
   return std::make_unique<BSD_SocketUDP>(hostname, service, timeout);
262
#else
263
   BOTAN_UNUSED(hostname);
264
   BOTAN_UNUSED(service);
265
   BOTAN_UNUSED(timeout);
266
   return std::unique_ptr<OS::SocketUDP>();
267
#endif
268
}
269

270
std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view uri_string, std::chrono::microseconds timeout) {
6✔
271
   const auto uri = URI::from_any(uri_string);
6✔
272
   if(uri.port() == 0) {
6✔
273
      throw Invalid_Argument("UDP port not specified");
×
274
   }
275
   return open_socket_udp(uri.host(), std::to_string(uri.port()), timeout);
12✔
276
}
6✔
277

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