Fix darwin monitor

This commit is contained in:
世界 2024-03-14 13:37:44 +08:00
parent 6ef2a6cdaa
commit 689e60891c
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 62 additions and 47 deletions

View file

@ -42,7 +42,7 @@ func (m *networkUpdateMonitor) loopUpdate() {
select {
case <-m.done:
return
case <-time.After(time.Second):
default:
}
err := m.loopUpdate0()
if err != nil {
@ -67,7 +67,16 @@ func (m *networkUpdateMonitor) loopUpdate1(routeSocketFile *os.File) {
defer routeSocketFile.Close()
buffer := buf.NewPacket()
defer buffer.Release()
done := make(chan struct{})
go func() {
select {
case <-m.done:
routeSocketFile.Close()
case <-done:
}
}()
n, err := routeSocketFile.Read(buffer.FreeBytes())
close(done)
if err != nil {
return
}
@ -92,6 +101,16 @@ func (m *networkUpdateMonitor) Close() error {
}
func (m *defaultInterfaceMonitor) checkUpdate() error {
var (
defaultInterface *net.Interface
err error
)
if m.options.UnderNetworkExtension {
defaultInterface, err = getDefaultInterfaceBySocket()
if err != nil {
return err
}
} else {
ribMessage, err := route.FetchRIB(unix.AF_UNSPEC, route.RIBTypeRoute, 0)
if err != nil {
return err
@ -100,7 +119,6 @@ func (m *defaultInterfaceMonitor) checkUpdate() error {
if err != nil {
return err
}
var defaultInterface *net.Interface
for _, rawRouteMessage := range routeMessages {
routeMessage := rawRouteMessage.(*route.RouteMessage)
if len(routeMessage.Addrs) <= unix.RTAX_NETMASK {
@ -137,13 +155,6 @@ func (m *defaultInterfaceMonitor) checkUpdate() error {
defaultInterface = routeInterface
break
}
if defaultInterface == nil {
if m.options.UnderNetworkExtension {
defaultInterface, err = getDefaultInterfaceBySocket()
if err != nil {
return err
}
}
}
if defaultInterface == nil {
return ErrNoRoute

View file

@ -6,7 +6,6 @@ import (
"errors"
"net"
"net/netip"
"runtime"
"sync"
"time"
@ -44,6 +43,7 @@ type defaultInterfaceMonitor struct {
defaultInterfaceIndex int
androidVPNEnabled bool
networkMonitor NetworkUpdateMonitor
checkUpdateTimer *time.Timer
element *list.Element[NetworkUpdateCallback]
access sync.Mutex
callbacks list.List[DefaultInterfaceUpdateCallback]
@ -72,9 +72,13 @@ func (m *defaultInterfaceMonitor) Start() error {
}
func (m *defaultInterfaceMonitor) delayCheckUpdate() {
if runtime.GOOS == "android" {
time.Sleep(time.Second)
if m.checkUpdateTimer != nil {
m.checkUpdateTimer.Stop()
}
m.checkUpdateTimer = time.AfterFunc(time.Second, m.postCheckUpdate)
}
func (m *defaultInterfaceMonitor) postCheckUpdate() {
err := m.updateInterfaces()
if err != nil {
m.logger.Error("update interfaces: ", err)