2020-10-21 16:11:49 +00:00
|
|
|
package dialer
|
|
|
|
|
|
|
|
import (
|
2023-02-13 03:14:19 +00:00
|
|
|
"context"
|
2020-10-21 16:11:49 +00:00
|
|
|
"net"
|
2022-04-19 17:52:51 +00:00
|
|
|
"net/netip"
|
2020-10-21 16:11:49 +00:00
|
|
|
"syscall"
|
2021-09-06 15:07:34 +00:00
|
|
|
|
2023-11-03 13:01:45 +00:00
|
|
|
"github.com/metacubex/mihomo/component/iface"
|
2022-02-18 16:08:51 +00:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2020-10-21 16:11:49 +00:00
|
|
|
)
|
|
|
|
|
2023-02-13 03:14:19 +00:00
|
|
|
func bindControl(ifaceIdx int) controlFn {
|
|
|
|
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
2022-04-19 17:52:51 +00:00
|
|
|
addrPort, err := netip.ParseAddrPort(address)
|
|
|
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
|
|
|
return
|
2020-10-25 12:31:01 +00:00
|
|
|
}
|
2020-10-21 16:11:49 +00:00
|
|
|
|
2021-11-10 14:19:11 +00:00
|
|
|
var innerErr error
|
|
|
|
err = c.Control(func(fd uintptr) {
|
2020-10-21 16:11:49 +00:00
|
|
|
switch network {
|
|
|
|
case "tcp4", "udp4":
|
2021-11-10 14:19:11 +00:00
|
|
|
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifaceIdx)
|
2020-10-21 16:11:49 +00:00
|
|
|
case "tcp6", "udp6":
|
2021-11-10 14:19:11 +00:00
|
|
|
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifaceIdx)
|
2020-10-21 16:11:49 +00:00
|
|
|
}
|
|
|
|
})
|
2021-11-10 14:19:11 +00:00
|
|
|
|
|
|
|
if innerErr != nil {
|
|
|
|
err = innerErr
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
2020-10-21 16:11:49 +00:00
|
|
|
}
|
2020-10-25 12:31:01 +00:00
|
|
|
}
|
|
|
|
|
2022-04-19 17:52:51 +00:00
|
|
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
2021-09-06 15:07:34 +00:00
|
|
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
2020-10-25 12:31:01 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-02-13 03:14:19 +00:00
|
|
|
addControlToDialer(dialer, bindControl(ifaceObj.Index))
|
2020-10-21 16:11:49 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-09-06 15:07:34 +00:00
|
|
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
|
|
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
2020-10-21 16:11:49 +00:00
|
|
|
if err != nil {
|
2021-09-06 15:07:34 +00:00
|
|
|
return "", err
|
2020-10-21 16:11:49 +00:00
|
|
|
}
|
|
|
|
|
2023-02-13 03:14:19 +00:00
|
|
|
addControlToListenConfig(lc, bindControl(ifaceObj.Index))
|
2021-09-06 15:07:34 +00:00
|
|
|
return address, nil
|
2020-10-21 16:11:49 +00:00
|
|
|
}
|
2023-02-13 02:14:59 +00:00
|
|
|
|
|
|
|
func ParseNetwork(network string, addr netip.Addr) string {
|
|
|
|
return network
|
|
|
|
}
|