// Package run executes external commands the way an unattended deployment tool // has to: never interactive, always bounded by a timeout, always captured. package run import ( "bytes" "context" "errors" "fmt" "os" "os/exec" "runtime" "strings" "sync" "time" "git.starwarslab.us/ATOM_IT/Deployr/internal/logx" ) // ErrNeedRoot is returned when a command requires root and no non-interactive // escalation path exists. var ErrNeedRoot = errors.New("root privileges required and passwordless sudo is unavailable") // DefaultTimeout bounds a single installer invocation. Large suites (Office, // Visual Studio) legitimately take a long time; anything past this is hung. const DefaultTimeout = 30 * time.Minute // Options describes one command invocation. type Options struct { Name string // executable, resolved via PATH unless absolute Args []string // arguments Env []string // extra KEY=VALUE pairs layered over the parent env Dir string // working directory Timeout time.Duration // zero means DefaultTimeout // NeedRoot makes the command run as root on Unix: already-root runs // unchanged, otherwise it is prefixed with non-interactive sudo. NeedRoot bool // AsUser drops from root to this account on Unix (Homebrew refuses root). AsUser string DryRun bool Log *logx.Logger } // Result is the outcome of a command. type Result struct { Cmd string Args []string ExitCode int Stdout string Stderr string Duration time.Duration TimedOut bool Err error } // Failed reports whether the command did not complete with exit status 0. func (r Result) Failed() bool { return r.Err != nil || r.ExitCode != 0 } // Output returns stdout and stderr joined and trimmed, for error messages. func (r Result) Output() string { return strings.TrimSpace(strings.TrimSpace(r.Stdout) + "\n" + strings.TrimSpace(r.Stderr)) } // Contains reports whether the combined output contains needle, case-insensitively. // Package managers communicate a lot through prose rather than exit codes. func (r Result) Contains(needle string) bool { return strings.Contains(strings.ToLower(r.Output()), strings.ToLower(needle)) } // Describe renders the command line for logs. func (r Result) Describe() string { if len(r.Args) == 0 { return r.Cmd } return r.Cmd + " " + strings.Join(r.Args, " ") } // Error summarises a failure in one line. func (r Result) Error() string { switch { case r.TimedOut: return fmt.Sprintf("timed out after %s", r.Duration.Round(time.Second)) case r.Err != nil: return r.Err.Error() default: msg := fmt.Sprintf("exit status %d", r.ExitCode) if out := lastLine(r.Output()); out != "" { msg += ": " + out } return msg } } func lastLine(s string) string { lines := strings.Split(strings.TrimSpace(s), "\n") for i := len(lines) - 1; i >= 0; i-- { if l := strings.TrimSpace(lines[i]); l != "" { if len(l) > 200 { return l[:200] + "..." } return l } } return "" } // Exec runs a command to completion and returns its captured result. func Exec(ctx context.Context, o Options) Result { name, args := o.Name, append([]string(nil), o.Args...) env := append([]string(nil), o.Env...) if runtime.GOOS != "windows" { var err error name, args, env, err = escalate(name, args, env, o) if err != nil { return Result{Cmd: o.Name, Args: o.Args, Err: err, ExitCode: -1} } } res := Result{Cmd: name, Args: args} if o.Log != nil { o.Log.Debugf("exec: %s", res.Describe()) } if o.DryRun { return res } timeout := o.Timeout if timeout <= 0 { timeout = DefaultTimeout } ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() cmd := exec.CommandContext(ctx, name, args...) cmd.Dir = o.Dir if len(env) > 0 { cmd.Env = append(os.Environ(), env...) } // Nothing may ever wait on a prompt: stdin is closed, not inherited. cmd.Stdin = nil var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr // Give a killed process a moment to die before we give up on its pipes. cmd.WaitDelay = 10 * time.Second hideWindow(cmd) start := time.Now() err := cmd.Run() res.Duration = time.Since(start) res.Stdout = stdout.String() res.Stderr = stderr.String() switch { case ctx.Err() == context.DeadlineExceeded: res.TimedOut = true res.ExitCode = -1 res.Err = fmt.Errorf("timed out after %s", timeout) case err == nil: res.ExitCode = 0 default: var ee *exec.ExitError if errors.As(err, &ee) { res.ExitCode = ee.ExitCode() } else { res.ExitCode = -1 res.Err = err } } if o.Log != nil && res.Failed() { o.Log.Debugf("exit %d after %s: %s", res.ExitCode, res.Duration.Round(time.Millisecond), lastLine(res.Output())) } return res } // escalate rewrites a command for Unix privilege requirements: sudo up to root // when NeedRoot, or sudo down to AsUser when running as root. func escalate(name string, args, env []string, o Options) (string, []string, []string, error) { root := os.Geteuid() == 0 if o.AsUser != "" && root { prefixed := []string{"-u", o.AsUser, "-H"} if len(env) > 0 { // sudo scrubs the environment, so re-apply it on the far side. prefixed = append(prefixed, "/usr/bin/env") prefixed = append(prefixed, env...) env = nil } prefixed = append(prefixed, name) return "sudo", append(prefixed, args...), env, nil } if o.NeedRoot && !root { if !sudoNonInteractive() { return "", nil, nil, ErrNeedRoot } return "sudo", append([]string{"-n", name}, args...), env, nil } return name, args, env, nil } var ( sudoOnce sync.Once sudoOK bool ) // sudoNonInteractive reports whether `sudo -n` succeeds without a password. // Probing once per process keeps us from spraying auth failures into the logs. func sudoNonInteractive() bool { sudoOnce.Do(func() { if _, err := exec.LookPath("sudo"); err != nil { return } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() sudoOK = exec.CommandContext(ctx, "sudo", "-n", "true").Run() == nil }) return sudoOK } var ( pathMu sync.Mutex pathCache = map[string]string{} ) // Which resolves an executable, caching both hits and misses. func Which(name string) (string, bool) { pathMu.Lock() defer pathMu.Unlock() if p, ok := pathCache[name]; ok { return p, p != "" } p, err := exec.LookPath(name) if err != nil { pathCache[name] = "" return "", false } pathCache[name] = p return p, true } // Available reports whether an executable exists on PATH. func Available(name string) bool { _, ok := Which(name) return ok } // CanEscalate reports whether privileged commands can run without a prompt: // already root, or passwordless sudo is configured. On Windows the process // token decides, so this is not the right question and it answers true. func CanEscalate() bool { if runtime.GOOS == "windows" { return true } return os.Geteuid() == 0 || sudoNonInteractive() }