Skip to content

Commit

Permalink
feat: fetch flags and mtu from if_msghdr directly
Browse files Browse the repository at this point in the history
  • Loading branch information
ruokeqx committed Jan 2, 2025
1 parent 12269c2 commit 868e37b
Showing 1 changed file with 10 additions and 25 deletions.
35 changes: 10 additions & 25 deletions tun/tun_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,12 @@
package tun

import (
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"syscall"
"time"
"unsafe"

"golang.org/x/sys/unix"
Expand All @@ -30,18 +28,6 @@ type NativeTun struct {
closeOnce sync.Once
}

func retryInterfaceByIndex(index int) (iface *net.Interface, err error) {
for i := 0; i < 20; i++ {
iface, err = net.InterfaceByIndex(index)
if err != nil && errors.Is(err, unix.ENOMEM) {
time.Sleep(time.Duration(i) * time.Second / 3)
continue
}
return iface, err
}
return nil, err
}

func (tun *NativeTun) routineRouteListener(tunIfindex int) {
var (
statusUp bool
Expand All @@ -62,26 +48,23 @@ func (tun *NativeTun) routineRouteListener(tunIfindex int) {
return
}

if n < 14 {
//sizeof(if_msghdr) = 112
if n < 112 {
continue
}

if data[3 /* type */] != unix.RTM_IFINFO {
if data[3 /* ifm_type */] != unix.RTM_IFINFO {
continue
}
ifindex := int(*(*uint16)(unsafe.Pointer(&data[12 /* ifindex */])))
ifindex := int(*(*uint16)(unsafe.Pointer(&data[12 /* ifm_index */])))
if ifindex != tunIfindex {
continue
}

iface, err := retryInterfaceByIndex(ifindex)
if err != nil {
tun.errors <- err
return
}
flags := int(*(*uint32)(unsafe.Pointer(&data[8 /* ifm_flags */])))

// Up / Down event
up := (iface.Flags & net.FlagUp) != 0
up := (flags & syscall.IFF_UP) != 0
if up != statusUp && up {
tun.events <- EventUp
}
Expand All @@ -90,11 +73,13 @@ func (tun *NativeTun) routineRouteListener(tunIfindex int) {
}
statusUp = up

mtu := int(*(*uint32)(unsafe.Pointer(&data[24 /* ifm_data.ifi_mtu */])))

// MTU changes
if iface.MTU != statusMTU {
if mtu != statusMTU {
tun.events <- EventMTUUpdate
}
statusMTU = iface.MTU
statusMTU = mtu
}
}

Expand Down

0 comments on commit 868e37b

Please sign in to comment.