5#include <bitcoin-build-config.h>
16#include <linux/rtnetlink.h>
17#elif defined(__FreeBSD__)
19#if __FreeBSD_version >= 1400000
21#define typeof __typeof
22#include <netlink/netlink.h>
23#include <netlink/netlink_route.h>
27#elif defined(__APPLE__)
29#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;
61#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 1400000)
63std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
66 auto sock{
CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)};
81 const size_t dst_data_len = family == AF_INET ? 4 : 16;
83 request.hdr.nlmsg_type = RTM_GETROUTE;
84 request.hdr.nlmsg_flags = NLM_F_REQUEST;
89 request.hdr.nlmsg_flags |= NLM_F_DUMP;
91 request.hdr.nlmsg_len = NLMSG_LENGTH(
sizeof(rtmsg) +
sizeof(nlattr) + dst_data_len);
92 request.hdr.nlmsg_seq = 0;
93 request.data.rtm_family = family;
94 request.data.rtm_dst_len = 0;
99 request.data.rtm_flags = RTM_F_PREFIX;
101 request.dst_hdr.nla_type = RTA_DST;
102 request.dst_hdr.nla_len =
sizeof(nlattr) + dst_data_len;
104 if (sock->Send(&request, request.hdr.nlmsg_len, 0) !=
static_cast<ssize_t
>(request.hdr.nlmsg_len)) {
113 recv_result = sock->Recv(response,
sizeof(response), 0);
114 }
while (recv_result < 0 && (errno == EINTR || errno == EAGAIN));
115 if (recv_result < 0) {
120 for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr, recv_result); hdr = NLMSG_NEXT(hdr, recv_result)) {
121 rtmsg* r = (rtmsg*)NLMSG_DATA(hdr);
122 int remaining_len = RTM_PAYLOAD(hdr);
125 rtattr *rta_gateway =
nullptr;
127 for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) {
128 if (attr->rta_type == RTA_GATEWAY) {
130 }
else if (attr->rta_type == RTA_OIF &&
sizeof(
int) == RTA_PAYLOAD(attr)) {
131 std::memcpy(&scope_id, RTA_DATA(attr),
sizeof(scope_id));
136 if (rta_gateway !=
nullptr) {
137 if (family == AF_INET &&
sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) {
139 std::memcpy(&gw, RTA_DATA(rta_gateway),
sizeof(gw));
141 }
else if (family == AF_INET6 &&
sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) {
143 std::memcpy(&gw, RTA_DATA(rta_gateway),
sizeof(gw));
154std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
156 NET_LUID interface_luid = {};
157 SOCKADDR_INET destination_address = {};
158 MIB_IPFORWARD_ROW2 best_route = {};
159 SOCKADDR_INET best_source_address = {};
160 DWORD best_if_idx = 0;
164 destination_address.si_family = family;
165 status = GetBestInterfaceEx((sockaddr*)&destination_address, &best_if_idx);
166 if (status != NO_ERROR) {
173 status = GetBestRoute2(&interface_luid, best_if_idx,
nullptr, &destination_address, 0, &best_route, &best_source_address);
174 if (status != NO_ERROR) {
180 Assume(best_route.NextHop.si_family == family);
181 if (family == AF_INET) {
182 return CNetAddr(best_route.NextHop.Ipv4.sin_addr);
183 }
else if(family == AF_INET6) {
184 return CNetAddr(best_route.NextHop.Ipv6.sin6_addr, best_route.InterfaceIndex);
189#elif defined(__APPLE__)
191#define ROUNDUP32(a) \
192 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t))
195std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
198 int mib[] = {CTL_NET, PF_ROUTE, 0, family, NET_RT_FLAGS, RTF_GATEWAY};
201 if (sysctl(mib,
sizeof(mib) /
sizeof(
int),
nullptr, &l,
nullptr, 0) < 0) {
205 std::vector<std::byte> buf(l);
206 if (sysctl(mib,
sizeof(mib) /
sizeof(
int), buf.data(), &l,
nullptr, 0) < 0) {
211 for (
size_t msg_pos = 0; msg_pos < buf.size(); ) {
212 if ((msg_pos +
sizeof(rt_msghdr)) > buf.size())
return std::nullopt;
213 const struct rt_msghdr* rt = (
const struct rt_msghdr*)(buf.data() + msg_pos);
214 const size_t next_msg_pos = msg_pos + rt->rtm_msglen;
215 if (rt->rtm_msglen <
sizeof(rt_msghdr) || next_msg_pos > buf.size())
return std::nullopt;
218 size_t sa_pos = msg_pos +
sizeof(
struct rt_msghdr);
219 std::optional<CNetAddr> dst, gateway;
220 for (
int i = 0; i < RTAX_MAX; i++) {
221 if (rt->rtm_addrs & (1 << i)) {
223 if ((sa_pos + 2) > next_msg_pos)
return std::nullopt;
224 const struct sockaddr* sa = (
const struct sockaddr*)(buf.data() + sa_pos);
225 if ((sa_pos + sa->sa_len) > next_msg_pos)
return std::nullopt;
227 dst = FromSockAddr(sa, sa->sa_len);
228 }
else if (i == RTAX_GATEWAY) {
229 gateway = FromSockAddr(sa, sa->sa_len);
233 sa_pos += ROUNDUP32(sa->sa_len);
237 if (dst && gateway && dst->IsBindAny()) {
241 msg_pos = next_msg_pos;
249std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t)
271 std::optional<CNetAddr>
ret = QueryDefaultGatewayImpl(family);
275 if (
ret && !
ret->IsBindAny()) {
284 std::vector<CNetAddr> addresses;
287 constexpr size_t MAX_ADAPTER_ADDR_SIZE = 4 * 1000 * 1000;
288 std::vector<std::byte> out_buf(15000, {});
290 ULONG out_buf_len = out_buf.size();
291 status = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME,
292 nullptr,
reinterpret_cast<PIP_ADAPTER_ADDRESSES
>(out_buf.data()), &out_buf_len);
293 if (status == ERROR_BUFFER_OVERFLOW && out_buf.size() < MAX_ADAPTER_ADDR_SIZE) {
298 out_buf.resize(std::min(std::max<size_t>(out_buf_len, out_buf.size()) * 2, MAX_ADAPTER_ADDR_SIZE));
304 if (status != NO_ERROR) {
312 for (PIP_ADAPTER_ADDRESSES cur_adapter =
reinterpret_cast<PIP_ADAPTER_ADDRESSES
>(out_buf.data());
313 cur_adapter !=
nullptr; cur_adapter = cur_adapter->Next) {
314 if (cur_adapter->OperStatus != IfOperStatusUp)
continue;
315 if (cur_adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
continue;
318 for (PIP_ADAPTER_UNICAST_ADDRESS cur_address = cur_adapter->FirstUnicastAddress;
319 cur_address !=
nullptr; cur_address = cur_address->Next) {
321 if ((cur_address->Flags & IP_ADAPTER_ADDRESS_TRANSIENT) != 0)
continue;
323 if (std::optional<CNetAddr> addr = FromSockAddr(cur_address->Address.lpSockaddr,
static_cast<socklen_t
>(cur_address->Address.iSockaddrLength))) {
324 addresses.push_back(*addr);
328#elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)
329 struct ifaddrs* myaddrs;
330 if (getifaddrs(&myaddrs) == 0) {
331 for (
struct ifaddrs* ifa = myaddrs; ifa !=
nullptr; ifa = ifa->ifa_next)
333 if (ifa->ifa_addr ==
nullptr)
continue;
334 if ((ifa->ifa_flags & IFF_UP) == 0)
continue;
335 if ((ifa->ifa_flags & IFF_LOOPBACK) != 0)
continue;
337 if (std::optional<CNetAddr> addr = FromSockAddr(ifa->ifa_addr, std::nullopt)) {
338 addresses.push_back(*addr);
341 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.
#define LogPrintLevel(category, level,...)
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.
std::string SysErrorString(int err)
Return system error string from errno value.