// SPDX-License-Identifier: GPL-3.0-or-later package probe import ( "bytes" "context" "errors" "fmt" "io" "os/exec" "strconv" "strings" "time" ) // Limits for one probe run (spec: 90 s, 2 MiB). const ( DefaultTimeout = 90 * time.Second DefaultMaxOutput = 2 * 1024 * 1024 maxStderr = 4 * 1024 ) // Target is a validated ssh destination. type Target struct { User string Addr string Port int } // Options tune a run; zero values mean the defaults. SSHPath "" means look up `ssh` on PATH. type Options struct { SSHPath string Timeout time.Duration MaxOutput int } // ErrTimeout and ErrTooLarge classify failures for callers and tests. var ( ErrTimeout = errors.New("probe timed out") ErrTooLarge = errors.New("probe output exceeds the size limit") ) // SSHArgs returns the ssh arguments: read-only, non-interactive, probe on stdin. func SSHArgs(t Target) []string { dest := t.Addr if t.User != "" { dest = t.User + "@" + t.Addr } return []string{"-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-p", strconv.Itoa(t.Port), dest, "python3", "-"} } // limitBuffer keeps at most max bytes and records that more arrived. type limitBuffer struct { buf bytes.Buffer max int exceeded bool cancel context.CancelFunc } func (l *limitBuffer) Write(p []byte) (int, error) { room := l.max - l.buf.Len() if len(p) > room { l.exceeded = true if room > 0 { l.buf.Write(p[:room]) } if l.cancel != nil { l.cancel() } return len(p), nil } return l.buf.Write(p) } // Run executes the probe over ssh and returns the validated profile plus its raw JSON line. func Run(ctx context.Context, t Target, script []byte, opt Options) (*Profile, []byte, error) { timeout, maxOut := opt.Timeout, opt.MaxOutput if timeout <= 0 { timeout = DefaultTimeout } if maxOut <= 0 { maxOut = DefaultMaxOutput } sshPath := opt.SSHPath if sshPath == "" { p, err := exec.LookPath("ssh") if err != nil { return nil, nil, errors.New("ssh not found on PATH") } sshPath = p } runCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() // A separate cancel for the size limit so a flood is stopped at once. sizeCtx, sizeCancel := context.WithCancel(runCtx) defer sizeCancel() cmd := exec.CommandContext(sizeCtx, sshPath, SSHArgs(t)...) cmd.Stdin = bytes.NewReader(script) out := &limitBuffer{max: maxOut, cancel: sizeCancel} errBuf := &limitBuffer{max: maxStderr} cmd.Stdout = out cmd.Stderr = errBuf cmd.WaitDelay = 2 * time.Second // a killed ssh must not keep us waiting on inherited pipes runErr := cmd.Run() switch { case out.exceeded: return nil, nil, fmt.Errorf("%w (%d bytes)", ErrTooLarge, maxOut) case errors.Is(runCtx.Err(), context.DeadlineExceeded): return nil, nil, fmt.Errorf("%w after %s", ErrTimeout, timeout) case ctx.Err() != nil: return nil, nil, ctx.Err() case runErr != nil: msg := strings.TrimSpace(errBuf.buf.String()) if msg == "" { msg = runErr.Error() } return nil, nil, fmt.Errorf("ssh failed: %s", firstLines(msg, 5)) } line := lastJSONLine(out.buf.Bytes()) if line == nil { return nil, nil, errors.New("probe printed no JSON") } p, err := Parse(line) if err != nil { return nil, nil, err } return p, line, nil } func lastJSONLine(b []byte) []byte { lines := bytes.Split(b, []byte("\n")) for i := len(lines) - 1; i >= 0; i-- { l := bytes.TrimSpace(lines[i]) if len(l) > 0 && l[0] == '{' { return l } } return nil } func firstLines(s string, n int) string { lines := strings.Split(s, "\n") if len(lines) > n { lines = lines[:n] } return strings.Join(lines, "; ") } var _ io.Writer = (*limitBuffer)(nil)