Repository Public
1// Package runcmd runs local programs for the agent: never through a shell,2// with a deadline, a minimal environment and bounded output.3package runcmd45import (6 "bytes"7 "context"8 "errors"9 "os"10 "os/exec"11 "strings"12 "syscall"13 "time"14)1516// BasePath is the PATH given to every child process.17const BasePath = "/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:/usr/local/bin"1819// Env returns the minimal environment of a child: PATH, a fixed C locale20// (parsers must not depend on the user's locale), HOME/USER when known, and21// the explicitly declared extra variables. Nothing else is inherited, so22// secrets present in the agent's own environment never reach a child.23func Env(extra ...string) []string {24 env := []string{"PATH=" + BasePath, "LC_ALL=C", "LANG=C"}25 if h, err := os.UserHomeDir(); err == nil && h != "" {26 env = append(env, "HOME="+h)27 }28 if u := os.Getenv("USER"); u != "" {29 env = append(env, "USER="+u)30 }31 return append(env, extra...)32}3334// Find returns the first existing executable among candidates (absolute35// paths), then falls back to a PATH lookup of name. Empty when not found.36func Find(name string, candidates ...string) string {37 for _, c := range candidates {38 if st, err := os.Stat(c); err == nil && !st.IsDir() && st.Mode()&0o111 != 0 {39 return c40 }41 }42 for _, dir := range strings.Split(BasePath, ":") {43 p := dir + "/" + name44 if st, err := os.Stat(p); err == nil && !st.IsDir() && st.Mode()&0o111 != 0 {45 return p46 }47 }48 return ""49}5051// capWriter keeps at most max bytes and remembers that it overflowed.52type capWriter struct {53 buf bytes.Buffer54 max int55 Truncated bool56}5758func (w *capWriter) Write(p []byte) (int, error) {59 if room := w.max - w.buf.Len(); room > 0 {60 if len(p) > room {61 w.buf.Write(p[:room])62 w.Truncated = true63 } else {64 w.buf.Write(p)65 }66 } else if len(p) > 0 {67 w.Truncated = true68 }69 return len(p), nil70}7172// ErrTimeout is returned when the program exceeded its deadline.73var ErrTimeout = errors.New("command timed out")7475// Result of a completed program.76type Result struct {77 Stdout []byte78 Stderr []byte79 ExitCode int80 Truncated bool81}8283// Run executes argv with the given timeout and output cap (per stream). The84// child runs in its own process group, which is killed as a whole on timeout.85// A non-zero exit status is not an error: inspect Result.ExitCode. The error86// is non-nil when the program could not be started or timed out.87func Run(ctx context.Context, timeout time.Duration, maxOut int, env []string, argv ...string) (*Result, error) {88 if len(argv) == 0 {89 return nil, errors.New("runcmd: empty argv")90 }91 ctx, cancel := context.WithTimeout(ctx, timeout)92 defer cancel()93 cmd := exec.Command(argv[0], argv[1:]...)94 if env == nil {95 env = Env()96 }97 cmd.Env = env98 cmd.Stdin = nil99 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}100 out, errw := &capWriter{max: maxOut}, &capWriter{max: maxOut}101 cmd.Stdout, cmd.Stderr = out, errw102 if err := cmd.Start(); err != nil {103 return nil, err104 }105 done := make(chan error, 1)106 go func() { done <- cmd.Wait() }()107 var werr error108 timedOut := false109 select {110 case werr = <-done:111 case <-ctx.Done():112 timedOut = true113 syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)114 select {115 case werr = <-done:116 case <-time.After(2 * time.Second):117 // A grandchild holding the pipes open must not block the agent.118 }119 }120 res := &Result{Stdout: out.buf.Bytes(), Stderr: errw.buf.Bytes(), Truncated: out.Truncated || errw.Truncated}121 if timedOut {122 res.ExitCode = -1123 return res, ErrTimeout124 }125 var ee *exec.ExitError126 if errors.As(werr, &ee) {127 res.ExitCode = ee.ExitCode()128 return res, nil129 }130 if werr != nil {131 return res, werr132 }133 return res, nil134}135136// Output is Run returning stdout, failing on a non-zero exit status.137func Output(ctx context.Context, timeout time.Duration, argv ...string) ([]byte, error) {138 res, err := Run(ctx, timeout, 4<<20, nil, argv...)139 if err != nil {140 return nil, err141 }142 if res.ExitCode != 0 {143 return res.Stdout, &ExitError{Code: res.ExitCode, Stderr: string(bytes.TrimSpace(res.Stderr))}144 }145 return res.Stdout, nil146}147148// ExitError is a non-zero exit status.149type ExitError struct {150 Code int151 Stderr string152}153154func (e *ExitError) Error() string {155 s := e.Stderr156 if len(s) > 200 {157 s = s[:200]158 }159 return "exit status " + itoa(e.Code) + ": " + s160}161162func itoa(n int) string {163 if n < 0 {164 return "-" + itoa(-n)165 }166 if n < 10 {167 return string(rune('0' + n))168 }169 return itoa(n/10) + string(rune('0'+n%10))170}171