196 lines
4.5 KiB
Go
196 lines
4.5 KiB
Go
|
|
package conn
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"context"
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"strings"
|
||
|
|
"sync"
|
||
|
|
|
||
|
|
"golang.org/x/crypto/ssh"
|
||
|
|
)
|
||
|
|
|
||
|
|
// DefaultExecLimit caps the captured stdout of Exec (§3.4).
|
||
|
|
const DefaultExecLimit = 1 << 20
|
||
|
|
|
||
|
|
// stderrLimit caps the stderr kept for ExitError.
|
||
|
|
const stderrLimit = 4 << 10
|
||
|
|
|
||
|
|
// ErrOutputLimit: the command printed more than the limit; it was killed
|
||
|
|
// and the output truncated (N-P2-15).
|
||
|
|
var ErrOutputLimit = errors.New("command output exceeds limit")
|
||
|
|
|
||
|
|
// ExitError is a non-zero exit status.
|
||
|
|
type ExitError struct {
|
||
|
|
Code int
|
||
|
|
Stderr string // first 4 KiB
|
||
|
|
}
|
||
|
|
|
||
|
|
func (e *ExitError) Error() string {
|
||
|
|
msg := strings.TrimSpace(e.Stderr)
|
||
|
|
if msg == "" {
|
||
|
|
return fmt.Sprintf("remote command exited with status %d", e.Code)
|
||
|
|
}
|
||
|
|
return fmt.Sprintf("remote command exited with status %d: %s", e.Code, msg)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Quote joins argv into a POSIX shell command line, quoting every argument
|
||
|
|
// that is not made of safe characters only.
|
||
|
|
func Quote(argv []string) string {
|
||
|
|
parts := make([]string, len(argv))
|
||
|
|
for i, a := range argv {
|
||
|
|
parts[i] = quoteArg(a)
|
||
|
|
}
|
||
|
|
return strings.Join(parts, " ")
|
||
|
|
}
|
||
|
|
|
||
|
|
func quoteArg(a string) string {
|
||
|
|
if a == "" {
|
||
|
|
return "''"
|
||
|
|
}
|
||
|
|
safe := true
|
||
|
|
for _, r := range a {
|
||
|
|
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("-_./=:,+@%", r)) {
|
||
|
|
safe = false
|
||
|
|
break
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if safe {
|
||
|
|
return a
|
||
|
|
}
|
||
|
|
return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'"
|
||
|
|
}
|
||
|
|
|
||
|
|
// limitWriter keeps at most limit bytes and calls overflow once when more
|
||
|
|
// arrive.
|
||
|
|
type limitWriter struct {
|
||
|
|
mu sync.Mutex
|
||
|
|
buf bytes.Buffer
|
||
|
|
limit int64
|
||
|
|
over bool
|
||
|
|
overflow func()
|
||
|
|
}
|
||
|
|
|
||
|
|
func (w *limitWriter) Write(p []byte) (int, error) {
|
||
|
|
w.mu.Lock()
|
||
|
|
defer w.mu.Unlock()
|
||
|
|
if w.over {
|
||
|
|
return 0, ErrOutputLimit
|
||
|
|
}
|
||
|
|
room := w.limit - int64(w.buf.Len())
|
||
|
|
if int64(len(p)) <= room {
|
||
|
|
return w.buf.Write(p)
|
||
|
|
}
|
||
|
|
w.buf.Write(p[:room])
|
||
|
|
w.over = true
|
||
|
|
if w.overflow != nil {
|
||
|
|
go w.overflow()
|
||
|
|
}
|
||
|
|
return int(room), ErrOutputLimit
|
||
|
|
}
|
||
|
|
|
||
|
|
func (w *limitWriter) bytes() ([]byte, bool) {
|
||
|
|
w.mu.Lock()
|
||
|
|
defer w.mu.Unlock()
|
||
|
|
return append([]byte(nil), w.buf.Bytes()...), w.over
|
||
|
|
}
|
||
|
|
|
||
|
|
// Exec runs argv on the server (arguments are shell-quoted) and returns its
|
||
|
|
// stdout (at most limit bytes; <= 0 means DefaultExecLimit) and exit code.
|
||
|
|
// A non-zero exit returns *ExitError along with the code. Cancelling ctx
|
||
|
|
// sends SIGKILL and closes the session immediately (N-P1-7); output over
|
||
|
|
// the limit kills the command and returns ErrOutputLimit with the
|
||
|
|
// truncated output. Code is -1 when there is no exit status.
|
||
|
|
func (c *Conn) Exec(ctx context.Context, argv []string, limit int64) ([]byte, int, error) {
|
||
|
|
if len(argv) == 0 {
|
||
|
|
return nil, -1, errors.New("exec: empty command")
|
||
|
|
}
|
||
|
|
if limit <= 0 {
|
||
|
|
limit = DefaultExecLimit
|
||
|
|
}
|
||
|
|
client, err := c.SSH()
|
||
|
|
if err != nil {
|
||
|
|
return nil, -1, err
|
||
|
|
}
|
||
|
|
if err := ctx.Err(); err != nil {
|
||
|
|
return nil, -1, err
|
||
|
|
}
|
||
|
|
|
||
|
|
var (
|
||
|
|
mu sync.Mutex
|
||
|
|
sess *ssh.Session
|
||
|
|
killed bool
|
||
|
|
)
|
||
|
|
kill := func() {
|
||
|
|
mu.Lock()
|
||
|
|
defer mu.Unlock()
|
||
|
|
killed = true
|
||
|
|
if sess != nil {
|
||
|
|
sess.Signal(ssh.SIGKILL)
|
||
|
|
sess.Close()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
stdout := &limitWriter{limit: limit, overflow: kill}
|
||
|
|
stderr := &limitWriter{limit: stderrLimit}
|
||
|
|
type result struct{ err error }
|
||
|
|
done := make(chan result, 1)
|
||
|
|
go func() {
|
||
|
|
s, err := client.NewSession()
|
||
|
|
if err != nil {
|
||
|
|
done <- result{c.MapErr(err)}
|
||
|
|
return
|
||
|
|
}
|
||
|
|
mu.Lock()
|
||
|
|
if killed {
|
||
|
|
mu.Unlock()
|
||
|
|
s.Close()
|
||
|
|
done <- result{context.Canceled}
|
||
|
|
return
|
||
|
|
}
|
||
|
|
sess = s
|
||
|
|
mu.Unlock()
|
||
|
|
defer s.Close()
|
||
|
|
s.Stdout, s.Stderr = stdout, stderr
|
||
|
|
done <- result{s.Run(Quote(argv))}
|
||
|
|
}()
|
||
|
|
|
||
|
|
var r result
|
||
|
|
select {
|
||
|
|
case r = <-done:
|
||
|
|
case <-ctx.Done():
|
||
|
|
kill()
|
||
|
|
return nil, -1, ctx.Err()
|
||
|
|
}
|
||
|
|
out, over := stdout.bytes()
|
||
|
|
if over {
|
||
|
|
return out, -1, fmt.Errorf("%w (%d bytes)", ErrOutputLimit, limit)
|
||
|
|
}
|
||
|
|
if r.err == nil {
|
||
|
|
return out, 0, nil
|
||
|
|
}
|
||
|
|
var ee *ssh.ExitError
|
||
|
|
if errors.As(r.err, &ee) {
|
||
|
|
se, _ := stderr.bytes()
|
||
|
|
return out, ee.ExitStatus(), &ExitError{Code: ee.ExitStatus(), Stderr: string(se)}
|
||
|
|
}
|
||
|
|
return out, -1, c.MapErr(r.err)
|
||
|
|
}
|
||
|
|
|
||
|
|
// ExecSupported reports whether the server runs commands (false for
|
||
|
|
// `ForceCommand internal-sftp`). Probed with `true`; only a definite answer
|
||
|
|
// is cached (a cancelled or lost probe is retried next time).
|
||
|
|
func (c *Conn) ExecSupported(ctx context.Context) bool {
|
||
|
|
c.execMu.Lock()
|
||
|
|
defer c.execMu.Unlock()
|
||
|
|
if c.execKnown {
|
||
|
|
return c.execOK
|
||
|
|
}
|
||
|
|
_, code, err := c.Exec(ctx, []string{"true"}, 64)
|
||
|
|
if ctx.Err() != nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
c.execKnown, c.execOK = true, err == nil && code == 0
|
||
|
|
return c.execOK
|
||
|
|
}
|