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

randombit / botan / 5079590438

25 May 2023 12:28PM UTC coverage: 92.228% (+0.5%) from 91.723%
5079590438

Pull #3502

github

Pull Request #3502: Apply clang-format to the codebase

75589 of 81959 relevant lines covered (92.23%)

12139530.51 hits per line

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

81.03
/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/uri.h>
15
#include <chrono>
16

17
#if defined(BOTAN_HAS_BOOST_ASIO)
18
   /*
19
   * We don't need serial port support anyway, and asking for it
20
   * causes macro conflicts with Darwin's termios.h when this
21
   * file is included in the amalgamation. GH #350
22
   */
23
   #define BOOST_ASIO_DISABLE_SERIAL_PORT
24
   #include <boost/asio.hpp>
25
   #include <boost/asio/system_timer.hpp>
26
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
27
   #include <errno.h>
28
   #include <fcntl.h>
29
   #include <netdb.h>
30
   #include <netinet/in.h>
31
   #include <string.h>
32
   #include <sys/socket.h>
33
   #include <sys/time.h>
34
   #include <unistd.h>
35

36
#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
37
   #include <ws2tcpip.h>
38
#endif
39

40
namespace Botan {
41

42
namespace {
43

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

52
         boost::asio::ip::udp::resolver resolver(m_io);
6✔
53
         boost::asio::ip::udp::resolver::query query(std::string{hostname}, std::string{service});
24✔
54
         boost::asio::ip::udp::resolver::iterator dns_iter = resolver.resolve(query);
6✔
55

56
         boost::system::error_code ec = boost::asio::error::would_block;
6✔
57

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

62
         boost::asio::async_connect(m_udp, dns_iter, connect_cb);
6✔
63

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

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

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

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

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

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

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

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

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

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

103
         while(ec == boost::asio::error::would_block) {
23✔
104
            m_io.run_one();
17✔
105
         }
106

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

114
         return got;
6✔
115
      }
×
116

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

124
         m_timer.async_wait(std::bind(&Asio_SocketUDP::check_timeout, this));
18✔
125
      }
18✔
126

127
      const std::chrono::microseconds m_timeout;
128
      boost::asio::io_service m_io;
129
      boost::asio::system_timer m_timer;
130
      boost::asio::ip::udp::socket m_udp;
131
};
132
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
133
class BSD_SocketUDP final : public OS::SocketUDP {
134
   public:
135
      BSD_SocketUDP(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
136
            m_timeout(timeout) {
137
         socket_init();
138

139
         m_socket = invalid_socket();
140

141
         addrinfo* res;
142
         addrinfo hints;
143
         clear_mem(&hints, 1);
144
         hints.ai_family = AF_UNSPEC;
145
         hints.ai_socktype = SOCK_DGRAM;
146

147
         const std::string hostname_str(hostname);
148
         const std::string service_str(service);
149

150
         int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, &res);
151

152
         if(rc != 0) {
153
            throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
154
         }
155

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

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

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

168
            set_nonblocking(m_socket);
169
            memcpy(&sa, res->ai_addr, res->ai_addrlen);
170
            salen = static_cast<socklen_t>(res->ai_addrlen);
171
         }
172

173
         ::freeaddrinfo(res);
174

175
         if(m_socket == invalid_socket()) {
176
            throw System_Error(fmt("Connecting to {} for service {} failed with errno {}", hostname, service, errno),
177
                               errno);
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
         fd_set write_set;
194
         FD_ZERO(&write_set);
195
         FD_SET(m_socket, &write_set);
196

197
         size_t sent_so_far = 0;
198
         while(sent_so_far != len) {
199
            struct timeval timeout = make_timeout_tv();
200
            int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);
201

202
            if(active == 0) {
203
               throw System_Error("Timeout during socket write");
204
            }
205

206
            const size_t left = len - sent_so_far;
207
            socket_op_ret_type sent = ::sendto(m_socket,
208
                                               cast_uint8_ptr_to_char(buf + sent_so_far),
209
                                               static_cast<sendrecv_len_type>(left),
210
                                               0,
211
                                               reinterpret_cast<sockaddr*>(&sa),
212
                                               salen);
213
            if(sent < 0) {
214
               throw System_Error("Socket write failed", errno);
215
            } else {
216
               sent_so_far += static_cast<size_t>(sent);
217
            }
218
         }
219
      }
