2020-10-21 16:11:49 +00:00
|
|
|
package dialer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"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
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2020-10-21 16:11:49 +00:00
|
|
|
)
|
|
|
|
|
2020-10-25 12:31:01 +00:00
|
|
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
|
|
|
|
2021-09-06 15:07:34 +00:00
|
|
|
func bindControl(ifaceName string, 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)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-11-17 08:03:47 +00:00
|
|
|
var innerErr error
|
|
|
|
err = c.Control(func(fd uintptr) {
|
|
|
|
innerErr = unix.BindToDevice(int(fd), ifaceName)
|
2020-10-21 16:11:49 +00:00
|
|
|
})
|
2021-11-17 08:03:47 +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
|
|
|
dialer.Control = bindControl(ifaceName, dialer.Control)
|
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) {
|
|
|
|
lc.Control = bindControl(ifaceName, lc.Control)
|
2020-10-21 16:11:49 +00:00
|
|
|
|
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
|
|
|
|
}
|