2021-11-08 16:59:48 +08:00
|
|
|
//go:build linux
|
|
|
|
|
|
|
|
package dialer
|
|
|
|
|
|
|
|
import (
|
2023-02-13 11:14:19 +08:00
|
|
|
"context"
|
2021-11-08 16:59:48 +08:00
|
|
|
"net"
|
2022-04-20 01:52:51 +08:00
|
|
|
"net/netip"
|
2021-11-08 16:59:48 +08:00
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
2022-04-20 01:52:51 +08:00
|
|
|
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ netip.Addr) {
|
2023-02-13 11:14:19 +08:00
|
|
|
addControlToDialer(dialer, bindMarkToControl(mark))
|
2021-11-08 16:59:48 +08:00
|
|
|
}
|
|
|
|
|
2022-04-20 01:52:51 +08:00
|
|
|
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
|
2023-02-13 11:14:19 +08:00
|
|
|
addControlToListenConfig(lc, bindMarkToControl(mark))
|
2021-11-08 16:59:48 +08:00
|
|
|
}
|
|
|
|
|
2023-02-13 11:14:19 +08:00
|
|
|
func bindMarkToControl(mark int) controlFn {
|
|
|
|
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
2021-11-08 16:59:48 +08:00
|
|
|
|
2022-04-20 01:52:51 +08:00
|
|
|
addrPort, err := netip.ParseAddrPort(address)
|
|
|
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
|
|
|
return
|
2021-11-08 16:59:48 +08:00
|
|
|
}
|
|
|
|
|
2022-06-30 17:27:38 +08:00
|
|
|
var innerErr error
|
|
|
|
err = c.Control(func(fd uintptr) {
|
|
|
|
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
2021-11-08 16:59:48 +08:00
|
|
|
})
|
2022-06-30 17:27:38 +08:00
|
|
|
if innerErr != nil {
|
|
|
|
err = innerErr
|
|
|
|
}
|
|
|
|
return
|
2021-11-08 16:59:48 +08:00
|
|
|
}
|
|
|
|
}
|