5#include <bitcoin-build-config.h>
24#include <linux/netlink.h>
25#include <linux/rtnetlink.h>
26#elif defined(__FreeBSD__)
27#include <netlink/netlink.h>
28#include <netlink/netlink_route.h>
31#elif defined(__APPLE__)
33#include <sys/sysctl.h>
44std::optional<CNetAddr> FromSockAddr(
const struct sockaddr* addr, std::optional<socklen_t> sa_len_opt)
47 if (sa_len_opt.has_value()) {
51 switch (addr->sa_family) {
52 case AF_INET: sa_len =
sizeof(
struct sockaddr_in);
break;
53 case AF_INET6: sa_len =
sizeof(
struct sockaddr_in6);
break;
67#if defined(__linux__) || defined(__FreeBSD__)
70static constexpr ssize_t NETLINK_MAX_RESPONSE_SIZE{1'048'576};
72std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
75 auto sock{
CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)};
90 const size_t dst_data_len = family == AF_INET ? 4 : 16;
92 request.hdr.nlmsg_type = RTM_GETROUTE;
93 request.hdr.nlmsg_flags = NLM_F_REQUEST;
98 request.hdr.nlmsg_flags |= NLM_F_DUMP;
100 request.hdr.nlmsg_len = NLMSG_LENGTH(
sizeof(rtmsg) +
sizeof(nlattr) + dst_data_len);
101 request.hdr.nlmsg_seq = 0;
102 request.data.rtm_family = family;
103 request.data.rtm_dst_len = 0;
108 request.data.rtm_flags = RTM_F_PREFIX;
110 request.dst_hdr.nla_type = RTA_DST;
111 request.dst_hdr.nla_len =
sizeof(nlattr) + dst_data_len;
113 if (sock->Send(&request, request.hdr.nlmsg_len, 0) !=
static_cast<ssize_t
>(request.hdr.nlmsg_len)) {
120 ssize_t total_bytes_read{0};
125 recv_result = sock->Recv(response,
sizeof(response), 0);
126 }
while (recv_result < 0 && (errno == EINTR || errno == EAGAIN));
127 if (recv_result < 0) {
132 total_bytes_read += recv_result;
133 if (total_bytes_read > NETLINK_MAX_RESPONSE_SIZE) {
134 LogWarning(
"Netlink response exceeded size limit (%zu bytes, family=%d)\n", NETLINK_MAX_RESPONSE_SIZE, family);
138 using recv_result_t = std::conditional_t<std::is_signed_v<
decltype(NLMSG_HDRLEN)>, int64_t,
decltype(NLMSG_HDRLEN)>;
140 for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr,
static_cast<recv_result_t
>(recv_result)); hdr = NLMSG_NEXT(hdr, recv_result)) {
141 if (!(hdr->nlmsg_flags & NLM_F_MULTI)) {
145 if (hdr->nlmsg_type == NLMSG_DONE) {
150 rtmsg* r = (rtmsg*)NLMSG_DATA(hdr);
151 int remaining_len = RTM_PAYLOAD(hdr);
153 if (hdr->nlmsg_type != RTM_NEWROUTE) {
158 if (r->rtm_dst_len != 0) {
163 rtattr* rta_gateway =
nullptr;
165 for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) {
166 if (attr->rta_type == RTA_GATEWAY) {
168 }
else if (attr->rta_type == RTA_OIF &&
sizeof(
int) == RTA_PAYLOAD(attr)) {
169 std::memcpy(&scope_id, RTA_DATA(attr),
sizeof(scope_id));
174 if (rta_gateway !=
nullptr) {
175 if (family == AF_INET &&
sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) {
177 std::memcpy(&gw, RTA_DATA(rta_gateway),
sizeof(gw));
179 }
else if (family == AF_INET6 &&
sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) {
181 std::memcpy(&gw, RTA_DATA(rta_gateway),
sizeof(gw));
193std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
195 NET_LUID interface_luid = {};
196 SOCKADDR_INET destination_address = {};
197 MIB_IPFORWARD_ROW2 best_route = {};
198 SOCKADDR_INET best_source_address = {};
199 DWORD best_if_idx = 0;
203 destination_address.si_family = family;
204 status = GetBestInterfaceEx((sockaddr*)&destination_address, &best_if_idx);
205 if (status != NO_ERROR) {
212 status = GetBestRoute2(&interface_luid, best_if_idx,
nullptr, &destination_address, 0, &best_route, &best_source_address);
213 if (status != NO_ERROR) {
214 LogError(
"Could not get best route for default route for interface index %d: %s\n",
219 Assume(best_route.NextHop.si_family == family);
220 if (family == AF_INET) {
221 return CNetAddr(best_route.NextHop.Ipv4.sin_addr);
222 }
else if(family == AF_INET6) {
223 return CNetAddr(best_route.NextHop.Ipv6.sin6_addr, best_route.InterfaceIndex);
228#elif defined(__APPLE__)
230#define ROUNDUP32(a) \
231 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t))
234std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
237 int mib[] = {CTL_NET, PF_ROUTE, 0, family, NET_RT_FLAGS, RTF_GATEWAY};
240 if (sysctl(mib,
sizeof(mib) /
sizeof(
int),
nullptr, &l,
nullptr, 0) < 0) {
244 std::vector<std::byte> buf(l);
245 if (sysctl(mib,
sizeof(mib) /
sizeof(
int), buf.data(), &l,
nullptr, 0) < 0) {
250 for (
size_t msg_pos = 0; msg_pos < buf.size(); ) {
251 if ((msg_pos +
sizeof(rt_msghdr)) > buf.size())
return std::nullopt;
252 const struct rt_msghdr* rt = (
const struct rt_msghdr*)(buf.data() + msg_pos);
253 const size_t next_msg_pos = msg_pos + rt->rtm_msglen;
254 if (rt->rtm_msglen <
sizeof(rt_msghdr) || next_msg_pos > buf.size())
return std::nullopt;
257 size_t sa_pos = msg_pos +
sizeof(
struct rt_msghdr);
258 std::optional<CNetAddr> dst, gateway;
259 for (
int i = 0; i < RTAX_MAX; i++) {
260 if (rt->rtm_addrs & (1 << i)) {
262 if ((sa_pos + 2) > next_msg_pos)
return std::nullopt;
263 const struct sockaddr* sa = (
const struct sockaddr*)(buf.data() + sa_pos);
264 if ((sa_pos + sa->sa_len) > next_msg_pos)
return std::nullopt;
266 dst = FromSockAddr(sa, sa->sa_len);
267 }
else if (i == RTAX_GATEWAY) {
268 gateway = FromSockAddr(sa, sa->sa_len);
272 sa_pos += ROUNDUP32(sa->sa_len);
276 if (dst && gateway && dst->IsBindAny()) {
280 msg_pos = next_msg_pos;
288std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t)
310 std::optional<CNetAddr>
ret = QueryDefaultGatewayImpl(family);
314 if (
ret && !
ret->IsBindAny()) {
323 std::vector<CNetAddr> addresses;
326 constexpr size_t MAX_ADAPTER_ADDR_SIZE = 4 * 1000 * 1000;
327 std::vector<std::byte> out_buf(15000, {});
329 ULONG out_buf_len = out_buf.size();
330 status = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME,
331 nullptr,
reinterpret_cast<PIP_ADAPTER_ADDRESSES
>(out_buf.data()), &out_buf_len);
332 if (status == ERROR_BUFFER_OVERFLOW && out_buf.size() < MAX_ADAPTER_ADDR_SIZE) {
337 out_buf.resize(std::min(std::max<size_t>(out_buf_len, out_buf.size()) * 2, MAX_ADAPTER_ADDR_SIZE));
343 if (status != NO_ERROR) {
351 for (PIP_ADAPTER_ADDRESSES cur_adapter =
reinterpret_cast<PIP_ADAPTER_ADDRESSES
>(out_buf.data());
352 cur_adapter !=
nullptr; cur_adapter = cur_adapter->Next) {
353 if (cur_adapter->OperStatus != IfOperStatusUp)
continue;
354 if (cur_adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
continue;
357 for (PIP_ADAPTER_UNICAST_ADDRESS cur_address = cur_adapter->FirstUnicastAddress;
358 cur_address !=
nullptr; cur_address = cur_address->Next) {
360 if ((cur_address->Flags & IP_ADAPTER_ADDRESS_TRANSIENT) != 0)
continue;
362 if (std::optional<CNetAddr> addr = FromSockAddr(cur_address->Address.lpSockaddr,
static_cast<socklen_t
>(cur_address->Address.iSockaddrLength))) {
363 addresses.push_back(*addr);
367#elif defined(HAVE_IFADDRS)
368 struct ifaddrs* myaddrs;
369 if (getifaddrs(&myaddrs) == 0) {
370 for (
struct ifaddrs* ifa = myaddrs; ifa !=
nullptr; ifa = ifa->ifa_next)
372 if (ifa->ifa_addr ==
nullptr)
continue;
373 if ((ifa->ifa_flags & IFF_UP) == 0)
continue;
374 if ((ifa->ifa_flags & IFF_LOOPBACK) != 0)
continue;
376 if (std::optional<CNetAddr> addr = FromSockAddr(ifa->ifa_addr, std::nullopt)) {
377 addresses.push_back(*addr);
380 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.