2024-05-15 01:53:03 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package shellexec
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-07-16 03:00:10 +02:00
|
|
|
"log"
|
2024-05-15 01:53:03 +02:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
2024-08-01 08:47:33 +02:00
|
|
|
"path/filepath"
|
2024-06-12 20:33:45 +02:00
|
|
|
"reflect"
|
2024-07-16 03:00:10 +02:00
|
|
|
"regexp"
|
2024-08-10 03:49:35 +02:00
|
|
|
"runtime"
|
2024-07-16 03:00:10 +02:00
|
|
|
"strings"
|
2024-06-24 23:34:31 +02:00
|
|
|
"sync"
|
2024-05-15 01:53:03 +02:00
|
|
|
"syscall"
|
|
|
|
|
|
|
|
"github.com/creack/pty"
|
2024-07-16 03:00:10 +02:00
|
|
|
"github.com/wavetermdev/thenextwave/pkg/remote"
|
2024-05-15 01:53:03 +02:00
|
|
|
"github.com/wavetermdev/thenextwave/pkg/util/shellutil"
|
2024-05-16 09:29:58 +02:00
|
|
|
"github.com/wavetermdev/thenextwave/pkg/wavebase"
|
2024-08-16 06:32:08 +02:00
|
|
|
"golang.org/x/crypto/ssh"
|
2024-05-15 01:53:03 +02:00
|
|
|
)
|
|
|
|
|
2024-05-15 07:37:04 +02:00
|
|
|
type TermSize struct {
|
|
|
|
Rows int `json:"rows"`
|
|
|
|
Cols int `json:"cols"`
|
|
|
|
}
|
|
|
|
|
2024-06-24 23:34:31 +02:00
|
|
|
type CommandOptsType struct {
|
|
|
|
Interactive bool `json:"interactive,omitempty"`
|
|
|
|
Login bool `json:"login,omitempty"`
|
|
|
|
Cwd string `json:"cwd,omitempty"`
|
|
|
|
Env map[string]string `json:"env,omitempty"`
|
|
|
|
}
|
|
|
|
|
2024-05-15 08:25:21 +02:00
|
|
|
type ShellProc struct {
|
2024-07-16 03:00:10 +02:00
|
|
|
Cmd ConnInterface
|
2024-06-24 23:34:31 +02:00
|
|
|
CloseOnce *sync.Once
|
|
|
|
DoneCh chan any // closed after proc.Wait() returns
|
|
|
|
WaitErr error // WaitErr is synchronized by DoneCh (written before DoneCh is closed) and CloseOnce
|
2024-05-15 08:25:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (sp *ShellProc) Close() {
|
2024-07-16 03:00:10 +02:00
|
|
|
sp.Cmd.Kill()
|
2024-05-15 08:25:21 +02:00
|
|
|
go func() {
|
2024-07-16 03:00:10 +02:00
|
|
|
waitErr := sp.Cmd.Wait()
|
2024-06-24 23:34:31 +02:00
|
|
|
sp.SetWaitErrorAndSignalDone(waitErr)
|
2024-08-10 03:49:35 +02:00
|
|
|
|
|
|
|
// windows cannot handle the pty being
|
|
|
|
// closed twice, so we let the pty
|
|
|
|
// close itself instead
|
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
sp.Cmd.Close()
|
|
|
|
}
|
2024-05-15 08:25:21 +02:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2024-06-24 23:34:31 +02:00
|
|
|
func (sp *ShellProc) SetWaitErrorAndSignalDone(waitErr error) {
|
|
|
|
sp.CloseOnce.Do(func() {
|
|
|
|
sp.WaitErr = waitErr
|
|
|
|
close(sp.DoneCh)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (sp *ShellProc) Wait() error {
|
|
|
|
<-sp.DoneCh
|
|
|
|
return sp.WaitErr
|
|
|
|
}
|
|
|
|
|
|
|
|
// returns (done, waitError)
|
|
|
|
func (sp *ShellProc) WaitNB() (bool, error) {
|
|
|
|
select {
|
|
|
|
case <-sp.DoneCh:
|
|
|
|
return true, sp.WaitErr
|
|
|
|
default:
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func ExitCodeFromWaitErr(err error) int {
|
|
|
|
if err == nil {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
if exitErr, ok := err.(*exec.ExitError); ok {
|
|
|
|
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
|
|
|
|
return status.ExitStatus()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2024-06-12 20:33:45 +02:00
|
|
|
func setBoolConditionally(rval reflect.Value, field string, value bool) {
|
|
|
|
if rval.Elem().FieldByName(field).IsValid() {
|
|
|
|
rval.Elem().FieldByName(field).SetBool(value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func setSysProcAttrs(cmd *exec.Cmd) {
|
|
|
|
rval := reflect.ValueOf(cmd.SysProcAttr)
|
|
|
|
setBoolConditionally(rval, "Setsid", true)
|
|
|
|
setBoolConditionally(rval, "Setctty", true)
|
|
|
|
}
|
|
|
|
|
2024-06-24 23:34:31 +02:00
|
|
|
func checkCwd(cwd string) error {
|
|
|
|
if cwd == "" {
|
|
|
|
return fmt.Errorf("cwd is empty")
|
|
|
|
}
|
|
|
|
if _, err := os.Stat(cwd); err != nil {
|
|
|
|
return fmt.Errorf("error statting cwd %q: %w", cwd, err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-07-16 03:00:10 +02:00
|
|
|
var userHostRe = regexp.MustCompile(`^([a-zA-Z0-9][a-zA-Z0-9._@\\-]*@)?([a-z0-9][a-z0-9.-]*)(?::([0-9]+))?$`)
|
|
|
|
|
2024-08-10 03:49:35 +02:00
|
|
|
type PipePty struct {
|
|
|
|
remoteStdinWrite *os.File
|
|
|
|
remoteStdoutRead *os.File
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pp *PipePty) Fd() uintptr {
|
|
|
|
return pp.remoteStdinWrite.Fd()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pp *PipePty) Name() string {
|
|
|
|
return "pipe-pty"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pp *PipePty) Read(p []byte) (n int, err error) {
|
|
|
|
return pp.remoteStdoutRead.Read(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pp *PipePty) Write(p []byte) (n int, err error) {
|
|
|
|
return pp.remoteStdinWrite.Write(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pp *PipePty) Close() error {
|
|
|
|
err1 := pp.remoteStdinWrite.Close()
|
|
|
|
err2 := pp.remoteStdoutRead.Close()
|
|
|
|
|
|
|
|
if err1 != nil {
|
|
|
|
return err1
|
|
|
|
}
|
|
|
|
return err2
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pp *PipePty) WriteString(s string) (n int, err error) {
|
|
|
|
return pp.Write([]byte(s))
|
|
|
|
}
|
|
|
|
|
2024-08-16 06:32:08 +02:00
|
|
|
func StartRemoteShellProc(termSize TermSize, cmdStr string, cmdOpts CommandOptsType, client *ssh.Client) (*ShellProc, error) {
|
|
|
|
shellPath, err := remote.DetectShell(client)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var shellOpts []string
|
|
|
|
var cmdCombined string
|
|
|
|
log.Printf("detected shell: %s", shellPath)
|
|
|
|
|
|
|
|
err = remote.InstallClientRcFiles(client)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("error installing rc files: %v", err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
homeDir := remote.GetHomeDir(client)
|
2024-07-16 03:00:10 +02:00
|
|
|
|
|
|
|
if cmdStr == "" {
|
2024-08-16 06:32:08 +02:00
|
|
|
/* transform command in order to inject environment vars */
|
|
|
|
if isBashShell(shellPath) {
|
|
|
|
log.Printf("recognized as bash shell")
|
|
|
|
// add --rcfile
|
|
|
|
// cant set -l or -i with --rcfile
|
|
|
|
shellOpts = append(shellOpts, "--rcfile", fmt.Sprintf(`"%s"/.waveterm/bash-integration/.bashrc`, homeDir))
|
|
|
|
} else {
|
|
|
|
if cmdOpts.Login {
|
|
|
|
shellOpts = append(shellOpts, "-l")
|
|
|
|
}
|
|
|
|
if cmdOpts.Interactive {
|
|
|
|
shellOpts = append(shellOpts, "-i")
|
|
|
|
}
|
|
|
|
// zdotdir setting moved to after session is created
|
|
|
|
}
|
|
|
|
cmdCombined = fmt.Sprintf("%s %s", shellPath, strings.Join(shellOpts, " "))
|
|
|
|
log.Printf("combined command is: %s", cmdCombined)
|
2024-07-16 03:00:10 +02:00
|
|
|
} else {
|
|
|
|
shellPath = cmdStr
|
2024-08-16 06:32:08 +02:00
|
|
|
if cmdOpts.Login {
|
|
|
|
shellOpts = append(shellOpts, "-l")
|
2024-07-16 03:00:10 +02:00
|
|
|
}
|
2024-08-16 06:32:08 +02:00
|
|
|
if cmdOpts.Interactive {
|
|
|
|
shellOpts = append(shellOpts, "-i")
|
|
|
|
}
|
|
|
|
shellOpts = append(shellOpts, "-c", cmdStr)
|
|
|
|
cmdCombined = fmt.Sprintf("%s %s", shellPath, strings.Join(shellOpts, " "))
|
2024-07-16 03:00:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
session, err := client.NewSession()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2024-08-10 03:49:35 +02:00
|
|
|
remoteStdinRead, remoteStdinWriteOurs, err := os.Pipe()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
remoteStdoutReadOurs, remoteStdoutWrite, err := os.Pipe()
|
2024-07-16 03:00:10 +02:00
|
|
|
if err != nil {
|
2024-08-10 03:49:35 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
pipePty := &PipePty{
|
|
|
|
remoteStdinWrite: remoteStdinWriteOurs,
|
|
|
|
remoteStdoutRead: remoteStdoutReadOurs,
|
2024-07-16 03:00:10 +02:00
|
|
|
}
|
|
|
|
if termSize.Rows == 0 || termSize.Cols == 0 {
|
|
|
|
termSize.Rows = shellutil.DefaultTermRows
|
|
|
|
termSize.Cols = shellutil.DefaultTermCols
|
|
|
|
}
|
|
|
|
if termSize.Rows <= 0 || termSize.Cols <= 0 {
|
|
|
|
return nil, fmt.Errorf("invalid term size: %v", termSize)
|
|
|
|
}
|
2024-08-10 03:49:35 +02:00
|
|
|
session.Stdin = remoteStdinRead
|
|
|
|
session.Stdout = remoteStdoutWrite
|
|
|
|
session.Stderr = remoteStdoutWrite
|
2024-08-16 06:32:08 +02:00
|
|
|
|
2024-07-23 22:16:53 +02:00
|
|
|
for envKey, envVal := range cmdOpts.Env {
|
|
|
|
// note these might fail depending on server settings, but we still try
|
|
|
|
session.Setenv(envKey, envVal)
|
|
|
|
}
|
|
|
|
|
2024-08-16 06:32:08 +02:00
|
|
|
if isZshShell(shellPath) {
|
|
|
|
cmdCombined = fmt.Sprintf(`ZDOTDIR="%s/.waveterm/zsh-integration" %s`, homeDir, cmdCombined)
|
|
|
|
}
|
|
|
|
|
2024-07-16 03:00:10 +02:00
|
|
|
session.RequestPty("xterm-256color", termSize.Rows, termSize.Cols, nil)
|
|
|
|
|
2024-08-10 03:49:35 +02:00
|
|
|
sessionWrap := SessionWrap{session, cmdCombined, pipePty, pipePty}
|
2024-07-16 03:00:10 +02:00
|
|
|
err = sessionWrap.Start()
|
|
|
|
if err != nil {
|
2024-08-10 03:49:35 +02:00
|
|
|
pipePty.Close()
|
2024-07-16 03:00:10 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2024-08-10 03:49:35 +02:00
|
|
|
return &ShellProc{Cmd: sessionWrap, CloseOnce: &sync.Once{}, DoneCh: make(chan any)}, nil
|
2024-07-16 03:00:10 +02:00
|
|
|
}
|
|
|
|
|
2024-08-01 08:47:33 +02:00
|
|
|
func isZshShell(shellPath string) bool {
|
|
|
|
// get the base path, and then check contains
|
|
|
|
shellBase := filepath.Base(shellPath)
|
|
|
|
return strings.Contains(shellBase, "zsh")
|
|
|
|
}
|
|
|
|
|
|
|
|
func isBashShell(shellPath string) bool {
|
|
|
|
// get the base path, and then check contains
|
|
|
|
shellBase := filepath.Base(shellPath)
|
|
|
|
return strings.Contains(shellBase, "bash")
|
|
|
|
}
|
|
|
|
|
2024-06-24 23:34:31 +02:00
|
|
|
func StartShellProc(termSize TermSize, cmdStr string, cmdOpts CommandOptsType) (*ShellProc, error) {
|
2024-08-01 08:47:33 +02:00
|
|
|
shellutil.InitCustomShellStartupFiles()
|
2024-06-24 23:34:31 +02:00
|
|
|
var ecmd *exec.Cmd
|
|
|
|
var shellOpts []string
|
2024-08-01 08:47:33 +02:00
|
|
|
|
|
|
|
shellPath := shellutil.DetectLocalShellPath()
|
2024-06-24 23:34:31 +02:00
|
|
|
if cmdStr == "" {
|
2024-08-01 08:47:33 +02:00
|
|
|
if isBashShell(shellPath) {
|
|
|
|
// add --rcfile
|
|
|
|
// cant set -l or -i with --rcfile
|
|
|
|
shellOpts = append(shellOpts, "--rcfile", shellutil.GetBashRcFileOverride())
|
2024-08-10 03:49:35 +02:00
|
|
|
} else if runtime.GOOS != "windows" {
|
2024-08-01 08:47:33 +02:00
|
|
|
if cmdOpts.Login {
|
|
|
|
shellOpts = append(shellOpts, "-l")
|
|
|
|
}
|
|
|
|
if cmdOpts.Interactive {
|
|
|
|
shellOpts = append(shellOpts, "-i")
|
|
|
|
}
|
|
|
|
}
|
2024-06-24 23:34:31 +02:00
|
|
|
ecmd = exec.Command(shellPath, shellOpts...)
|
2024-08-01 08:47:33 +02:00
|
|
|
ecmd.Env = os.Environ()
|
|
|
|
if isZshShell(shellPath) {
|
|
|
|
shellutil.UpdateCmdEnv(ecmd, map[string]string{"ZDOTDIR": shellutil.GetZshZDotDir()})
|
|
|
|
}
|
2024-06-24 23:34:31 +02:00
|
|
|
} else {
|
2024-08-01 08:47:33 +02:00
|
|
|
if cmdOpts.Login {
|
|
|
|
shellOpts = append(shellOpts, "-l")
|
|
|
|
}
|
|
|
|
if cmdOpts.Interactive {
|
|
|
|
shellOpts = append(shellOpts, "-i")
|
|
|
|
}
|
2024-06-24 23:34:31 +02:00
|
|
|
shellOpts = append(shellOpts, "-c", cmdStr)
|
|
|
|
ecmd = exec.Command(shellPath, shellOpts...)
|
2024-08-01 08:47:33 +02:00
|
|
|
ecmd.Env = os.Environ()
|
2024-06-24 23:34:31 +02:00
|
|
|
}
|
|
|
|
if cmdOpts.Cwd != "" {
|
|
|
|
ecmd.Dir = cmdOpts.Cwd
|
|
|
|
}
|
|
|
|
if cwdErr := checkCwd(ecmd.Dir); cwdErr != nil {
|
|
|
|
ecmd.Dir = wavebase.GetHomeDir()
|
|
|
|
}
|
2024-08-01 08:47:33 +02:00
|
|
|
envToAdd := shellutil.WaveshellLocalEnvVars(shellutil.DefaultTermType)
|
2024-05-16 09:29:58 +02:00
|
|
|
if os.Getenv("LANG") == "" {
|
|
|
|
envToAdd["LANG"] = wavebase.DetermineLang()
|
|
|
|
}
|
|
|
|
shellutil.UpdateCmdEnv(ecmd, envToAdd)
|
2024-07-23 22:16:53 +02:00
|
|
|
shellutil.UpdateCmdEnv(ecmd, cmdOpts.Env)
|
2024-05-15 08:25:21 +02:00
|
|
|
if termSize.Rows == 0 || termSize.Cols == 0 {
|
|
|
|
termSize.Rows = shellutil.DefaultTermRows
|
|
|
|
termSize.Cols = shellutil.DefaultTermCols
|
|
|
|
}
|
|
|
|
if termSize.Rows <= 0 || termSize.Cols <= 0 {
|
|
|
|
return nil, fmt.Errorf("invalid term size: %v", termSize)
|
|
|
|
}
|
2024-08-10 03:49:35 +02:00
|
|
|
cmdPty, err := pty.StartWithSize(ecmd, &pty.Winsize{Rows: uint16(termSize.Rows), Cols: uint16(termSize.Cols)})
|
2024-05-15 08:25:21 +02:00
|
|
|
if err != nil {
|
|
|
|
cmdPty.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-08-10 03:49:35 +02:00
|
|
|
return &ShellProc{Cmd: CmdWrap{ecmd, cmdPty}, CloseOnce: &sync.Once{}, DoneCh: make(chan any)}, nil
|
2024-05-15 08:25:21 +02:00
|
|
|
}
|
|
|
|
|
2024-05-15 07:37:04 +02:00
|
|
|
func RunSimpleCmdInPty(ecmd *exec.Cmd, termSize TermSize) ([]byte, error) {
|
2024-05-15 01:53:03 +02:00
|
|
|
ecmd.Env = os.Environ()
|
2024-08-01 08:47:33 +02:00
|
|
|
shellutil.UpdateCmdEnv(ecmd, shellutil.WaveshellLocalEnvVars(shellutil.DefaultTermType))
|
2024-05-15 07:37:04 +02:00
|
|
|
if termSize.Rows == 0 || termSize.Cols == 0 {
|
|
|
|
termSize.Rows = shellutil.DefaultTermRows
|
|
|
|
termSize.Cols = shellutil.DefaultTermCols
|
|
|
|
}
|
|
|
|
if termSize.Rows <= 0 || termSize.Cols <= 0 {
|
|
|
|
return nil, fmt.Errorf("invalid term size: %v", termSize)
|
|
|
|
}
|
2024-08-10 03:49:35 +02:00
|
|
|
cmdPty, err := pty.StartWithSize(ecmd, &pty.Winsize{Rows: uint16(termSize.Rows), Cols: uint16(termSize.Cols)})
|
2024-05-15 01:53:03 +02:00
|
|
|
if err != nil {
|
|
|
|
cmdPty.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-08-10 03:49:35 +02:00
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
defer cmdPty.Close()
|
|
|
|
}
|
2024-05-15 01:53:03 +02:00
|
|
|
ioDone := make(chan bool)
|
|
|
|
var outputBuf bytes.Buffer
|
|
|
|
go func() {
|
|
|
|
// ignore error (/dev/ptmx has read error when process is done)
|
|
|
|
defer close(ioDone)
|
|
|
|
io.Copy(&outputBuf, cmdPty)
|
|
|
|
}()
|
|
|
|
exitErr := ecmd.Wait()
|
|
|
|
if exitErr != nil {
|
|
|
|
return nil, exitErr
|
|
|
|
}
|
|
|
|
<-ioDone
|
|
|
|
return outputBuf.Bytes(), nil
|
|
|
|
}
|