Make generated files have SUDO_USER's permissions if possible.

This commit is contained in:
世界 2023-12-17 20:49:25 +08:00
parent 6d4f54d56a
commit 285278b7be
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 22 additions and 3 deletions

View file

@ -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,

View file

@ -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)
}
}