This repository has been archived by the owner on Oct 2, 2022. It is now read-only.
generated from ContainerSSH/library-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler_channel.go
284 lines (257 loc) · 6.79 KB
/
handler_channel.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package docker
import (
"context"
"errors"
"io"
"strings"
"github.com/containerssh/log"
"github.com/containerssh/sshserver"
"github.com/containerssh/unixutils"
)
type channelHandler struct {
sshserver.AbstractSessionChannelHandler
channelID uint64
networkHandler *networkHandler
username string
env map[string]string
pty bool
columns uint32
rows uint32
exitSent bool
exec dockerExecution
session sshserver.SessionChannel
}
func (c *channelHandler) OnEnvRequest(_ uint64, name string, value string) error {
c.networkHandler.mutex.Lock()
defer c.networkHandler.mutex.Unlock()
if c.exec != nil {
return log.UserMessage(EProgramAlreadyRunning, "program already running", "program already running")
}
c.env[name] = value
return nil
}
func (c *channelHandler) OnPtyRequest(
_ uint64,
term string,
columns uint32,
rows uint32,
_ uint32,
_ uint32,
_ []byte,
) error {
c.networkHandler.mutex.Lock()
defer c.networkHandler.mutex.Unlock()
if c.exec != nil {
return log.UserMessage(EProgramAlreadyRunning, "program already running", "program already running")
}
c.env["TERM"] = term
c.rows = rows
c.columns = columns
c.pty = true
return nil
}
func (c *channelHandler) parseProgram(program string) []string {
programParts, err := unixutils.ParseCMD(program)
if err != nil {
return []string{"/bin/sh", "-c", program}
} else {
if strings.HasPrefix(programParts[0], "/") || strings.HasPrefix(
programParts[0],
"./",
) || strings.HasPrefix(programParts[0], "../") {
return programParts
} else {
return []string{"/bin/sh", "-c", program}
}
}
}
func (c *channelHandler) run(
ctx context.Context,
program []string,
) error {
c.networkHandler.mutex.Lock()
defer c.networkHandler.mutex.Unlock()
if c.exec != nil {
return log.UserMessage(EProgramAlreadyRunning, "program already running", "program already running")
}
var err error
switch c.networkHandler.config.Execution.Mode {
case ExecutionModeConnection:
err = c.handleExecModeConnection(ctx, program)
case ExecutionModeSession:
err = c.handleExecModeSession(ctx, program)
default:
err = log.UserMessage(
EConfigError,
"cannot run program",
"invalid execution mode: %s",
c.networkHandler.config.Execution.Mode,
)
}
if err != nil {
return err
}
c.exec.run(
c.session.Stdin(),
c.session.Stdout(),
c.session.Stderr(),
c.session.CloseWrite,
func(exitStatus int) {
c.session.ExitStatus(uint32(exitStatus))
if err := c.session.Close(); err != nil && !errors.Is(err, io.EOF) {
c.networkHandler.logger.Debug(log.Wrap(
err,
EFailedOutputCloseWriting,
"failed to close session",
))
}
},
)
return nil
}
func (c *channelHandler) handleExecModeConnection(
ctx context.Context,
program []string,
) error {
exec, err := c.networkHandler.container.createExec(ctx, program, c.env, c.pty)
if err != nil {
return err
}
c.exec = exec
if c.pty {
err = c.exec.resize(ctx, uint(c.rows), uint(c.columns))
if err != nil {
c.networkHandler.logger.Debug(err)
}
}
return nil
}
func (c *channelHandler) handleExecModeSession(
ctx context.Context,
program []string,
) error {
cnt, err := c.networkHandler.dockerClient.createContainer(
ctx,
c.networkHandler.labels,
c.env,
&c.pty,
program,
)
if err != nil {
return err
}
removeContainer := func() {
ctx, cancelFunc := context.WithTimeout(
context.Background(), c.networkHandler.config.Timeouts.ContainerStop,
)
defer cancelFunc()
_ = cnt.remove(ctx)
}
c.exec, err = cnt.attach(ctx)
if err != nil {
removeContainer()
return err
}
if err := cnt.start(ctx); err != nil {
removeContainer()
return err
}
if c.pty {
err := c.exec.resize(ctx, uint(c.rows), uint(c.columns))
if err != nil {
removeContainer()
return err
}
}
return nil
}
func (c *channelHandler) OnExecRequest(
_ uint64,
program string,
) error {
if c.networkHandler.config.Execution.disableCommand {
return log.UserMessage(
EProgramExecutionDisabled,
"Command execution is disabled.",
"Command execution is disabled.",
)
}
startContext, cancelFunc := context.WithTimeout(context.Background(), c.networkHandler.config.Timeouts.CommandStart)
defer cancelFunc()
return c.run(
startContext,
c.parseProgram(program),
)
}
func (c *channelHandler) OnShell(
_ uint64,
) error {
startContext, cancelFunc := context.WithTimeout(context.Background(), c.networkHandler.config.Timeouts.CommandStart)
defer cancelFunc()
return c.run(startContext, c.getDefaultShell())
}
func (c *channelHandler) getDefaultShell() []string {
return c.networkHandler.config.Execution.ShellCommand
}
func (c *channelHandler) OnSubsystem(
_ uint64,
subsystem string,
) error {
startContext, cancelFunc := context.WithTimeout(context.Background(), c.networkHandler.config.Timeouts.CommandStart)
defer cancelFunc()
if binary, ok := c.networkHandler.config.Execution.Subsystems[subsystem]; ok {
return c.run(startContext, []string{binary})
}
return log.UserMessage(ESubsystemNotSupported, "subsystem not supported", "the specified subsystem is not supported (%s)", subsystem)
}
func (c *channelHandler) OnSignal(_ uint64, signal string) error {
c.networkHandler.mutex.Lock()
defer c.networkHandler.mutex.Unlock()
if c.exec == nil {
return log.UserMessage(
EProgramNotRunning,
"Cannot send signal, program is not running.",
"Cannot send signal, program is not running.",
)
}
ctx, cancelFunc := context.WithTimeout(context.Background(), c.networkHandler.config.Timeouts.Signal)
defer cancelFunc()
return c.exec.signal(ctx, signal)
}
func (c *channelHandler) OnWindow(_ uint64, columns uint32, rows uint32, _ uint32, _ uint32) error {
c.networkHandler.mutex.Lock()
defer c.networkHandler.mutex.Unlock()
if c.exec == nil {
return log.UserMessage(
EProgramNotRunning,
"Cannot resize window, program is not running.",
"Cannot resize window, program is not running.",
)
}
ctx, cancelFunc := context.WithTimeout(context.Background(), c.networkHandler.config.Timeouts.Window)
defer cancelFunc()
return c.exec.resize(ctx, uint(rows), uint(columns))
}
func (c *channelHandler) OnClose() {
if c.exec != nil {
c.exec.kill()
}
container := c.networkHandler.container
if container != nil && c.networkHandler.config.Execution.Mode == ExecutionModeSession {
ctx, cancel := context.WithTimeout(context.Background(), c.networkHandler.config.Timeouts.ContainerStop)
defer cancel()
_ = container.remove(ctx)
}
}
func (c *channelHandler) OnShutdown(shutdownContext context.Context) {
if c.exec != nil {
c.exec.term(shutdownContext)
// We wait for the program to exit. This is not needed in session or connection mode, but
// later we will need to support persistent containers.
select {
case <-shutdownContext.Done():
c.exec.kill()
case <-c.exec.done():
}
}
}