2020-10-22 00:11:49 +08:00
|
|
|
package dialer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"syscall"
|
2021-09-06 23:07:34 +08:00
|
|
|
|
|
|
|
"github.com/Dreamacro/clash/component/iface"
|
2022-02-19 00:08:51 +08:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2020-10-22 00:11:49 +08:00
|
|
|
)
|
|
|
|
|
2020-10-25 20:31:01 +08:00
|
|
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
|
|
|
|
2021-09-06 23:07:34 +08:00
|
|
|
func bindControl(ifaceIdx int, chain controlFn) controlFn {
|
|
|
|
return func(network, address string, c syscall.RawConn) (err error) {
|
|
|
|
defer func() {
|
|
|
|
if err == nil && chain != nil {
|
|
|
|
err = chain(network, address, c)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-10-25 20:31:01 +08:00
|
|
|
ipStr, _, err := net.SplitHostPort(address)
|
|
|
|
if err == nil {
|
|
|
|
ip := net.ParseIP(ipStr)
|
|
|
|
if ip != nil && !ip.IsGlobalUnicast() {
|
2021-09-06 23:07:34 +08:00
|
|
|
return
|
2020-10-25 20:31:01 +08:00
|
|
|
}
|
|
|
|
}
|
2020-10-22 00:11:49 +08:00
|
|
|
|
2021-11-10 22:19:11 +08:00
|
|
|
var innerErr error
|
|
|
|
err = c.Control(func(fd uintptr) {
|
2020-10-22 00:11:49 +08:00
|
|
|
switch network {
|
|
|
|
case "tcp4", "udp4":
|
2021-11-10 22:19:11 +08:00
|
|
|
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifaceIdx)
|
2020-10-22 00:11:49 +08:00
|
|
|
case "tcp6", "udp6":
|
2021-11-10 22:19:11 +08:00
|
|
|
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifaceIdx)
|
2020-10-22 00:11:49 +08:00
|
|
|
}
|
|
|
|
})
|
2021-11-10 22:19:11 +08:00
|
|
|
|
|
|
|
if innerErr != nil {
|
|
|
|
err = innerErr
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
2020-10-22 00:11:49 +08:00
|
|
|
}
|
2020-10-25 20:31:01 +08:00
|
|
|
}
|
|
|
|
|
2021-09-06 23:07:34 +08:00
|
|
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ net.IP) error {
|
|
|
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
2020-10-25 20:31:01 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-09-06 23:07:34 +08:00
|
|
|
dialer.Control = bindControl(ifaceObj.Index, dialer.Control)
|
2020-10-22 00:11:49 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-09-06 23:07:34 +08:00
|
|
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
|
|
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
2020-10-22 00:11:49 +08:00
|
|
|
if err != nil {
|
2021-09-06 23:07:34 +08:00
|
|
|
return "", err
|
2020-10-22 00:11:49 +08:00
|
|
|
}
|
|
|
|
|
2021-09-06 23:07:34 +08:00
|
|
|
lc.Control = bindControl(ifaceObj.Index, lc.Control)
|
|
|
|
return address, nil
|
2020-10-22 00:11:49 +08:00
|
|
|
}
|