OpenCBDC Transaction Processor
Loading...
Searching...
No Matches
socket_selector.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 MIT Digital Currency Initiative,
2// Federal Reserve Bank of Boston
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include "socket_selector.hpp"
7
8#include <cassert>
9#include <unistd.h>
10
11namespace cbdc::network {
12 auto socket_selector::add(const socket& sock) -> bool {
13 return add(sock.m_sock_fd);
14 }
15
16 auto socket_selector::wait() -> bool {
17 m_ready_fds = m_fds;
18 const auto nfds
19 = select(m_fd_max + 1, &m_ready_fds, nullptr, nullptr, nullptr);
20 // This macro does not bounds-check fd within m_fds. Since it comes
21 // from the system library there's nothing we can do about it.
22 // m_unblock_fds is set in init() and checked for validity so this
23 // should still be safe.
24 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
25 auto unblock = FD_ISSET(m_unblock_fds[0], &m_ready_fds);
26 if(static_cast<int>(unblock) != 0) {
27 auto dummy = char();
28 [[maybe_unused]] auto res
29 = read(m_unblock_fds[0], &dummy, sizeof(dummy));
30 assert(res != -1);
31 return false;
32 }
33 return nfds > 0;
34 }
35
36 auto socket_selector::add(int fd) -> bool {
37 if(fd >= FD_SETSIZE) {
38 return false;
39 }
40 // This macro does not bounds-check fd within m_fds. Since it comes
41 // from the system library there's nothing we can do about it.
42 // We check the bounds directly above, so this should be safe.
43 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
44 FD_SET(fd, &m_fds);
45 m_fd_max = std::max(m_fd_max, fd);
46 return true;
47 }
48
49 auto socket_selector::init() -> bool {
50 auto pipe_res = pipe(m_unblock_fds.data());
51 if(pipe_res != 0) {
52 return false;
53 }
54 auto add_res = add(m_unblock_fds[0]);
55 return add_res;
56 }
57
59 if(m_unblock_fds[1] != -1) {
60 static constexpr auto dummy_byte = char();
61 [[maybe_unused]] auto res
62 = write(m_unblock_fds[1], &dummy_byte, sizeof(dummy_byte));
63 assert(res != -1);
64 }
65 }
66
68 unblock();
69 close(m_unblock_fds[0]);
70 close(m_unblock_fds[1]);
71 }
72}
auto add(const socket &sock) -> bool
Adds a socket to the selector so that it is checked for events after a call to wait.
auto wait() -> bool
Blocks until at least one socket in the selector is ready to perform a read operation.
void unblock()
Unblocks a blocked wait() call.
auto init() -> bool
Sets-up the socket selector.
Generic superclass for network sockets.
Definition socket.hpp:30