add sockopts config

This commit is contained in:
ginuerzh
2022-03-29 23:04:12 +08:00
parent 78089d8887
commit 47cfc087e9
11 changed files with 115 additions and 36 deletions

View File

@ -10,14 +10,17 @@ import (
"github.com/go-gost/core/logger"
)
const (
DefaultTimeout = 15 * time.Second
)
var (
DefaultNetDialer = &NetDialer{
Timeout: 30 * time.Second,
}
DefaultNetDialer = &NetDialer{}
)
type NetDialer struct {
Interface string
Mark int
Timeout time.Duration
DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
Logger logger.Logger
@ -27,6 +30,10 @@ func (d *NetDialer) Dial(ctx context.Context, network, addr string) (net.Conn, e
if d == nil {
d = DefaultNetDialer
}
if d.Timeout <= 0 {
d.Timeout = DefaultTimeout
}
log := d.Logger
if log == nil {
log = logger.Default()
@ -39,7 +46,7 @@ func (d *NetDialer) Dial(ctx context.Context, network, addr string) (net.Conn, e
if d.DialFunc != nil {
return d.DialFunc(ctx, network, addr)
}
logger.Default().Infof("interface: %s %v/%s", ifceName, ifAddr, network)
log.Infof("interface: %s %v/%s", ifceName, ifAddr, network)
switch network {
case "udp", "udp4", "udp6":
@ -59,17 +66,18 @@ func (d *NetDialer) Dial(ctx context.Context, network, addr string) (net.Conn, e
Timeout: d.Timeout,
LocalAddr: ifAddr,
Control: func(network, address string, c syscall.RawConn) error {
var cerr error
err := c.Control(func(fd uintptr) {
cerr = bindDevice(fd, ifceName)
return c.Control(func(fd uintptr) {
if ifceName != "" {
if err := bindDevice(fd, ifceName); err != nil {
log.Warnf("bind device: %v", err)
}
}
if d.Mark != 0 {
if err := setMark(fd, d.Mark); err != nil {
log.Warnf("set mark: %v", err)
}
}
})
if err != nil {
return err
}
if cerr != nil {
return cerr
}
return nil
},
}
return netd.DialContext(ctx, network, addr)

View File

@ -12,3 +12,10 @@ func bindDevice(fd uintptr, ifceName string) error {
}
return unix.BindToDevice(int(fd), ifceName)
}
func setMark(fd uintptr, mark int) error {
if mark == 0 {
return nil
}
return unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_MARK, mark)
}

View File

@ -5,3 +5,7 @@ package dialer
func bindDevice(fd uintptr, ifceName string) error {
return nil
}
func setMark(fd uintptr, mark int) error {
return nil
}

View File

@ -41,7 +41,7 @@ func (r *UDPRelay) SetBufferSize(n int) {
func (r *UDPRelay) Run() (err error) {
bufSize := r.bufferSize
if bufSize <= 0 {
bufSize = 1024
bufSize = 1500
}
errc := make(chan error, 2)