Only consider routes which are UP and whose destinations are a gateway. If multiple match, ensure we're reporting the one with minimum metric value.

Signed-off-by: DL6ER <dl6er@dl6er.de>
This commit is contained in:
DL6ER 2022-06-07 07:52:34 +02:00
parent 4b6bafe53a
commit b0d9244eba
No known key found for this signature in database
GPG Key ID: 00135ACBD90B28DD
2 changed files with 33 additions and 9 deletions

View File

@ -40,6 +40,8 @@
#include "../database/aliasclients.h"
// get_edestr()
#include "api_helper.h"
// RTF_UP, RTF_GATEWAY
#include <linux/route.h>
// defined in src/dnsmasq/cache.c
extern char *querystr(char *desc, unsigned short type);
@ -1461,6 +1463,7 @@ void getGateway(const int *sock)
// Get IPv4 default route gateway and associated interface
in_addr_t gw = 0;
long dest_r = 0, gw_r = 0;
int flags = 0, metric = 0, minmetric = __INT_MAX__;
char iface[IF_NAMESIZE] = { 0 };
char iface_r[IF_NAMESIZE] = { 0 };
char buf[1024] = { 0 };
@ -1471,16 +1474,29 @@ void getGateway(const int *sock)
// Parse /proc/net/route - the kernel's IPv4 routing table
while(fgets(buf, sizeof(buf), file))
{
if(sscanf(buf, "%s %lx %lx", iface_r, &dest_r, &gw_r) == 3)
{
// Skip non-default routes
if(dest_r != 0)
continue;
if(sscanf(buf, "%s %lx %lx %x %*i %*i %i", iface_r, &dest_r, &gw_r, &flags, &metric) != 5)
continue;
// default 0.0.0.0
// Only anaylze routes which are UP and whose
// destinations are a gateway
if(!(flags & RTF_UP) || !(flags & RTF_GATEWAY))
continue;
// Only analyze "catch all" routes (destination 0.0.0.0)
if(dest_r != 0)
continue;
// Store default gateway, overwrite if we find a route with
// a lower metric
if(metric < minmetric)
{
minmetric = metric;
gw = gw_r;
strcpy(iface, iface_r);
break;
if(config.debug & DEBUG_API)
logg("Reading interfaces: flags: %i, addr: %s, iface: %s, metric: %i, minmetric: %i",
flags, inet_ntoa(*(struct in_addr *) &gw), iface, metric, minmetric);
}
}
fclose(file);

View File

@ -1328,10 +1328,18 @@
}
@test "Reported default gateway is correct" {
routes="$(ip -4 route show default)"
ipaddr="$(awk '{print $3}' <<< $routes)"
interf="$(awk '{print $5}' <<< $routes)"
printf "ip -4 route show default: %s\n" "${routes}"
run bash -c 'echo ">gateway >quit" | nc -v 127.0.0.1 4711'
ftlip="$(awk '{print $1}' <<< "${lines[0]}")"
ftlif="$(awk '{print $2}' <<< "${lines[0]}")"
printf "%s\n" "${lines[@]}"
# Check gateway IP address
[[ "$(awk '{print $1}' <<< "${lines[0]}")" == "$(ip -4 route show default | awk '{print $3}')" ]]
printf "Checking IP: %s == %s\n" "$ftlip" "$ipaddr"
[[ "$ftlip" == "$ipaddr" ]]
# Check gateway interface
[[ "$(awk '{print $2}' <<< "${lines[0]}")" == "$(ip -4 route show default | awk '{print $5}')" ]]
printf "Checking IF: %s == %s\n" "$ftlif" "$interf"
[[ "$ftlif" == "$interf" ]]
}