648 lines
18 KiB
Go
648 lines
18 KiB
Go
package guest
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"encoding/json"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/pkg/sftp"
|
|
"golang.org/x/crypto/ssh"
|
|
)
|
|
|
|
const MaxTransferBytes int64 = 64 << 20
|
|
|
|
type SSH struct {
|
|
root string
|
|
}
|
|
|
|
type ExecResult struct {
|
|
ExitCode int `json:"exit_code"`
|
|
TimedOut bool `json:"timed_out"`
|
|
Output string `json:"output"`
|
|
Truncated bool `json:"truncated"`
|
|
LogID string `json:"log_id"`
|
|
}
|
|
|
|
type HostKey struct {
|
|
Fingerprint string `json:"fingerprint"`
|
|
Authorized string `json:"host_key"`
|
|
}
|
|
|
|
type transferResult struct {
|
|
Bytes int64 `json:"bytes"`
|
|
}
|
|
|
|
func NewSSH(root string) *SSH { return &SSH{root: root} }
|
|
|
|
func (s *SSH) PublicKey() (string, error) {
|
|
signer, err := s.signer()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(ssh.MarshalAuthorizedKey(signer.PublicKey())), nil
|
|
}
|
|
|
|
func (s *SSH) Probe(ctx context.Context, address string) (HostKey, error) {
|
|
conn, err := s.dial(ctx, address)
|
|
if err != nil {
|
|
return HostKey{}, err
|
|
}
|
|
defer conn.Close()
|
|
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
|
var offered ssh.PublicKey
|
|
config := &ssh.ClientConfig{
|
|
User: "reims-probe",
|
|
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
|
|
offered = key
|
|
return nil
|
|
},
|
|
Timeout: 5 * time.Second,
|
|
}
|
|
_, _, _, handshakeErr := ssh.NewClientConn(conn, address, config)
|
|
if offered == nil {
|
|
if handshakeErr == nil {
|
|
return HostKey{}, errors.New("SSH server did not provide a host key")
|
|
}
|
|
return HostKey{}, fmt.Errorf("SSH handshake: %w", handshakeErr)
|
|
}
|
|
return hostKeyInfo(offered), nil
|
|
}
|
|
|
|
func (s *SSH) TrustHostKey(vm, address, fingerprint string) error {
|
|
return s.TrustHostKeyContext(context.Background(), vm, address, fingerprint)
|
|
}
|
|
|
|
func (s *SSH) TrustHostKeyContext(ctx context.Context, vm, address, fingerprint string) error {
|
|
observed, err := s.Probe(ctx, address)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if observed.Fingerprint != fingerprint {
|
|
return fmt.Errorf("SSH host key changed during confirmation: expected %s, observed %s", fingerprint, observed.Fingerprint)
|
|
}
|
|
pins, err := s.readPins()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pins[vm] = fingerprint
|
|
return s.writePins(pins)
|
|
}
|
|
|
|
func (s *SSH) WaitReady(ctx context.Context, vm, address, username string, timeout time.Duration) (map[string]any, error) {
|
|
if timeout <= 0 || timeout > 30*time.Second {
|
|
return nil, errors.New("SSH wait timeout must be between 1 and 30000 milliseconds")
|
|
}
|
|
deadline := time.NewTimer(timeout)
|
|
defer deadline.Stop()
|
|
tick := time.NewTicker(500 * time.Millisecond)
|
|
defer tick.Stop()
|
|
var lastErr error
|
|
for {
|
|
key, err := s.Probe(ctx, address)
|
|
if err == nil {
|
|
pins, pinErr := s.readPins()
|
|
if pinErr != nil {
|
|
return nil, pinErr
|
|
}
|
|
if pins[vm] == "" {
|
|
return map[string]any{
|
|
"ready": false, "trust_required": true, "fingerprint": key.Fingerprint,
|
|
"host_key": key.Authorized,
|
|
"message": "Review the SSH host fingerprint and host key, then call guest_trust_host. Add plugin_public_key to the guest's ~/.ssh/authorized_keys before running commands.",
|
|
}, nil
|
|
}
|
|
if pins[vm] != key.Fingerprint {
|
|
return nil, fmt.Errorf("SSH host fingerprint changed for %s: pinned %s, observed %s", vm, pins[vm], key.Fingerprint)
|
|
}
|
|
client, dialErr := s.connect(ctx, vm, address, username)
|
|
if dialErr == nil {
|
|
_ = client.Close()
|
|
return map[string]any{"ready": true, "fingerprint": key.Fingerprint}, nil
|
|
}
|
|
lastErr = dialErr
|
|
} else {
|
|
lastErr = err
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
case <-deadline.C:
|
|
if lastErr != nil {
|
|
return map[string]any{"ready": false, "message": lastErr.Error()}, nil
|
|
}
|
|
return map[string]any{"ready": false}, nil
|
|
case <-tick.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *SSH) Exec(ctx context.Context, vm, address, username, command, cwd string, env map[string]string, timeout time.Duration) (ExecResult, error) {
|
|
if strings.TrimSpace(command) == "" {
|
|
return ExecResult{}, errors.New("command is required")
|
|
}
|
|
if timeout <= 0 || timeout > 30*time.Minute {
|
|
return ExecResult{}, errors.New("command timeout must be between 1 millisecond and 30 minutes")
|
|
}
|
|
client, err := s.connect(ctx, vm, address, username)
|
|
if err != nil {
|
|
return ExecResult{}, err
|
|
}
|
|
defer client.Close()
|
|
session, err := client.NewSession()
|
|
if err != nil {
|
|
return ExecResult{}, err
|
|
}
|
|
defer session.Close()
|
|
logs := filepath.Join(s.root, "logs")
|
|
if err := os.MkdirAll(logs, 0o700); err != nil {
|
|
return ExecResult{}, err
|
|
}
|
|
logFile, err := os.CreateTemp(logs, "guest-exec-*.log")
|
|
if err != nil {
|
|
return ExecResult{}, err
|
|
}
|
|
logID := filepath.Base(logFile.Name())
|
|
writer := &outputWriter{file: logFile}
|
|
session.Stdout = writer
|
|
session.Stderr = writer
|
|
remote := shellCommand(command, cwd, env)
|
|
if err := session.Start(remote); err != nil {
|
|
_ = logFile.Close()
|
|
return ExecResult{}, err
|
|
}
|
|
done := make(chan error, 1)
|
|
go func() { done <- session.Wait() }()
|
|
timer := time.NewTimer(timeout)
|
|
defer timer.Stop()
|
|
timedOut := false
|
|
select {
|
|
case err = <-done:
|
|
case <-ctx.Done():
|
|
timedOut = true
|
|
err = stopRemote(session, client, done)
|
|
case <-timer.C:
|
|
timedOut = true
|
|
err = stopRemote(session, client, done)
|
|
}
|
|
closeErr := logFile.Close()
|
|
if closeErr != nil {
|
|
return ExecResult{}, closeErr
|
|
}
|
|
if err != nil && !timedOut {
|
|
var exitErr *ssh.ExitError
|
|
if !errors.As(err, &exitErr) {
|
|
return ExecResult{}, err
|
|
}
|
|
}
|
|
exitCode := 0
|
|
if err != nil {
|
|
var exitErr *ssh.ExitError
|
|
if errors.As(err, &exitErr) {
|
|
exitCode = exitErr.ExitStatus()
|
|
} else {
|
|
exitCode = -1
|
|
}
|
|
}
|
|
return ExecResult{ExitCode: exitCode, TimedOut: timedOut, Output: writer.result(), Truncated: writer.truncated(), LogID: logID}, nil
|
|
}
|
|
|
|
func stopRemote(session *ssh.Session, client *ssh.Client, done <-chan error) error {
|
|
_ = session.Signal(ssh.SIGTERM)
|
|
timer := time.NewTimer(5 * time.Second)
|
|
defer timer.Stop()
|
|
select {
|
|
case err := <-done:
|
|
return err
|
|
case <-timer.C:
|
|
_ = session.Signal(ssh.SIGKILL)
|
|
_ = client.Close()
|
|
return <-done
|
|
}
|
|
}
|
|
|
|
func (s *SSH) ReadLog(logID string, offset int64, limit int) (map[string]any, error) {
|
|
if logID == "" || filepath.Base(logID) != logID || strings.ContainsAny(logID, `/\\`) || offset < 0 {
|
|
return nil, errors.New("invalid guest log id or offset")
|
|
}
|
|
if limit <= 0 {
|
|
limit = 8192
|
|
}
|
|
if limit > 64<<10 {
|
|
return nil, errors.New("guest log page cannot exceed 65536 bytes")
|
|
}
|
|
file, err := os.Open(filepath.Join(s.root, "logs", logID))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
info, err := file.Stat()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if offset > info.Size() {
|
|
return nil, errors.New("guest log offset is past end of file")
|
|
}
|
|
if _, err := file.Seek(offset, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
page, err := io.ReadAll(io.LimitReader(file, int64(limit)))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
next := offset + int64(len(page))
|
|
return map[string]any{"log_id": logID, "offset": offset, "next_offset": next, "eof": next >= info.Size(), "text": string(page)}, nil
|
|
}
|
|
|
|
func (s *SSH) Put(ctx context.Context, vm, address, username, localPath, remotePath string) (transferResult, error) {
|
|
info, err := os.Stat(localPath)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
if !info.Mode().IsRegular() || info.Size() > MaxTransferBytes {
|
|
return transferResult{}, fmt.Errorf("upload must be a regular file no larger than %d bytes", MaxTransferBytes)
|
|
}
|
|
client, err := s.connect(ctx, vm, address, username)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
defer client.Close()
|
|
transfer, err := sftp.NewClient(client)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
defer transfer.Close()
|
|
home, err := transfer.Getwd()
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
target, err := confinedPath(home, remotePath)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
if err := mkdirGuestPath(transfer, home, path.Dir(target)); err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
parent, err := transfer.RealPath(path.Dir(target))
|
|
if err != nil || !withinGuestHome(home, parent) {
|
|
return transferResult{}, errors.New("guest upload directory resolves outside the guest home directory")
|
|
}
|
|
target = path.Join(parent, path.Base(target))
|
|
tempPath := target + ".reims-upload-" + fmt.Sprint(time.Now().UnixNano())
|
|
remote, err := transfer.Create(tempPath)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
local, err := os.Open(localPath)
|
|
if err != nil {
|
|
_ = remote.Close()
|
|
_ = transfer.Remove(tempPath)
|
|
return transferResult{}, err
|
|
}
|
|
count, copyErr := io.Copy(remote, io.LimitReader(local, MaxTransferBytes+1))
|
|
localErr := local.Close()
|
|
remoteErr := remote.Close()
|
|
if copyErr != nil || localErr != nil || remoteErr != nil {
|
|
_ = transfer.Remove(tempPath)
|
|
return transferResult{}, errors.Join(copyErr, localErr, remoteErr)
|
|
}
|
|
if count > MaxTransferBytes {
|
|
_ = transfer.Remove(tempPath)
|
|
return transferResult{}, fmt.Errorf("upload exceeds %d bytes", MaxTransferBytes)
|
|
}
|
|
if err := transfer.Rename(tempPath, target); err != nil {
|
|
_ = transfer.Remove(tempPath)
|
|
return transferResult{}, err
|
|
}
|
|
return transferResult{Bytes: count}, nil
|
|
}
|
|
|
|
func (s *SSH) Get(ctx context.Context, vm, address, username, remotePath, localPath string) (transferResult, error) {
|
|
client, err := s.connect(ctx, vm, address, username)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
defer client.Close()
|
|
transfer, err := sftp.NewClient(client)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
defer transfer.Close()
|
|
home, err := transfer.Getwd()
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
target, err := confinedPath(home, remotePath)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
resolved, err := transfer.RealPath(target)
|
|
if err != nil || !withinGuestHome(home, resolved) {
|
|
return transferResult{}, errors.New("guest download path resolves outside the guest home directory")
|
|
}
|
|
remote, err := transfer.Open(resolved)
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
defer remote.Close()
|
|
info, err := remote.Stat()
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
if !info.Mode().IsRegular() || info.Size() > MaxTransferBytes {
|
|
return transferResult{}, fmt.Errorf("download must be a regular file no larger than %d bytes", MaxTransferBytes)
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(localPath), 0o700); err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
local, err := os.CreateTemp(filepath.Dir(localPath), ".reims-download-*")
|
|
if err != nil {
|
|
return transferResult{}, err
|
|
}
|
|
tempPath := local.Name()
|
|
count, copyErr := io.Copy(local, io.LimitReader(remote, MaxTransferBytes+1))
|
|
closeErr := local.Close()
|
|
if copyErr != nil || closeErr != nil || count > MaxTransferBytes {
|
|
_ = os.Remove(tempPath)
|
|
if count > MaxTransferBytes {
|
|
return transferResult{}, fmt.Errorf("download exceeds %d bytes", MaxTransferBytes)
|
|
}
|
|
return transferResult{}, errors.Join(copyErr, closeErr)
|
|
}
|
|
if err := os.Rename(tempPath, localPath); err != nil {
|
|
_ = os.Remove(tempPath)
|
|
return transferResult{}, err
|
|
}
|
|
return transferResult{Bytes: count}, nil
|
|
}
|
|
|
|
func (s *SSH) connect(ctx context.Context, vm, address, username string) (*ssh.Client, error) {
|
|
if strings.TrimSpace(username) == "" {
|
|
return nil, errors.New("SSH username is not configured for this VM")
|
|
}
|
|
pins, err := s.readPins()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
fingerprint := pins[vm]
|
|
if fingerprint == "" {
|
|
return nil, fmt.Errorf("SSH host key is not trusted for %s; call guest_wait_ready and review the fingerprint", vm)
|
|
}
|
|
signer, err := s.signer()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
conn, err := s.dial(ctx, address)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
config := &ssh.ClientConfig{
|
|
User: username,
|
|
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
|
|
HostKeyCallback: func(_ string, _ net.Addr, offered ssh.PublicKey) error {
|
|
got := ssh.FingerprintSHA256(offered)
|
|
if got != fingerprint {
|
|
return fmt.Errorf("SSH host fingerprint changed for %s: pinned %s, observed %s", vm, fingerprint, got)
|
|
}
|
|
return nil
|
|
},
|
|
Timeout: 10 * time.Second,
|
|
}
|
|
clientConn, chans, reqs, err := ssh.NewClientConn(conn, address, config)
|
|
if err != nil {
|
|
_ = conn.Close()
|
|
return nil, err
|
|
}
|
|
_ = conn.SetDeadline(time.Time{})
|
|
return ssh.NewClient(clientConn, chans, reqs), nil
|
|
}
|
|
|
|
func (s *SSH) dial(ctx context.Context, address string) (net.Conn, error) {
|
|
conn, err := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", address)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("connect to guest SSH at %s: %w", address, err)
|
|
}
|
|
deadline := time.Now().Add(10 * time.Second)
|
|
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
|
|
deadline = ctxDeadline
|
|
}
|
|
_ = conn.SetDeadline(deadline)
|
|
return conn, nil
|
|
}
|
|
|
|
func (s *SSH) signer() (ssh.Signer, error) {
|
|
keyPath := filepath.Join(s.root, "keys", "id_ed25519")
|
|
if data, err := os.ReadFile(keyPath); err == nil {
|
|
return ssh.ParsePrivateKey(data)
|
|
} else if !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(keyPath), 0o700); err != nil {
|
|
return nil, err
|
|
}
|
|
_, private, err := ed25519.GenerateKey(rand.Reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
block, err := ssh.MarshalPrivateKey(private, "reims.agent")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
encoded := pem.EncodeToMemory(block)
|
|
if err := os.WriteFile(keyPath, encoded, 0o600); err != nil {
|
|
return nil, err
|
|
}
|
|
return ssh.ParsePrivateKey(encoded)
|
|
}
|
|
|
|
func hostKeyInfo(key ssh.PublicKey) HostKey {
|
|
return HostKey{Fingerprint: ssh.FingerprintSHA256(key), Authorized: string(ssh.MarshalAuthorizedKey(key))}
|
|
}
|
|
|
|
func (s *SSH) readPins() (map[string]string, error) {
|
|
file := filepath.Join(s.root, "keys", "known_hosts.json")
|
|
data, err := os.ReadFile(file)
|
|
if os.IsNotExist(err) {
|
|
return map[string]string{}, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
pins := map[string]string{}
|
|
if err := json.Unmarshal(data, &pins); err != nil {
|
|
return nil, fmt.Errorf("read pinned SSH fingerprints: %w", err)
|
|
}
|
|
return pins, nil
|
|
}
|
|
|
|
func (s *SSH) writePins(pins map[string]string) error {
|
|
dir := filepath.Join(s.root, "keys")
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
return err
|
|
}
|
|
data, err := json.MarshalIndent(pins, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
file, err := os.CreateTemp(dir, ".known-hosts-*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
name := file.Name()
|
|
if _, err := file.Write(data); err != nil {
|
|
_ = file.Close()
|
|
_ = os.Remove(name)
|
|
return err
|
|
}
|
|
if err := file.Close(); err != nil {
|
|
_ = os.Remove(name)
|
|
return err
|
|
}
|
|
return os.Rename(name, filepath.Join(dir, "known_hosts.json"))
|
|
}
|
|
|
|
func confinedPath(home, requested string) (string, error) {
|
|
requested = strings.TrimSpace(requested)
|
|
if requested == "" || strings.ContainsRune(requested, '\x00') {
|
|
return "", errors.New("guest path is required")
|
|
}
|
|
home = path.Clean(home)
|
|
if !path.IsAbs(home) || home == "." {
|
|
return "", errors.New("guest home directory is unavailable")
|
|
}
|
|
var target string
|
|
if path.IsAbs(requested) {
|
|
target = path.Clean(requested)
|
|
} else {
|
|
target = path.Join(home, requested)
|
|
}
|
|
if !withinGuestHome(home, target) {
|
|
return "", errors.New("guest path must remain inside the guest home directory")
|
|
}
|
|
return target, nil
|
|
}
|
|
|
|
func withinGuestHome(home, target string) bool {
|
|
home = path.Clean(home)
|
|
target = path.Clean(target)
|
|
return target == home || strings.HasPrefix(target, strings.TrimSuffix(home, "/")+"/")
|
|
}
|
|
|
|
func mkdirGuestPath(transfer *sftp.Client, home, target string) error {
|
|
if !withinGuestHome(home, target) {
|
|
return errors.New("guest directory must remain inside the guest home directory")
|
|
}
|
|
relative := strings.TrimPrefix(strings.TrimPrefix(path.Clean(target), path.Clean(home)), "/")
|
|
current := path.Clean(home)
|
|
for _, part := range strings.Split(relative, "/") {
|
|
if part == "." || part == "" {
|
|
continue
|
|
}
|
|
current = path.Join(current, part)
|
|
info, err := transfer.Lstat(current)
|
|
if os.IsNotExist(err) {
|
|
if err := transfer.Mkdir(current); err != nil && !strings.Contains(strings.ToLower(err.Error()), "already exists") {
|
|
return err
|
|
}
|
|
info, err = transfer.Lstat(current)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
|
|
return fmt.Errorf("guest directory component %q is not a normal directory", current)
|
|
}
|
|
resolved, err := transfer.RealPath(current)
|
|
if err != nil || !withinGuestHome(home, resolved) {
|
|
return errors.New("guest directory resolves outside the guest home directory")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type outputWriter struct {
|
|
mu sync.Mutex
|
|
file *os.File
|
|
count int64
|
|
head []byte
|
|
tail []byte
|
|
}
|
|
|
|
func (w *outputWriter) Write(data []byte) (int, error) {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
n, err := w.file.Write(data)
|
|
if n > 0 {
|
|
w.count += int64(n)
|
|
if len(w.head) < 8<<10 {
|
|
keep := min(8<<10-len(w.head), n)
|
|
w.head = append(w.head, data[:keep]...)
|
|
}
|
|
w.tail = append(w.tail, data[:n]...)
|
|
if len(w.tail) > 8<<10 {
|
|
w.tail = append(w.tail[:0], w.tail[len(w.tail)-(8<<10):]...)
|
|
}
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
func (w *outputWriter) result() string {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
if w.count <= 16<<10 {
|
|
overlap := int64(len(w.head)+len(w.tail)) - w.count
|
|
if overlap > 0 {
|
|
return string(w.head) + string(w.tail[overlap:])
|
|
}
|
|
return string(w.head) + string(w.tail)
|
|
}
|
|
return string(w.head) + "\n… output truncated …\n" + string(w.tail)
|
|
}
|
|
|
|
func (w *outputWriter) truncated() bool {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
return w.count > 16<<10
|
|
}
|
|
|
|
func shellCommand(command, cwd string, env map[string]string) string {
|
|
var b strings.Builder
|
|
if cwd != "" {
|
|
fmt.Fprintf(&b, "cd %s && ", shellQuote(cwd))
|
|
}
|
|
for key, value := range env {
|
|
if !safeEnvName(key) {
|
|
continue
|
|
}
|
|
fmt.Fprintf(&b, "%s=%s ", key, shellQuote(value))
|
|
}
|
|
b.WriteString("sh -lc ")
|
|
b.WriteString(shellQuote(command))
|
|
return b.String()
|
|
}
|
|
|
|
func safeEnvName(key string) bool {
|
|
if key == "" || (key[0] != '_' && (key[0] < 'A' || key[0] > 'Z') && (key[0] < 'a' || key[0] > 'z')) {
|
|
return false
|
|
}
|
|
for _, r := range key {
|
|
if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" }
|