5#include <bitcoin-build-config.h>
15#include <linux/rtnetlink.h>
16#elif defined(__FreeBSD__)
17#include <netlink/netlink.h>
18#include <netlink/netlink_route.h>
21#elif defined(__APPLE__)
23#include <sys/sysctl.h>
36std::optional<CNetAddr> FromSockAddr(
const struct sockaddr* addr, std::optional<socklen_t> sa_len_opt)
39 if (sa_len_opt.has_value()) {
43 switch (addr->sa_family) {
44 case AF_INET: sa_len =
sizeof(
struct sockaddr_in);
break;
45 case AF_INET6: sa_len =
sizeof(
struct sockaddr_in6);
break;
59#if defined(__linux__) || defined(__FreeBSD__)
62static constexpr ssize_t NETLINK_MAX_RESPONSE_SIZE{1'048'576};
64std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
67 auto sock{
CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)};
82 const size_t dst_data_len = family == AF_INET ? 4 : 16;
84 request.hdr.nlmsg_type = RTM_GETROUTE;
85 request.hdr.nlmsg_flags = NLM_F_REQUEST;
90 request.hdr.nlmsg_flags |= NLM_F_DUMP;
92 request.hdr.nlmsg_len = NLMSG_LENGTH(
sizeof(rtmsg) +
sizeof(nlattr) + dst_data_len);
93 request.hdr.nlmsg_seq = 0;
94 request.data.rtm_family = family;
95 request.data.rtm_dst_len = 0;
100 request.data.rtm_flags = RTM_F_PREFIX;
102 request.dst_hdr.nla_type = RTA_DST;
103 request.dst_hdr.nla_len =
sizeof(nlattr) + dst_data_len;
105 if (sock->Send(&request, request.hdr.nlmsg_len, 0) !=
static_cast<ssize_t
>(request.hdr.nlmsg_len)) {
112 ssize_t total_bytes_read{0};
117 recv_result = sock->Recv(response,
sizeof(response), 0);
118 }
while (recv_result < 0 && (errno == EINTR || errno == EAGAIN));
119 if (recv_result < 0) {
124 total_bytes_read += recv_result;
125 if (total_bytes_read > NETLINK_MAX_RESPONSE_SIZE) {
126 LogWarning(
"Netlink response exceeded size limit (%zu bytes, family=%d)\n", NETLINK_MAX_RESPONSE_SIZE, family);
130 using recv_result_t = std::conditional_t<std::is_signed_v<
decltype(NLMSG_HDRLEN)>, int64_t,
decltype(NLMSG_HDRLEN)>;
132 for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr,
static_cast<recv_result_t
>(recv_result)); hdr = NLMSG_NEXT(hdr, recv_result)) {
133 if (!(hdr->nlmsg_flags & NLM_F_MULTI)) {
137 if (hdr->nlmsg_type == NLMSG_DONE) {
142 rtmsg* r = (rtmsg*)NLMSG_DATA(hdr);
143 int remaining_len = RTM_PAYLOAD(hdr);
145 if (hdr->nlmsg_type != RTM_NEWROUTE) {
150 if (r->rtm_dst_len != 0) {
155 rtattr* rta_gateway =
nullptr;
157 for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) {
158 if (attr->rta_type == RTA_GATEWAY) {
160 }
else if (attr->rta_type == RTA_OIF &&
sizeof(
int) == RTA_PAYLOAD(attr)) {
161 std::memcpy(&scope_id, RTA_DATA(attr),
sizeof(scope_id));
166 if (rta_gateway !=
nullptr) {
167 if (family == AF_INET &&
sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) {
169 std::memcpy(&gw, RTA_DATA(rta_gateway),
sizeof(gw));
171 }
else if (family == AF_INET6 &&
sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) {
173 std::memcpy(&gw, RTA_DATA(rta_gateway),
sizeof(gw));
185std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
187 NET_LUID interface_luid = {};
188 SOCKADDR_INET destination_address = {};
189 MIB_IPFORWARD_ROW2 best_route = {};
190 SOCKADDR_INET best_source_address = {};
191 DWORD best_if_idx = 0;
195 destination_address.si_family = family;
196 status = GetBestInterfaceEx((sockaddr*)&destination_address, &best_if_idx);
197 if (status != NO_ERROR) {
204 status = GetBestRoute2(&interface_luid, best_if_idx,
nullptr, &destination_address, 0, &best_route, &best_source_address);
205 if (status != NO_ERROR) {
206 LogError(
"Could not get best route for default route for interface index %d: %s\n",
211 Assume(best_route.NextHop.si_family == family);
212 if (family == AF_INET) {
213 return CNetAddr(best_route.NextHop.Ipv4.sin_addr);
214 }
else if(family == AF_INET6) {
215 return CNetAddr(best_route.NextHop.Ipv6.sin6_addr, best_route.InterfaceIndex);
220#elif defined(__APPLE__)
222#define ROUNDUP32(a) \
223 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t))
226std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
229 int mib[] = {CTL_NET, PF_ROUTE, 0, family, NET_RT_FLAGS, RTF_GATEWAY};
232 if (sysctl(mib,
sizeof(mib) /
sizeof(
int),
nullptr, &l,
nullptr, 0) < 0) {
236 std::vector<std::byte> buf(l);
237 if (sysctl(mib,
sizeof(mib) /
sizeof(
int), buf.data(), &l,
nullptr, 0) < 0) {
242 for (
size_t msg_pos = 0; msg_pos < buf.size(); ) {
243 if ((msg_pos +
sizeof(rt_msghdr)) > buf.size())
return std::nullopt;
244 const struct rt_msghdr* rt = (
const struct rt_msghdr*)(buf.data() + msg_pos);
245 const size_t next_msg_pos = msg_pos + rt->rtm_msglen;
246 if (rt->rtm_msglen <
sizeof(rt_msghdr) || next_msg_pos > buf.size())
return std::nullopt;
249 size_t sa_pos = msg_pos +
sizeof(
struct rt_msghdr);
250 std::optional<CNetAddr> dst, gateway;
251 for (
int i = 0; i < RTAX_MAX; i++) {
252 if (rt->rtm_addrs & (1 << i)) {
254 if ((sa_pos + 2) > next_msg_pos)
return std::nullopt;
255 const struct sockaddr* sa = (
const struct sockaddr*)(buf.data() + sa_pos);
256 if ((sa_pos + sa->sa_len) > next_msg_pos)
return std::nullopt;
258 dst = FromSockAddr(sa, sa->sa_len);
259 }
else if (i == RTAX_GATEWAY) {
260 gateway = FromSockAddr(sa, sa->sa_len);
264 sa_pos += ROUNDUP32(sa->sa_len);
268 if (dst && gateway && dst->IsBindAny()) {
272 msg_pos = next_msg_pos;
280std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t)
302 std::optional<CNetAddr>
ret = QueryDefaultGatewayImpl(family);
306 if (
ret && !
ret->IsBindAny()) {
315 std::vector<CNetAddr> addresses;
318 constexpr size_t MAX_ADAPTER_ADDR_SIZE = 4 * 1000 * 1000;
319 std::vector<std::byte> out_buf(15000, {});
321 ULONG out_buf_len = out_buf.size();
322 status = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME,
323 nullptr,
reinterpret_cast<PIP_ADAPTER_ADDRESSES
>(out_buf.data()), &out_buf_len);
324 if (status == ERROR_BUFFER_OVERFLOW && out_buf.size() < MAX_ADAPTER_ADDR_SIZE) {
329 out_buf.resize(std::min(std::max<size_t>(out_buf_len, out_buf.size()) * 2, MAX_ADAPTER_ADDR_SIZE));
335 if (status != NO_ERROR) {
343 for (PIP_ADAPTER_ADDRESSES cur_adapter =
reinterpret_cast<PIP_ADAPTER_ADDRESSES
>(out_buf.data());
344 cur_adapter !=
nullptr; cur_adapter = cur_adapter->Next) {
345 if (cur_adapter->OperStatus != IfOperStatusUp)
continue;
346 if (cur_adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
continue;
349 for (PIP_ADAPTER_UNICAST_ADDRESS cur_address = cur_adapter->FirstUnicastAddress;
350 cur_address !=
nullptr; cur_address = cur_address->Next) {
352 if ((cur_address->Flags & IP_ADAPTER_ADDRESS_TRANSIENT) != 0)
continue;
354 if (std::optional<CNetAddr> addr = FromSockAddr(cur_address->Address.lpSockaddr,
static_cast<socklen_t
>(cur_address->Address.iSockaddrLength))) {
355 addresses.push_back(*addr);
359#elif defined(HAVE_IFADDRS)
360 struct ifaddrs* myaddrs;
361 if (getifaddrs(&myaddrs) == 0) {
362 for (
struct ifaddrs* ifa = myaddrs; ifa !=
nullptr; ifa = ifa->ifa_next)
364 if (ifa->ifa_addr ==
nullptr)
continue;
365 if ((ifa->ifa_flags & IFF_UP) == 0)
continue;
366 if ((ifa->ifa_flags & IFF_LOOPBACK) != 0)
continue;
368 if (std::optional<CNetAddr> addr = FromSockAddr(ifa->ifa_addr, std::nullopt)) {
369 addresses.push_back(*addr);
372 freeifaddrs(myaddrs);
#define Assume(val)
Assume is the identity function.
A combination of a network address (CNetAddr) and a (TCP) port.
bool SetSockAddr(const struct sockaddr *paddr, socklen_t addrlen)
Set CService from a network sockaddr.
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
std::optional< CNetAddr > QueryDefaultGateway(Network network)
Query the OS for the default gateway for network.
std::string NetworkErrorString(int err)
Return readable error string for a network error code.