From 8d3c28a516acf419db44dc30f710641d4b7555ff Mon Sep 17 00:00:00 2001 From: xjasonlyu Date: Thu, 1 Dec 2022 15:46:49 +0800 Subject: [PATCH] Feature: support mark on FreeBSD & OpenBSD --- component/dialer/sockopt_freebsd.go | 33 +++++++++++++++++++++++++++++ component/dialer/sockopt_openbsd.go | 33 +++++++++++++++++++++++++++++ component/dialer/sockopt_others.go | 2 +- 3 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 component/dialer/sockopt_freebsd.go create mode 100644 component/dialer/sockopt_openbsd.go diff --git a/component/dialer/sockopt_freebsd.go b/component/dialer/sockopt_freebsd.go new file mode 100644 index 0000000..02d0f4b --- /dev/null +++ b/component/dialer/sockopt_freebsd.go @@ -0,0 +1,33 @@ +package dialer + +import ( + "net" + "syscall" + + "golang.org/x/sys/unix" +) + +func setSocketOptions(network, address string, c syscall.RawConn, opts *Options) (err error) { + if opts == nil || !isTCPSocket(network) && !isUDPSocket(network) { + return + } + + var innerErr error + err = c.Control(func(fd uintptr) { + host, _, _ := net.SplitHostPort(address) + if ip := net.ParseIP(host); ip != nil && !ip.IsGlobalUnicast() { + return + } + + if opts.RoutingMark != 0 { + if innerErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_USER_COOKIE, opts.RoutingMark); innerErr != nil { + return + } + } + }) + + if innerErr != nil { + err = innerErr + } + return +} diff --git a/component/dialer/sockopt_openbsd.go b/component/dialer/sockopt_openbsd.go new file mode 100644 index 0000000..361ee80 --- /dev/null +++ b/component/dialer/sockopt_openbsd.go @@ -0,0 +1,33 @@ +package dialer + +import ( + "net" + "syscall" + + "golang.org/x/sys/unix" +) + +func setSocketOptions(network, address string, c syscall.RawConn, opts *Options) (err error) { + if opts == nil || !isTCPSocket(network) && !isUDPSocket(network) { + return + } + + var innerErr error + err = c.Control(func(fd uintptr) { + host, _, _ := net.SplitHostPort(address) + if ip := net.ParseIP(host); ip != nil && !ip.IsGlobalUnicast() { + return + } + + if opts.RoutingMark != 0 { + if innerErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RTABLE, opts.RoutingMark); innerErr != nil { + return + } + } + }) + + if innerErr != nil { + err = innerErr + } + return +} diff --git a/component/dialer/sockopt_others.go b/component/dialer/sockopt_others.go index ebaef93..1695529 100644 --- a/component/dialer/sockopt_others.go +++ b/component/dialer/sockopt_others.go @@ -1,4 +1,4 @@ -//go:build !linux && !darwin && !windows +//go:build !unix && !windows package dialer