From 8e164185b900cd63ab802a7e9202c9937e1fa5a3 Mon Sep 17 00:00:00 2001 From: Cuong Manh Le Date: Thu, 12 Jan 2023 08:58:29 +0700 Subject: [PATCH] cmd/ctrld: always pass config file on windows start mode On windows, the SYSTEM user is used to run ctrld service. This user has different environment with the user that run the `ctrld` binary via CLI. That causes the mismatch issue in config file path, log path, or more generally, everything that involve with home directory. To circumvent this pain, just always passing the config path and the original home dir in start mode. So `ctrld run` command can setup things correctly. --- cmd/ctrld/cli.go | 16 +++++++++++----- cmd/ctrld/main.go | 4 ++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/cmd/ctrld/cli.go b/cmd/ctrld/cli.go index 6549f39..b84cc06 100644 --- a/cmd/ctrld/cli.go +++ b/cmd/ctrld/cli.go @@ -144,6 +144,8 @@ func initCLI() { runCmd.Flags().StringVarP(&logPath, "log", "", "", "path to log file") runCmd.Flags().IntVarP(&cacheSize, "cache_size", "", 0, "Enable cache with size items") runCmd.Flags().StringVarP(&cdUID, "cd", "", "", "Control D resolver uid") + runCmd.Flags().StringVarP(&homedir, "homedir", "", "", "") + _ = runCmd.Flags().MarkHidden("homedir") rootCmd.AddCommand(runCmd) @@ -169,14 +171,18 @@ func initCLI() { defaultConfigFile = filepath.Join(dir, defaultConfigFile) readConfigFile(true) } + sc.Arguments = append(sc.Arguments, "--homedir="+dir) + } - // On Windows, the service will be run as SYSTEM, so if ctrld start as Admin, - // the written config won't be writable by SYSTEM account, we have to update - // the config here when "--cd" is supplied. - if runtime.GOOS == "windows" && cdUID != "" { - processCDFlags() + // On Windows, the service will be run as SYSTEM, so if ctrld start as Admin, + // the user home dir is different, so pass specific arguments that relevant here. + if runtime.GOOS == "windows" { + processCDFlags() + if configPath == "" { + sc.Arguments = append(sc.Arguments, "--config="+defaultConfigFile) } } + s, err := service.New(&prog{}, sc) if err != nil { stderrMsg(err.Error()) diff --git a/cmd/ctrld/main.go b/cmd/ctrld/main.go index f82ee2f..5185e28 100644 --- a/cmd/ctrld/main.go +++ b/cmd/ctrld/main.go @@ -22,6 +22,7 @@ var ( secondaryUpstream string domains []string logPath string + homedir string cacheSize int cfg ctrld.Config verbose int @@ -44,6 +45,9 @@ func normalizeLogFilePath(logFilePath string) string { if logFilePath == "" || filepath.IsAbs(logFilePath) || service.Interactive() { return logFilePath } + if homedir != "" { + return filepath.Join(homedir, logFilePath) + } dir, _ := os.UserHomeDir() if dir == "" { return logFilePath