From 007c97fe679c71abe6013567885346796830cd04 Mon Sep 17 00:00:00 2001 From: Jack Date: Mon, 27 Mar 2023 13:26:39 +0800 Subject: [PATCH] Feature: support pre&post-up exec (#233) * Add tun pre/post script * Improve: pre & post tun --------- Co-authored-by: xjasonlyu --- engine/engine.go | 26 ++++++++++++++++++++++++++ engine/key.go | 2 ++ main.go | 2 ++ 3 files changed, 30 insertions(+) diff --git a/engine/engine.go b/engine/engine.go index 6e67179..e7cb863 100644 --- a/engine/engine.go +++ b/engine/engine.go @@ -3,6 +3,8 @@ package engine import ( "errors" "net" + "os/exec" + "strings" "sync" "time" @@ -90,6 +92,15 @@ func stop() (err error) { return err } +func execCommand(cmd string) error { + parts := strings.Fields(cmd) + if len(parts) == 0 { + return errors.New("empty command") + } + _, err := exec.Command(parts[0], parts[1:]...).Output() + return err +} + func general(k *Key) error { level, err := log.ParseLevel(k.LogLevel) if err != nil { @@ -158,6 +169,21 @@ func netstack(k *Key) (err error) { return errors.New("empty device") } + if k.TUNPreUp != "" { + if preUpErr := execCommand(k.TUNPreUp); preUpErr != nil { + log.Warnf("[TUN] failed to pre-execute: %s: %v", k.TUNPreUp, preUpErr) + } + } + + defer func() { + if k.TUNPostUp == "" || err != nil { + return + } + if postUpErr := execCommand(k.TUNPostUp); postUpErr != nil { + log.Warnf("[TUN] failed to post-execute: %s: %v", k.TUNPostUp, postUpErr) + } + }() + if _defaultProxy, err = parseProxy(k.Proxy); err != nil { return } diff --git a/engine/key.go b/engine/key.go index 1bd5ede..32e39dc 100644 --- a/engine/key.go +++ b/engine/key.go @@ -13,5 +13,7 @@ type Key struct { TCPModerateReceiveBuffer bool `yaml:"tcp-moderate-receive-buffer"` TCPSendBufferSize string `yaml:"tcp-send-buffer-size"` TCPReceiveBufferSize string `yaml:"tcp-receive-buffer-size"` + TUNPreUp string `yaml:"tun-pre-up"` + TUNPostUp string `yaml:"tun-post-up"` UDPTimeout time.Duration `yaml:"udp-timeout"` } diff --git a/main.go b/main.go index eb17ff6..7cc4b1f 100644 --- a/main.go +++ b/main.go @@ -36,6 +36,8 @@ func init() { flag.StringVar(&key.TCPSendBufferSize, "tcp-sndbuf", "", "Set TCP send buffer size for netstack") flag.StringVar(&key.TCPReceiveBufferSize, "tcp-rcvbuf", "", "Set TCP receive buffer size for netstack") flag.BoolVar(&key.TCPModerateReceiveBuffer, "tcp-auto-tuning", false, "Enable TCP receive buffer auto-tuning") + flag.StringVar(&key.TUNPreUp, "tun-pre-up", "", "Execute a command before TUN device setup") + flag.StringVar(&key.TUNPostUp, "tun-post-up", "", "Execute a command after TUN device setup") flag.BoolVar(&versionFlag, "version", false, "Show version and then quit") flag.Parse() }