220

221
      size_t read(uint8_t buf[], size_t len) override {
222
         fd_set read_set;
223
         FD_ZERO(&read_set);
224
         FD_SET(m_socket, &read_set);
225

226
         struct timeval timeout = make_timeout_tv();
227
         int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);
228

229
         if(active == 0) {
230
            throw System_Error("Timeout during socket read");
231
         }
232

233
         socket_op_ret_type got =
234
            ::recvfrom(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0, nullptr, nullptr);
235

236
         if(got < 0) {
237
            throw System_Error("Socket read failed", errno);
238
         }
239

240
         return static_cast<size_t>(got);
241
      }
242

243
   private:
244
   #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
245
      typedef SOCKET socket_type;
246
      typedef int socket_op_ret_type;
247
      typedef int sendrecv_len_type;
248

249
      static socket_type invalid_socket() { return INVALID_SOCKET; }
250

251
      static void close_socket(socket_type s) { ::closesocket(s); }
252

253
      static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }
254

255
      static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }
256

257
      static void set_nonblocking(socket_type s) {
258
         u_long nonblocking = 1;
259
         ::ioctlsocket(s, FIONBIO, &nonblocking);
260
      }
261

262
      static void socket_init() {
263
         WSAData wsa_data;
264
         WORD wsa_version = MAKEWORD(2, 2);
265

266
         if(::WSAStartup(wsa_version, &wsa_data) != 0) {
267
            throw System_Error("WSAStartup() failed", WSAGetLastError());
268
         }
269

270
         if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
271
            ::WSACleanup();
272
            throw System_Error("Could not find a usable version of Winsock.dll");
273
         }
274
      }
275

276
      static void socket_fini() { ::WSACleanup(); }
277
   #else
278
      typedef int socket_type;
279
      typedef ssize_t socket_op_ret_type;
280
      typedef size_t sendrecv_len_type;
281

282
      static socket_type invalid_socket() { return -1; }
283

284
      static void close_socket(socket_type s) { ::close(s); }
285

286
      static std::string get_last_socket_error() { return ::strerror(errno); }
287

288
      static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }
289

290
      static void set_nonblocking(socket_type s) {
291
         if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
292
            throw System_Error("Setting socket to non-blocking state failed", errno);
293
         }
294
      }
295

296
      static void socket_init() {}
297

298
      static void socket_fini() {}
299
   #endif
300
      sockaddr_storage sa;
301
      socklen_t salen;
302

303
      struct timeval make_timeout_tv() const {
304
         struct timeval tv;
305
         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(m_timeout.count() / 1000000);
306
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(m_timeout.count() % 1000000);
307
         return tv;
308
      }
309

310
      const std::chrono::microseconds m_timeout;
311
      socket_type m_socket;
312
};
313
#endif
314
}
315

316
std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view hostname,
6✔
317
                                                   std::string_view service,
318
                                                   std::chrono::microseconds timeout) {
319
#if defined(BOTAN_HAS_BOOST_ASIO)
320
   return std::make_unique<Asio_SocketUDP>(hostname, service, timeout);
6✔
321
#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
322
   return std::make_unique<BSD_SocketUDP>(hostname, service, timeout);
323
#else
324
   BOTAN_UNUSED(hostname);
325
   BOTAN_UNUSED(service);
326
   BOTAN_UNUSED(timeout);
327
   return std::unique_ptr<OS::SocketUDP>();
328
#endif
329
}
330

331
std::unique_ptr<OS::SocketUDP> OS::open_socket_udp(std::string_view uri_string, std::chrono::microseconds timeout) {
6✔
332
   const auto uri = URI::fromAny(uri_string);
6✔
333
   if(uri.port == 0) {
6✔
334
      throw Invalid_Argument("UDP port not specified");
×
335
   }
336
   return open_socket_udp(uri.host, std::to_string(uri.port), timeout);
12✔
337
}
6✔
338

339
}
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

© 2025 Coveralls, Inc