• 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

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

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

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

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

31
namespace Botan {
32

33
namespace {
34

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

93
         while(ec == boost::asio::error::would_block) {
22✔
94
            m_io.run_one();
16✔
95
         }
96

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

104
         return got;
6✔
105
      }
106

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

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

116
         m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout, this));
18✔
117
      }
18✔
118

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

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

133
         addrinfo hints;
134
         clear_mem(&hints, 1);
135
         hints.ai_family = AF_UNSPEC;
136
         hints.ai_socktype = SOCK_DGRAM;
137

138
         addrinfo* res = nullptr;
139
         int rc = ::getaddrinfo(std::string(hostname).c_str(), std::string(service).c_str(), &hints, &res);
140

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

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

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

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

159
            Botan::OS::Socket_Platform::set_nonblocking(m_socket);
160
            memcpy(&m_sa, rp->ai_addr, rp->ai_addrlen);
161
            m_salen = static_cast<socklen_t>(rp->ai_addrlen);
162
         }
163

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

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

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

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

186
         size_t sent_so_far = 0;
187
         while(sent_so_far != len) {
188
            struct timeval timeout = make_timeout_tv();
189
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
190
            if(active == 0) {
191
               throw System_Error("Timeout during socket write");
192
            }
193

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

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

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

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

225
         return static_cast<size_t>(got);
226
      }
227

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

235
      sockaddr_storage m_sa;
236
      socklen_t m_salen;
237

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

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

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

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

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