// Package terminal provides interactive shells for the web terminal: a local // PTY on the panel host and remote sessions over SSH. package terminal import ( "context" "errors" "fmt" "io" "net" "os" "os/exec" "runtime" "strings" "sync" "time" "github.com/creack/pty" "golang.org/x/crypto/ssh" ) // Mode selects the session kind. const ( ModeLocal = "local" ModeSSH = "ssh" ) // Errors surfaced to the API layer. var ( ErrUnsupported = errors.New("当前系统不支持本机终端") ErrInvalid = errors.New("终端参数不合法") ) // Config describes a session request. type Config struct { Mode string Host string Port int User string Password string PrivateKey string Shell string WorkDir string Cols int Rows int } // Session is a bidirectional terminal channel. type Session struct { reader io.Reader writer io.Writer resizeFn func(cols, rows int) error closeFn func() error waitFn func() error mu sync.Mutex closed bool } // Start opens the requested session. func Start(ctx context.Context, cfg Config) (*Session, error) { if cfg.Cols <= 0 { cfg.Cols = 100 } if cfg.Rows <= 0 { cfg.Rows = 30 } switch cfg.Mode { case "", ModeLocal: return startLocal(cfg) case ModeSSH: return startSSH(ctx, cfg) default: return nil, fmt.Errorf("未知终端类型 %q", cfg.Mode) } } // Read implements io.Reader. func (s *Session) Read(p []byte) (int, error) { return s.reader.Read(p) } // Write implements io.Writer. func (s *Session) Write(p []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() if s.closed { return 0, io.ErrClosedPipe } return s.writer.Write(p) } // Resize updates the PTY window size. func (s *Session) Resize(cols, rows int) error { if cols <= 0 || rows <= 0 { return nil } if cols > 1000 { cols = 1000 } if rows > 1000 { rows = 1000 } return s.resizeFn(cols, rows) } // Wait blocks until the shell exits. func (s *Session) Wait() error { return s.waitFn() } // Close releases the session; it is safe to call multiple times. func (s *Session) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.closed { return nil } s.closed = true return s.closeFn() } func startLocal(cfg Config) (*Session, error) { if runtime.GOOS == "windows" { return nil, ErrUnsupported } shell := cfg.Shell if shell == "" { for _, candidate := range []string{"/bin/bash", "/bin/sh"} { if _, err := os.Stat(candidate); err == nil { shell = candidate break } } } if shell == "" { return nil, ErrUnsupported } args := []string{"-l"} if strings.HasSuffix(shell, "/bash") { args = []string{"-l"} } cmd := exec.Command(shell, args...) cmd.Env = append(os.Environ(), "TERM=xterm-256color", "COLORTERM=truecolor", "MP_TERMINAL=1", ) if cfg.WorkDir != "" { cmd.Dir = cfg.WorkDir } else if os.Geteuid() == 0 { cmd.Dir = "/root" } ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: uint16(cfg.Cols), Rows: uint16(cfg.Rows)}) if err != nil { return nil, fmt.Errorf("启动终端失败: %w", err) } sess := &Session{ reader: ptmx, writer: ptmx, resizeFn: func(cols, rows int) error { return pty.Setsize(ptmx, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)}) }, closeFn: func() error { _ = ptmx.Close() if cmd.Process != nil { _ = cmd.Process.Kill() } return nil }, waitFn: func() error { err := cmd.Wait() if err != nil { var exitErr *exec.ExitError if errors.As(err, &exitErr) { return nil // non-zero exit is a normal shell outcome } } return err }, } return sess, nil } func startSSH(ctx context.Context, cfg Config) (*Session, error) { if strings.TrimSpace(cfg.Host) == "" || strings.TrimSpace(cfg.User) == "" { return nil, fmt.Errorf("%w: 缺少主机或用户名", ErrInvalid) } port := cfg.Port if port == 0 { port = 22 } var auth []ssh.AuthMethod if strings.TrimSpace(cfg.PrivateKey) != "" { signer, err := ssh.ParsePrivateKey([]byte(cfg.PrivateKey)) if err != nil { return nil, fmt.Errorf("%w: 私钥解析失败: %v", ErrInvalid, err) } auth = append(auth, ssh.PublicKeys(signer)) } if cfg.Password != "" { auth = append(auth, ssh.Password(cfg.Password)) } if len(auth) == 0 { return nil, fmt.Errorf("%w: 需要密码或私钥", ErrInvalid) } clientCfg := &ssh.ClientConfig{ User: cfg.User, Auth: auth, // The panel cannot maintain known_hosts for arbitrary targets; the // connection is still encrypted and the operator supplies the host. HostKeyCallback: ssh.InsecureIgnoreHostKey(), Timeout: 12 * time.Second, } addr := net.JoinHostPort(cfg.Host, fmt.Sprint(port)) dialer := net.Dialer{Timeout: 12 * time.Second} conn, err := dialer.DialContext(ctx, "tcp", addr) if err != nil { return nil, fmt.Errorf("连接 %s 失败: %w", addr, err) } sshConn, chans, reqs, err := ssh.NewClientConn(conn, addr, clientCfg) if err != nil { conn.Close() return nil, fmt.Errorf("SSH 握手失败: %w", err) } client := ssh.NewClient(sshConn, chans, reqs) sshSess, err := client.NewSession() if err != nil { client.Close() return nil, fmt.Errorf("创建 SSH 会话失败: %w", err) } modes := ssh.TerminalModes{ ssh.ECHO: 1, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400, } if err := sshSess.RequestPty("xterm-256color", cfg.Rows, cfg.Cols, modes); err != nil { sshSess.Close() client.Close() return nil, fmt.Errorf("请求 PTY 失败: %w", err) } stdin, err := sshSess.StdinPipe() if err != nil { sshSess.Close() client.Close() return nil, err } stdout, err := sshSess.StdoutPipe() if err != nil { sshSess.Close() client.Close() return nil, err } sshSess.Stderr = sshSess.Stdout if err := sshSess.Shell(); err != nil { sshSess.Close() client.Close() return nil, fmt.Errorf("打开 shell 失败: %w", err) } sess := &Session{ reader: stdout, writer: stdin, resizeFn: func(cols, rows int) error { return sshSess.WindowChange(rows, cols) }, closeFn: func() error { _ = sshSess.Close() return client.Close() }, waitFn: sshSess.Wait, } return sess, nil }