diff --git a/cmd/sing-box/cmd_run.go b/cmd/sing-box/cmd_run.go index 568ce1b1..bde811f7 100644 --- a/cmd/sing-box/cmd_run.go +++ b/cmd/sing-box/cmd_run.go @@ -133,7 +133,7 @@ func create() (*box.Box, context.CancelFunc, error) { } options.Log.DisableColor = true } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(globalCtx) instance, err := box.New(box.Options{ Context: ctx, Options: options, diff --git a/cmd/sing-box/main.go b/cmd/sing-box/main.go index 1880d1cb..66b7daa1 100644 --- a/cmd/sing-box/main.go +++ b/cmd/sing-box/main.go @@ -3,15 +3,19 @@ package main import ( "context" "os" + "os/user" + "strconv" "time" _ "github.com/sagernet/sing-box/include" "github.com/sagernet/sing-box/log" + "github.com/sagernet/sing/service/filemanager" "github.com/spf13/cobra" ) var ( + globalCtx context.Context configPaths []string configDirectories []string workingDir string @@ -37,15 +41,30 @@ func main() { } func preRun(cmd *cobra.Command, args []string) { + globalCtx = context.Background() + sudoUser := os.Getenv("SUDO_USER") + sudoUID, _ := strconv.Atoi(os.Getenv("SUDO_UID")) + sudoGID, _ := strconv.Atoi(os.Getenv("SUDO_GID")) + if sudoUID == 0 && sudoGID == 0 && sudoUser != "" { + sudoUserObject, _ := user.Lookup(sudoUser) + if sudoUserObject != nil { + sudoUID, _ = strconv.Atoi(sudoUserObject.Uid) + sudoGID, _ = strconv.Atoi(sudoUserObject.Gid) + } + } + if sudoUID > 0 && sudoGID > 0 { + globalCtx = filemanager.WithDefault(globalCtx, "", "", sudoUID, sudoGID) + } if disableColor { log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger()) } if workingDir != "" { _, err := os.Stat(workingDir) if err != nil { - os.MkdirAll(workingDir, 0o777) + filemanager.MkdirAll(globalCtx, workingDir, 0o777) } - if err := os.Chdir(workingDir); err != nil { + err = os.Chdir(workingDir) + if err != nil { log.Fatal(err) } }