Debian Codegraph @

interp/handler.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package interp
5
6 import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "io"
12 "io/fs"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "runtime"
17 "strings"
18 "time"
19
20 "mvdan.cc/sh/v3/expand"
21 "mvdan.cc/sh/v3/syntax"
22 )
23
24 // HandlerCtx returns the [HandlerContext] value stored in ctx,
25 // which is used when calling handler functions.
26 // It panics if ctx has no HandlerContext stored.
27 func HandlerCtx(ctx context.Context) HandlerContext {
28 hc, ok := ctx.Value(handlerCtxKey{}).(HandlerContext)
29 if !ok {
30 panic("interp.HandlerCtx: no HandlerContext in ctx")
31 }
32 return hc
33 }
34
35 type handlerCtxKey struct{}
36
37 type handlerKind int
38
39 const (
40 _ handlerKind = iota
41 handlerKindExec // [ExecHandlerFunc]
42 handlerKindCall // [CallHandlerFunc]
43 handlerKindOpen // [OpenHandlerFunc]
44 handlerKindReadDir // [ReadDirHandlerFunc2]
45 handlerKindStat // [StatHandlerFunc]
46 handlerKindAccess // [AccessHandlerFunc]
47 )
48
49 // HandlerContext is the data passed to all the handler functions via [context.WithValue].
50 // It contains some of the current state of the [Runner].
51 type HandlerContext struct {
52 runner *Runner // for internal use only, e.g. [HandlerContext.Builtin]
53
54 // kind records which type of handler this context was built for.
55 kind handlerKind
56
57 // Env is a read-only version of the interpreter's environment,
58 // including environment variables, global variables, and local function
59 // variables.
60 Env expand.Environ
61
62 // Dir is the interpreter's current directory.
63 Dir string
64
65 // Pos is the source position which relates to the operation,
66 // such as a [syntax.CallExpr] when calling an [ExecHandlerFunc].
67 // It may be invalid if the operation has no relevant position information.
68 Pos syntax.Pos
69
70 // TODO(v4): use an os.File for stdin below directly.
71
72 // Stdin is the interpreter's current standard input reader.
73 // It is always an [*os.File], except on js/wasm, where it may be
74 // any reader; the type here remains an [io.Reader]
75 // due to backwards compatibility.
76 Stdin io.Reader
77 // Stdout is the interpreter's current standard output writer.
78 Stdout io.Writer
79 // Stderr is the interpreter's current standard error writer.
80 Stderr io.Writer
81
82 // LastExitStatus is the value that "$?" would hold when the handler is called.
83 // A [CallHandlerFunc] or [ExecHandlerFunc] runs as part of its own command,
84 // so this refers to the command before it.
85 // At the start of a trap callback, it is the status of the command which triggered the trap.
86 LastExitStatus int
87 }
88
89 // CallHandlerFunc is a handler which runs on every [syntax.CallExpr].
90 // It is called once variable assignments and field expansion have occurred.
91 // The context includes a [HandlerContext] value.
92 //
93 // The call's arguments are replaced by what the handler returns,
94 // and then the call is executed by the Runner as usual.
95 // The args slice is never empty.
96 // At this time, returning an empty slice without an error is not supported.
97 //
98 // This handler is similar to [ExecHandlerFunc], but has two major differences:
99 //
100 // First, it runs for all simple commands, including function calls and builtins.
101 //
102 // Second, it is not expected to execute the simple command, but instead to
103 // allow running custom code which allows replacing the argument list.
104 // Shell builtins touch on many internals of the Runner, after all.
105 //
106 // Returning a non-nil error will halt the [Runner] and will be returned via the API.
107 type CallHandlerFunc func(ctx context.Context, args []string) ([]string, error)
108
109 // TODO: consistently treat handler errors as non-fatal by default,
110 // but have an interface or API to specify fatal errors which should make
111 // the shell exit with a particular status code.
112
113 // ExecHandlerFunc is a handler which executes simple commands.
114 // It is called for all [syntax.CallExpr] nodes
115 // where the first argument is neither a declared function nor a builtin.
116 // The args slice is never empty.
117 // The context includes a [HandlerContext] value.
118 //
119 // Returning a nil error means a zero exit status.
120 // Other exit statuses can be set by returning or wrapping a [NewExitStatus] error,
121 // and such an error is returned via the API if it is the last statement executed.
122 // Any other error will halt the [Runner] and will be returned via the API.
123 type ExecHandlerFunc func(ctx context.Context, args []string) error
124
125 // DefaultExecHandler returns the [ExecHandlerFunc] used by default.
126 // It finds binaries in PATH and executes them.
127 // When context is cancelled, an interrupt signal is sent to running processes.
128 // killTimeout is a duration to wait before sending the kill signal.
129 // A negative value means that a kill signal will be sent immediately.
130 //
131 // On Windows, the kill signal is always sent immediately,
132 // because Go doesn't currently support sending Interrupt on Windows.
133 // [Runner] defaults to a killTimeout of 2 seconds.
134 //
135 // On Unix, a file which fails to execute with ENOEXEC, such as a script
136 // without a shebang line, is run as a shell script with a new [Runner]
137 // using default options and handlers, like other shells do.
138 //
139 // TODO: perhaps intercept ENOEXEC scripts as well as shell shebangs
140 // such as "#!/bin/sh" so that they reuse the runner's configured handlers.
141 func DefaultExecHandler(killTimeout time.Duration) ExecHandlerFunc {
142 return func(ctx context.Context, args []string) error {
143 hc := HandlerCtx(ctx)
144 path, err := LookPathDir(hc.Dir, hc.Env, args[0])
145 if err != nil {
146 fmt.Fprintln(hc.Stderr, err)
147 return ExitStatus(127)
148 }
149 newCmd := func() *exec.Cmd {
150 cmd := exec.CommandContext(ctx, path)
151 cmd.Args = args
152 cmd.Env = execEnv(hc.Env)
153 cmd.Dir = hc.Dir
154 cmd.Stdin = hc.Stdin
155 cmd.Stdout = hc.Stdout
156 cmd.Stderr = hc.Stderr
157 if killTimeout > 0 && runtime.GOOS != "windows" {
158 // On cancellation, send an interrupt signal first, and let
159 // WaitDelay escalate to a kill signal if the process does not
160 // exit in time. Otherwise, keep the default of killing right away.
161 cmd.Cancel = func() error { return cmd.Process.Signal(os.Interrupt) }
162 cmd.WaitDelay = killTimeout
163 }
164 return cmd
165 }
166 cmd := newCmd()
167 err = cmd.Start()
168 // On Unix, a concurrently forked process may briefly hold a write
169 // file descriptor for the file inherited before its exec, making
170 // our exec fail with ETXTBSY; see https://go.dev/issue/22315.
171 // The window is short-lived, so retry with backoff. A failed Start
172 // closes the command's pipes, so build a fresh one for each attempt.
173 for delay := time.Millisecond; isETXTBSY(err) && delay < 300*time.Millisecond; delay *= 2 {
174 time.Sleep(delay)
175 cmd = newCmd()
176 err = cmd.Start()
177 }
178 if isENOEXEC(err) {
179 // Like other shells, run a file which the kernel refuses to
180 // execute with ENOEXEC, such as a script without a shebang line,
181 // as a shell script with a new copy of the shell.
182 return runScriptENOEXEC(ctx, hc, killTimeout, path, args)
183 }
184 if err == nil {
185 err = cmd.Wait()
186 }
187
188 switch err := err.(type) {
189 case *exec.ExitError:
190 // Windows and Plan9 do not have support for [syscall.WaitStatus]
191 // with methods like Signaled and Signal, so for those, [waitStatus] is a no-op.
192 // Note: [waitStatus] is an alias [syscall.WaitStatus]
193 if status, ok := err.Sys().(waitStatus); ok && status.Signaled() {
194 if ctx.Err() != nil {
195 return ctx.Err()
196 }
197 return ExitStatus(128 + status.Signal())
198 }
199 return ExitStatus(err.ExitCode())
200 case *exec.Error:
201 // did not start
202 fmt.Fprintf(hc.Stderr, "%v\n", err)
203 return ExitStatus(127)
204 default:
205 // The command exited with success, but WaitDelay elapsed with its
206 // I/O pipes still open, e.g. due to an orphaned subprocess.
207 if errors.Is(err, exec.ErrWaitDelay) {
208 return nil
209 }
210 return err
211 }
212 }
213 }
214
215 // runScriptENOEXEC runs a file as a shell script with a new shell,
216 // as POSIX requires when the kernel fails to execute it with ENOEXEC.
217 // The new shell does not inherit functions or unexported variables.
218 func runScriptENOEXEC(ctx context.Context, hc HandlerContext, killTimeout time.Duration, path string, args []string) error {
219 b, err := os.ReadFile(path)
220 if err != nil {
221 fmt.Fprintln(hc.Stderr, err)
222 return ExitStatus(126)
223 }
224 // Like Bash, refuse to run the file as a script
225 // if a null byte appears before the first newline.
226 line, _, _ := bytes.Cut(b, []byte("\n"))
227 if bytes.IndexByte(line, 0) >= 0 {
228 fmt.Fprintf(hc.Stderr, "%s: cannot execute binary file\n", args[0])
229 return ExitStatus(126)
230 }
231 file, err := syntax.NewParser().Parse(bytes.NewReader(b), args[0])
232 if err != nil {
233 fmt.Fprintln(hc.Stderr, err)
234 return ExitStatus(2) // like Bash with a syntax error
235 }
236 r, err := New(
237 Dir(hc.Dir),
238 Env(expand.ListEnviron(execEnv(hc.Env)...)),
239 StdIO(hc.Stdin, hc.Stdout, hc.Stderr),
240 ExecHandler(DefaultExecHandler(killTimeout)),
241 )
242 if err != nil {
243 return err
244 }
245 r.Params = args[1:]
246 return r.Run(ctx, file)
247 }
248
249 func checkStat(dir, file string, checkExec bool) (string, error) {
250 if !filepath.IsAbs(file) {
251 file = filepath.Join(dir, file)
252 }
253 info, err := os.Stat(file)
254 if err != nil {
255 return "", err
256 }
257 m := info.Mode()
258 if m.IsDir() {
259 return "", fmt.Errorf("is a directory")
260 }
261 if checkExec && runtime.GOOS != "windows" && m&0o111 == 0 {
262 return "", fmt.Errorf("permission denied")
263 }
264 return file, nil
265 }
266
267 func winHasExt(file string) bool {
268 i := strings.LastIndex(file, ".")
269 if i < 0 {
270 return false
271 }
272 return strings.LastIndexAny(file, `:\/`) < i
273 }
274
275 // findExecutable returns the path to an existing executable file.
276 func findExecutable(dir, file string, exts []string) (string, error) {
277 if len(exts) == 0 {
278 // non-windows
279 return checkStat(dir, file, true)
280 }
281 if winHasExt(file) {
282 if file, err := checkStat(dir, file, true); err == nil {
283 return file, nil
284 }
285 }
286 for _, e := range exts {
287 f := file + e
288 if f, err := checkStat(dir, f, true); err == nil {
289 return f, nil
290 }
291 }
292 return "", fmt.Errorf("not found")
293 }
294
295 // findFile returns the path to an existing file.
296 func findFile(dir, file string, _ []string) (string, error) {
297 return checkStat(dir, file, false)
298 }
299
300 // LookPath is deprecated; see [LookPathDir].
301 func LookPath(env expand.Environ, file string) (string, error) {
302 return LookPathDir(env.Get("PWD").String(), env, file)
303 }
304
305 // LookPathDir is similar to [os/exec.LookPath], with the difference that it uses the
306 // provided environment. env is used to fetch relevant environment variables
307 // such as PWD and PATH.
308 //
309 // If no error is returned, the returned path must be valid.
310 func LookPathDir(cwd string, env expand.Environ, file string) (string, error) {
311 return lookPathDir(cwd, env, file, findExecutable)
312 }
313
314 // findAny defines a function to pass to [lookPathDir].
315 type findAny = func(dir string, file string, exts []string) (string, error)
316
317 func lookPathDir(cwd string, env expand.Environ, file string, find findAny) (string, error) {
318 if find == nil {
319 panic("no find function found")
320 }
321
322 pathList := filepath.SplitList(env.Get("PATH").String())
323 if len(pathList) == 0 {
324 pathList = []string{""}
325 }
326 chars := `/`
327 if runtime.GOOS == "windows" {
328 chars = `:\/`
329 }
330 exts := pathExts(env)
331 if strings.ContainsAny(file, chars) {
332 return find(cwd, file, exts)
333 }
334 for _, elem := range pathList {
335 var path string
336 switch elem {
337 case "", ".":
338 // otherwise "foo" won't be "./foo"
339 path = "." + string(filepath.Separator) + file
340 default:
341 path = filepath.Join(elem, file)
342 }
343 if f, err := find(cwd, path, exts); err == nil {
344 return f, nil
345 }
346 }
347 return "", fmt.Errorf("%q: executable file not found in $PATH", file)
348 }
349
350 // scriptFromPathDir is similar to [LookPathDir], with the difference that it looks
351 // for both executable and non-executable files.
352 func scriptFromPathDir(cwd string, env expand.Environ, file string) (string, error) {
353 return lookPathDir(cwd, env, file, findFile)
354 }
355
356 func pathExts(env expand.Environ) []string {
357 if runtime.GOOS != "windows" {
358 return nil
359 }
360 pathext := env.Get("PATHEXT").String()
361 if pathext == "" {
362 return []string{".com", ".exe", ".bat", ".cmd"}
363 }
364 var exts []string
365 for e := range strings.SplitSeq(strings.ToLower(pathext), `;`) {
366 if e == "" {
367 continue
368 }
369 if e[0] != '.' {
370 e = "." + e
371 }
372 exts = append(exts, e)
373 }
374 return exts
375 }
376
377 // OpenHandlerFunc is a handler which opens files.
378 // It is called for all files that are opened directly by the shell,
379 // such as in redirects, except for named pipes created by process substitutions.
380 // The context includes a [HandlerContext] value.
381 // Files opened by executed programs are not included.
382 //
383 // The path parameter may be relative to the current directory,
384 // which can be fetched via [HandlerCtx].
385 //
386 // Use a return error of type [*os.PathError] to have the error printed to
387 // stderr and the exit status set to 1.
388 // Any other error will halt the [Runner] and will be returned via the API.
389 //
390 // Note that implementations which do not return [os.File] will cause
391 // extra files and goroutines for input redirections; see [StdIO].
392 type OpenHandlerFunc func(ctx context.Context, path string, flag int, perm os.FileMode) (io.ReadWriteCloser, error)
393
394 // TODO: paths passed to [OpenHandlerFunc] should be cleaned.
395
396 // DefaultOpenHandler returns the [OpenHandlerFunc] used by default.
397 // It uses [os.OpenFile] to open files.
398 //
399 // For the sake of portability, /dev/null opens NUL on Windows.
400 func DefaultOpenHandler() OpenHandlerFunc {
401 return func(ctx context.Context, path string, flag int, perm os.FileMode) (io.ReadWriteCloser, error) {
402 mc := HandlerCtx(ctx)
403 if runtime.GOOS == "windows" && path == "/dev/null" {
404 path = "NUL"
405 // Note that even though https://go.dev/issue/71752 was resolved for Windows,
406 // the workaround here seems to still be required for Wine as of 10.14.
407 // TODO(mvdan): Why? Is this Wine's fault?
408 flag &^= os.O_TRUNC
409 } else if path != "" && !filepath.IsAbs(path) {
410 path = filepath.Join(mc.Dir, path)
411 }
412 return os.OpenFile(path, flag, perm)
413 }
414 }
415
416 // ReadDirHandlerFunc is a handler which reads directories. It is called during
417 // shell globbing, if enabled.
418 //
419 // Deprecated: use [ReadDirHandlerFunc2], which uses [fs.DirEntry].
420 type ReadDirHandlerFunc func(ctx context.Context, path string) ([]fs.FileInfo, error)
421
422 // ReadDirHandlerFunc2 is a handler which reads directories. It is called during
423 // shell globbing, if enabled.
424 // The context includes a [HandlerContext] value.
425 type ReadDirHandlerFunc2 func(ctx context.Context, path string) ([]fs.DirEntry, error)
426
427 // DefaultReadDirHandler returns the [ReadDirHandlerFunc] used by default.
428 // It uses [os.ReadDir].
429 //
430 // Deprecated: use [DefaultReadDirHandler2], which uses [fs.DirEntry].
431 func DefaultReadDirHandler() ReadDirHandlerFunc {
432 return func(ctx context.Context, path string) ([]fs.FileInfo, error) {
433 entries, err := os.ReadDir(path)
434 if err != nil {
435 return nil, err
436 }
437 infos := make([]fs.FileInfo, 0, len(entries))
438 for _, entry := range entries {
439 info, err := entry.Info()
440 if err != nil {
441 return nil, err
442 }
443 infos = append(infos, info)
444 }
445 return infos, nil
446 }
447 }
448
449 // DefaultReadDirHandler2 returns the [ReadDirHandlerFunc2] used by default.
450 // It uses [os.ReadDir].
451 func DefaultReadDirHandler2() ReadDirHandlerFunc2 {
452 return func(ctx context.Context, path string) ([]fs.DirEntry, error) {
453 return os.ReadDir(path)
454 }
455 }
456
457 // StatHandlerFunc is a handler which gets a file's information.
458 // The context includes a [HandlerContext] value.
459 type StatHandlerFunc func(ctx context.Context, name string, followSymlinks bool) (fs.FileInfo, error)
460
461 // DefaultStatHandler returns the [StatHandlerFunc] used by default.
462 // It makes use of [os.Stat] and [os.Lstat], depending on followSymlinks.
463 func DefaultStatHandler() StatHandlerFunc {
464 return func(ctx context.Context, path string, followSymlinks bool) (fs.FileInfo, error) {
465 if !followSymlinks {
466 return os.Lstat(path)
467 } else {
468 return os.Stat(path)
469 }
470 }
471 }
472
473 // AccessMode is a bitmask of file access checks, used by [AccessHandlerFunc].
474 type AccessMode uint32
475
476 // The values match access(2)'s R_OK, W_OK, and X_OK.
477 const (
478 AccessRead AccessMode = 0b100
479 AccessWrite AccessMode = 0b010
480 AccessExec AccessMode = 0b001
481 )
482
483 // TODO(v4): fold AccessHandlerFunc into StatHandlerFunc.
484
485 // AccessHandlerFunc is a handler which checks whether the current user can
486 // access a file. It is called by the unary test operators -r, -w, and -x,
487 // and by builtins such as cd. The path is always absolute.
488 // A nil error means access is allowed.
489 // The context includes a [HandlerContext] value.
490 type AccessHandlerFunc func(ctx context.Context, path string, mode AccessMode) error
491
492 // DefaultAccessHandler returns the [AccessHandlerFunc] used by default.
493 // On Unix it uses access(2), which consults the real filesystem and the
494 // current user's role. On other platforms, which lack access(2), it
495 // approximates the check via the stat handler and the file's permission bits.
496 func DefaultAccessHandler() AccessHandlerFunc {
497 return defaultAccess
498 }