仰望星辰工作室

miaopanel

miaopanel/ internal/terminal/terminal.go 6.0 KB · 270 行 原始文件
1// Package terminal provides interactive shells for the web terminal: a local
2// PTY on the panel host and remote sessions over SSH.
3package terminal
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "net"
11 "os"
12 "os/exec"
13 "runtime"
14 "strings"
15 "sync"
16 "time"
17
18 "github.com/creack/pty"
19 "golang.org/x/crypto/ssh"
20)
21
22// Mode selects the session kind.
23const (
24 ModeLocal = "local"
25 ModeSSH = "ssh"
26)
27
28// Errors surfaced to the API layer.
29var (
30 ErrUnsupported = errors.New("当前系统不支持本机终端")
31 ErrInvalid = errors.New("终端参数不合法")
32)
33
34// Config describes a session request.
35type Config struct {
36 Mode string
37 Host string
38 Port int
39 User string
40 Password string
41 PrivateKey string
42 Shell string
43 WorkDir string
44 Cols int
45 Rows int
46}
47
48// Session is a bidirectional terminal channel.
49type Session struct {
50 reader io.Reader
51 writer io.Writer
52 resizeFn func(cols, rows int) error
53 closeFn func() error
54 waitFn func() error
55
56 mu sync.Mutex
57 closed bool
58}
59
60// Start opens the requested session.
61func Start(ctx context.Context, cfg Config) (*Session, error) {
62 if cfg.Cols <= 0 {
63 cfg.Cols = 100
64 }
65 if cfg.Rows <= 0 {
66 cfg.Rows = 30
67 }
68 switch cfg.Mode {
69 case "", ModeLocal:
70 return startLocal(cfg)
71 case ModeSSH:
72 return startSSH(ctx, cfg)
73 default:
74 return nil, fmt.Errorf("未知终端类型 %q", cfg.Mode)
75 }
76}
77
78// Read implements io.Reader.
79func (s *Session) Read(p []byte) (int, error) { return s.reader.Read(p) }
80
81// Write implements io.Writer.
82func (s *Session) Write(p []byte) (int, error) {
83 s.mu.Lock()
84 defer s.mu.Unlock()
85 if s.closed {
86 return 0, io.ErrClosedPipe
87 }
88 return s.writer.Write(p)
89}
90
91// Resize updates the PTY window size.
92func (s *Session) Resize(cols, rows int) error {
93 if cols <= 0 || rows <= 0 {
94 return nil
95 }
96 if cols > 1000 {
97 cols = 1000
98 }
99 if rows > 1000 {
100 rows = 1000
101 }
102 return s.resizeFn(cols, rows)
103}
104
105// Wait blocks until the shell exits.
106func (s *Session) Wait() error { return s.waitFn() }
107
108// Close releases the session; it is safe to call multiple times.
109func (s *Session) Close() error {
110 s.mu.Lock()
111 defer s.mu.Unlock()
112 if s.closed {
113 return nil
114 }
115 s.closed = true
116 return s.closeFn()
117}
118
119func startLocal(cfg Config) (*Session, error) {
120 if runtime.GOOS == "windows" {
121 return nil, ErrUnsupported
122 }
123 shell := cfg.Shell
124 if shell == "" {
125 for _, candidate := range []string{"/bin/bash", "/bin/sh"} {
126 if _, err := os.Stat(candidate); err == nil {
127 shell = candidate
128 break
129 }
130 }
131 }
132 if shell == "" {
133 return nil, ErrUnsupported
134 }
135 args := []string{"-l"}
136 if strings.HasSuffix(shell, "/bash") {
137 args = []string{"-l"}
138 }
139 cmd := exec.Command(shell, args...)
140 cmd.Env = append(os.Environ(),
141 "TERM=xterm-256color",
142 "COLORTERM=truecolor",
143 "MP_TERMINAL=1",
144 )
145 if cfg.WorkDir != "" {
146 cmd.Dir = cfg.WorkDir
147 } else if os.Geteuid() == 0 {
148 cmd.Dir = "/root"
149 }
150 ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: uint16(cfg.Cols), Rows: uint16(cfg.Rows)})
151 if err != nil {
152 return nil, fmt.Errorf("启动终端失败: %w", err)
153 }
154 sess := &Session{
155 reader: ptmx,
156 writer: ptmx,
157 resizeFn: func(cols, rows int) error {
158 return pty.Setsize(ptmx, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
159 },
160 closeFn: func() error {
161 _ = ptmx.Close()
162 if cmd.Process != nil {
163 _ = cmd.Process.Kill()
164 }
165 return nil
166 },
167 waitFn: func() error {
168 err := cmd.Wait()
169 if err != nil {
170 var exitErr *exec.ExitError
171 if errors.As(err, &exitErr) {
172 return nil // non-zero exit is a normal shell outcome
173 }
174 }
175 return err
176 },
177 }
178 return sess, nil
179}
180
181func startSSH(ctx context.Context, cfg Config) (*Session, error) {
182 if strings.TrimSpace(cfg.Host) == "" || strings.TrimSpace(cfg.User) == "" {
183 return nil, fmt.Errorf("%w: 缺少主机或用户名", ErrInvalid)
184 }
185 port := cfg.Port
186 if port == 0 {
187 port = 22
188 }
189 var auth []ssh.AuthMethod
190 if strings.TrimSpace(cfg.PrivateKey) != "" {
191 signer, err := ssh.ParsePrivateKey([]byte(cfg.PrivateKey))
192 if err != nil {
193 return nil, fmt.Errorf("%w: 私钥解析失败: %v", ErrInvalid, err)
194 }
195 auth = append(auth, ssh.PublicKeys(signer))
196 }
197 if cfg.Password != "" {
198 auth = append(auth, ssh.Password(cfg.Password))
199 }
200 if len(auth) == 0 {
201 return nil, fmt.Errorf("%w: 需要密码或私钥", ErrInvalid)
202 }
203 clientCfg := &ssh.ClientConfig{
204 User: cfg.User,
205 Auth: auth,
206 // The panel cannot maintain known_hosts for arbitrary targets; the
207 // connection is still encrypted and the operator supplies the host.
208 HostKeyCallback: ssh.InsecureIgnoreHostKey(),
209 Timeout: 12 * time.Second,
210 }
211 addr := net.JoinHostPort(cfg.Host, fmt.Sprint(port))
212 dialer := net.Dialer{Timeout: 12 * time.Second}
213 conn, err := dialer.DialContext(ctx, "tcp", addr)
214 if err != nil {
215 return nil, fmt.Errorf("连接 %s 失败: %w", addr, err)
216 }
217 sshConn, chans, reqs, err := ssh.NewClientConn(conn, addr, clientCfg)
218 if err != nil {
219 conn.Close()
220 return nil, fmt.Errorf("SSH 握手失败: %w", err)
221 }
222 client := ssh.NewClient(sshConn, chans, reqs)
223
224 sshSess, err := client.NewSession()
225 if err != nil {
226 client.Close()
227 return nil, fmt.Errorf("创建 SSH 会话失败: %w", err)
228 }
229 modes := ssh.TerminalModes{
230 ssh.ECHO: 1,
231 ssh.TTY_OP_ISPEED: 14400,
232 ssh.TTY_OP_OSPEED: 14400,
233 }
234 if err := sshSess.RequestPty("xterm-256color", cfg.Rows, cfg.Cols, modes); err != nil {
235 sshSess.Close()
236 client.Close()
237 return nil, fmt.Errorf("请求 PTY 失败: %w", err)
238 }
239 stdin, err := sshSess.StdinPipe()
240 if err != nil {
241 sshSess.Close()
242 client.Close()
243 return nil, err
244 }
245 stdout, err := sshSess.StdoutPipe()
246 if err != nil {
247 sshSess.Close()
248 client.Close()
249 return nil, err
250 }
251 sshSess.Stderr = sshSess.Stdout
252 if err := sshSess.Shell(); err != nil {
253 sshSess.Close()
254 client.Close()
255 return nil, fmt.Errorf("打开 shell 失败: %w", err)
256 }
257 sess := &Session{
258 reader: stdout,
259 writer: stdin,
260 resizeFn: func(cols, rows int) error {
261 return sshSess.WindowChange(rows, cols)
262 },
263 closeFn: func() error {
264 _ = sshSess.Close()
265 return client.Close()
266 },
267 waitFn: sshSess.Wait,
268 }
269 return sess, nil
270}