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

randombit / botan / 13659960632

04 Mar 2025 06:01PM UTC coverage: 91.671% (-0.02%) from 91.692%
13659960632

Pull #4660

github

web-flow
Merge 9df2d96a1 into dbe3aab18
Pull Request #4660: Consolidation and Enhancement of BSD Socket Layer

95814 of 104519 relevant lines covered (91.67%)

11251709.59 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() == false) {
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) {
22✔
95
            m_io.run_one();
16✔
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
         m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout, this));
18✔
118
      }
18✔
119

120
      const std::chrono::microseconds m_timeout;
121
      boost::asio::io_context m_io;
122
      boost::asio::system_timer m_timer;
123
      boost::asio::ip::udp::socket m_udp;
124
};
125
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
126

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, rp->ai_addr, rp->ai_addrlen);
162
            m_salen = static_cast<socklen_t>(rp->ai_addrlen);
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
            if(active == 0) {
192
               throw System_Error("Timeout during socket write");
193
            }
194

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

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

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

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

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

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

237
      sockaddr_storage m_sa;
238
      socklen_t m_salen;
239

240
      struct timeval make_timeout_tv() const {
241
         struct timeval tv;
242
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
243
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
244
         return tv;
245
      }
246

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

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

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

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