Skip to content

Commit 93b591c

Browse files
committed
NetIF (OpenBSD): fix default route detection
1 parent 8ecd58d commit 93b591c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/common/netif/netif_bsd.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
#include "netif.h"
22

33
#include "common/io/io.h"
4+
#include "util/mallocHelper.h"
45

56
#include <net/if.h>
67
#include <net/if_dl.h>
78
#include <net/route.h>
89
#include <netinet/in.h>
910
#include <sys/socket.h>
1011

12+
#ifdef __OpenBSD__
13+
#include <sys/sysctl.h>
14+
#endif
15+
1116
#define ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n))
1217

1318
#if defined(__APPLE__)
@@ -47,6 +52,37 @@ get_rt_address(struct rt_msghdr *rtm, int desired)
4752

4853
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
4954
{
55+
#if defined(__OpenBSD__)
56+
int mib[6] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY};
57+
size_t needed;
58+
59+
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
60+
return false;
61+
62+
FF_AUTO_FREE char* buf = malloc(needed);
63+
64+
if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
65+
return false;
66+
67+
char* lim = buf + needed;
68+
struct rt_msghdr* rtm;
69+
for (char* next = buf; next < lim; next += rtm->rtm_msglen) {
70+
rtm = (struct rt_msghdr *)next;
71+
struct sockaddr* sa = (struct sockaddr *)(rtm + 1);
72+
73+
if ((rtm->rtm_flags & RTF_GATEWAY) &&
74+
(sa->sa_family == AF_INET)) {
75+
struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(rtm, RTA_IFP);
76+
if (sdl->sdl_family == AF_LINK) {
77+
assert(sdl->sdl_nlen <= IF_NAMESIZE);
78+
memcpy(iface, sdl->sdl_data, sdl->sdl_nlen);
79+
iface[sdl->sdl_nlen] = '\0';
80+
*ifIndex = sdl->sdl_index;
81+
return true;
82+
}
83+
}
84+
}
85+
#else
5086
//https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104
5187

5288
FF_AUTO_CLOSE_FD int pfRoute = socket(PF_ROUTE, SOCK_RAW, AF_INET);
@@ -69,6 +105,11 @@ bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
69105
.hdr = {
70106
.rtm_type = RTM_GET,
71107
.rtm_flags = RTF_UP | RTF_GATEWAY,
108+
#ifdef __OpenBSD__
109+
.rtm_addrs = RTA_DST | RTA_IFA,
110+
#else
111+
.rtm_addrs = RTA_DST | RTA_IFP,
112+
#endif
72113
.rtm_version = RTM_VERSION,
73114
.rtm_addrs = RTA_DST | RTA_IFP,
74115
.rtm_msglen = sizeof(rtmsg.hdr) + sizeof(rtmsg.dst),
@@ -106,5 +147,7 @@ bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
106147
return false;
107148
}
108149
}
150+
#endif
151+
109152
return false;
110153
}

0 commit comments

Comments
 (0)