sing/common/control/bind.go
stT-e5gna2z5MBS 3c4a2b06a9
BindToInterfaceFunc: allow block()/AutoDetectInterfaceFunc() to return error
to avoid Tun traffic loopback, AutoDetectInterfaceFunc() should return error when no valid interface is found
2023-09-20 14:05:54 +08:00

62 lines
1.8 KiB
Go

package control
import (
"os"
"runtime"
"syscall"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
func BindToInterface(finder InterfaceFinder, interfaceName string, interfaceIndex int) Func {
return func(network, address string, conn syscall.RawConn) error {
return BindToInterface0(finder, conn, network, address, interfaceName, interfaceIndex)
}
}
func BindToInterfaceFunc(finder InterfaceFinder, block func(network string, address string) (interfaceName string, interfaceIndex int, err error)) Func {
return func(network, address string, conn syscall.RawConn) error {
interfaceName, interfaceIndex, err := block(network, address)
if err != nil {
return err
}
return BindToInterface0(finder, conn, network, address, interfaceName, interfaceIndex)
}
}
const useInterfaceName = runtime.GOOS == "linux" || runtime.GOOS == "android"
func BindToInterface0(finder InterfaceFinder, conn syscall.RawConn, network string, address string, interfaceName string, interfaceIndex int) error {
if interfaceName == "" && interfaceIndex == -1 {
return nil
}
if addr := M.ParseSocksaddr(address).Addr; addr.IsValid() && N.IsVirtual(addr) {
return nil
}
if interfaceName != "" && useInterfaceName || interfaceIndex != -1 && !useInterfaceName {
return bindToInterface(conn, network, address, interfaceName, interfaceIndex)
}
if finder == nil {
return os.ErrInvalid
}
var err error
if useInterfaceName {
interfaceName, err = finder.InterfaceNameByIndex(interfaceIndex)
} else {
interfaceIndex, err = finder.InterfaceIndexByName(interfaceName)
}
if err != nil {
return err
}
if useInterfaceName {
if interfaceName == "" {
return nil
}
} else {
if interfaceIndex == -1 {
return nil
}
}
return bindToInterface(conn, network, address, interfaceName, interfaceIndex)
}