github.com/sagernet/sing-box@v1.9.0-rc.20/cmd/sing-box/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"os/user"
     7  	"strconv"
     8  	"time"
     9  
    10  	_ "github.com/sagernet/sing-box/include"
    11  	"github.com/sagernet/sing-box/log"
    12  	"github.com/sagernet/sing/service/filemanager"
    13  
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  var (
    18  	globalCtx         context.Context
    19  	configPaths       []string
    20  	configDirectories []string
    21  	workingDir        string
    22  	disableColor      bool
    23  )
    24  
    25  var mainCommand = &cobra.Command{
    26  	Use:              "sing-box",
    27  	PersistentPreRun: preRun,
    28  }
    29  
    30  func init() {
    31  	mainCommand.PersistentFlags().StringArrayVarP(&configPaths, "config", "c", nil, "set configuration file path")
    32  	mainCommand.PersistentFlags().StringArrayVarP(&configDirectories, "config-directory", "C", nil, "set configuration directory path")
    33  	mainCommand.PersistentFlags().StringVarP(&workingDir, "directory", "D", "", "set working directory")
    34  	mainCommand.PersistentFlags().BoolVarP(&disableColor, "disable-color", "", false, "disable color output")
    35  }
    36  
    37  func main() {
    38  	if err := mainCommand.Execute(); err != nil {
    39  		log.Fatal(err)
    40  	}
    41  }
    42  
    43  func preRun(cmd *cobra.Command, args []string) {
    44  	globalCtx = context.Background()
    45  	sudoUser := os.Getenv("SUDO_USER")
    46  	sudoUID, _ := strconv.Atoi(os.Getenv("SUDO_UID"))
    47  	sudoGID, _ := strconv.Atoi(os.Getenv("SUDO_GID"))
    48  	if sudoUID == 0 && sudoGID == 0 && sudoUser != "" {
    49  		sudoUserObject, _ := user.Lookup(sudoUser)
    50  		if sudoUserObject != nil {
    51  			sudoUID, _ = strconv.Atoi(sudoUserObject.Uid)
    52  			sudoGID, _ = strconv.Atoi(sudoUserObject.Gid)
    53  		}
    54  	}
    55  	if sudoUID > 0 && sudoGID > 0 {
    56  		globalCtx = filemanager.WithDefault(globalCtx, "", "", sudoUID, sudoGID)
    57  	}
    58  	if disableColor {
    59  		log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger())
    60  	}
    61  	if workingDir != "" {
    62  		_, err := os.Stat(workingDir)
    63  		if err != nil {
    64  			filemanager.MkdirAll(globalCtx, workingDir, 0o777)
    65  		}
    66  		err = os.Chdir(workingDir)
    67  		if err != nil {
    68  			log.Fatal(err)
    69  		}
    70  	}
    71  	if len(configPaths) == 0 && len(configDirectories) == 0 {
    72  		configPaths = append(configPaths, "config.json")
    73  	}
    74  }