-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.go
126 lines (99 loc) · 2.47 KB
/
ssh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"context"
"image/color"
"io"
"net"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/widget"
"github.com/fyne-io/terminal"
"golang.org/x/crypto/ssh"
)
type remote struct {
widget.BaseWidget
terminal *terminal.Terminal
session *ssh.Session
win fyne.Window
disconnected func()
err error
}
var _ fyne.Widget = (*remote)(nil)
var _ io.Closer = (*remote)(nil)
func (r *router) NewSSH(win fyne.Window, dial func(ctx context.Context, network, address string) (net.Conn, error)) (*remote, error) {
config := ssh.ClientConfig{
User: r.user,
Auth: []ssh.AuthMethod{
ssh.Password(r.password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := dial(context.Background(), "tcp", r.host+":22")
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, r.host+":22", &config)
if err != nil {
conn.Close()
return nil, err
}
client := ssh.NewClient(c, chans, reqs)
session, err := client.NewSession()
if err != nil {
c.Close()
return nil, err
}
rssh := &remote{
terminal: terminal.New(),
session: session,
win: win,
}
rssh.ExtendBaseWidget(rssh)
modes := ssh.TerminalModes{
ssh.ECHO: 1, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
cellSize := guessCellSize()
if err := session.RequestPty("xterm-256color", int(rssh.Size().Height/cellSize.Height), int(rssh.Size().Width/cellSize.Width), modes); err != nil {
_ = session.Close()
return nil, err
}
in, _ := session.StdinPipe()
out, _ := session.StdoutPipe()
go session.Run("")
go func() {
rssh.err = rssh.terminal.RunWithConnection(in, out)
if rssh.disconnected != nil {
rssh.disconnected()
}
}()
return rssh, nil
}
func (r *remote) OnDisconnected(f func()) {
r.disconnected = f
}
func (r *remote) Tapped(_ *fyne.PointEvent) {
r.win.Canvas().Focus(r.terminal)
}
func (r *remote) Resize(s fyne.Size) {
cellSize := guessCellSize()
r.err = r.session.WindowChange(int(s.Height/cellSize.Height), int(s.Width/cellSize.Width))
r.terminal.Resize(s)
}
func (r *remote) Close() error {
if r.session == nil {
return nil
}
err := r.session.Close()
r.session = nil
return err
}
func (r *remote) CreateRenderer() fyne.WidgetRenderer {
return widget.NewSimpleRenderer(r.terminal)
}
func guessCellSize() fyne.Size {
cell := canvas.NewText("M", color.White)
cell.TextStyle.Monospace = true
return cell.MinSize()
}