Clash.Meta/component/dialer/mark_linux.go

42 lines
907 B
Go
Raw Normal View History

2021-11-08 16:59:48 +08:00
//go:build linux
package dialer
import (
"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) {
2021-11-08 16:59:48 +08:00
dialer.Control = bindMarkToControl(mark, dialer.Control)
}
2022-04-20 01:52:51 +08:00
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
2021-11-08 16:59:48 +08:00
lc.Control = bindMarkToControl(mark, lc.Control)
}
func bindMarkToControl(mark 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)
}
}()
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
}
}