TUN inbound: Support autoSystemRoutingTable and autoOutboundsInterface on macOS and Linux as well (#6366)

https://github.com/XTLS/Xray-core/pull/6366#issuecomment-4788510365
This commit is contained in:
Jasper344612
2026-06-24 19:06:00 +08:00
committed by GitHub
parent 7e7e820763
commit 241aa38ac0
7 changed files with 550 additions and 85 deletions
+7 -81
View File
@@ -3,8 +3,6 @@ package tun
import (
"context"
"net"
"sort"
"strings"
"sync"
"github.com/xtls/xray-core/common/errors"
@@ -31,95 +29,23 @@ func (updater *InterfaceUpdater) Update() {
updater.Lock()
defer updater.Unlock()
if updater.iface != nil {
iface, err := net.InterfaceByIndex(updater.iface.Index)
if err == nil && iface.Name == updater.iface.Name {
return
}
}
updater.iface = nil
interfaces, err := net.Interfaces()
got, err := findOutboundInterface(updater.tunIndex, updater.fixedName)
if err != nil {
errors.LogInfoInner(context.Background(), err, "[tun] failed to update interface")
updater.iface = nil
return
}
var got *net.Interface
if updater.fixedName != "" {
for _, iface := range interfaces {
if iface.Index == updater.tunIndex {
continue
}
if iface.Name == updater.fixedName {
got = &iface
break
}
}
} else {
var ifs []struct {
index int
score int
}
for i, iface := range interfaces {
if iface.Index == updater.tunIndex {
continue
}
if strings.Contains(iface.Name, "vEthernet") {
continue
}
if iface.Flags&net.FlagUp == 0 {
continue
}
if iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil || len(addrs) == 0 {
continue
}
ifs = append(ifs, struct {
index int
score int
}{i, score(&iface, addrs)})
}
sort.Slice(ifs, func(i, j int) bool {
if ifs[i].score != ifs[j].score {
return ifs[i].score > ifs[j].score
}
return interfaces[ifs[i].index].Name < interfaces[ifs[j].index].Name
})
if len(ifs) > 0 {
iface := interfaces[ifs[0].index]
got = &iface
}
}
if got == nil {
errors.LogInfo(context.Background(), "[tun] failed to update interface > got == nil")
updater.iface = nil
return
}
if updater.iface != nil && updater.iface.Index == got.Index && updater.iface.Name == got.Name {
return
}
updater.iface = got
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
}
func score(iface *net.Interface, addrs []net.Addr) int {
score := 0
name := strings.ToLower(iface.Name)
if strings.Contains(name, "wlan") || strings.Contains(name, "wi-fi") {
score += 2
}
for _, addr := range addrs {
if strings.HasPrefix(addr.String(), "192.168.") {
score += 1
break
}
}
return score
}