-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathtermmanager.go
304 lines (260 loc) · 6.66 KB
/
termmanager.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2021 Gravitational, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package srv
import (
"io"
"sync"
"sync/atomic"
log "github.com/sirupsen/logrus"
)
// maxHistoryBytes is the maximum bytes that are retained as history and broadcasted to new clients.
const maxHistoryBytes = 1000
// maxPausedHistoryBytes is maximum bytes that are buffered when a session is paused.
const maxPausedHistoryBytes = 10000
// TermManager handles the streams of terminal-like sessions.
// It performs a number of tasks including:
// - multiplexing
// - history scrollback for new clients
// - stream breaking
type TermManager struct {
// These two fields need to be first in the struct so that they are 64-bit aligned which is a requirement
// for atomic operations on certain architectures.
countWritten uint64
countRead uint64
mu sync.Mutex
writers map[string]io.Writer
readerState map[string]bool
OnWriteError func(idString string, err error)
// buffer is used to buffer writes when turned off
buffer []byte
on bool
// history is used to store the scrollback history sent to new clients
history []byte
// incoming is a stream of incoming stdin data
incoming chan []byte
// remaining is a partially read chunk of stdin data
// we only support one concurrent reader so this isn't mutex protected
remaining []byte
readStateUpdate *sync.Cond
closed chan struct{}
lastWasBroadcast bool
terminateNotifier chan struct{}
}
// NewTermManager creates a new TermManager.
func NewTermManager() *TermManager {
return &TermManager{
writers: make(map[string]io.Writer),
readerState: make(map[string]bool),
closed: make(chan struct{}),
readStateUpdate: sync.NewCond(&sync.Mutex{}),
incoming: make(chan []byte, 100),
terminateNotifier: make(chan struct{}, 1),
}
}
// writeToClients writes to underlying clients
func (g *TermManager) writeToClients(p []byte) {
g.lastWasBroadcast = false
g.history = truncateFront(append(g.history, p...), maxHistoryBytes)
atomic.AddUint64(&g.countWritten, uint64(len(p)))
for key, w := range g.writers {
_, err := w.Write(p)
if err != nil {
if err != io.EOF {
log.Warnf("Failed to write to remote terminal: %v", err)
}
// Let term manager decide how to handle broken party writers
if g.OnWriteError != nil {
g.OnWriteError(key, err)
}
delete(g.writers, key)
}
}
}
func (g *TermManager) TerminateNotifier() <-chan struct{} {
return g.terminateNotifier
}
func (g *TermManager) Write(p []byte) (int, error) {
g.mu.Lock()
defer g.mu.Unlock()
if g.isClosed() {
return 0, io.EOF
}
if g.on {
g.writeToClients(p)
} else {
// Only keep the last maxPausedHistoryBytes of stdout/stderr while the session is paused.
// The alternative is flushing to disk but this should be a pretty rare occurrence and shouldn't be an issue in practice.
g.buffer = truncateFront(append(g.buffer, p...), maxPausedHistoryBytes)
}
return len(p), nil
}
func (g *TermManager) Read(p []byte) (int, error) {
if len(g.remaining) > 0 {
n := copy(p, g.remaining)
g.remaining = g.remaining[n:]
return n, nil
}
q := make(chan struct{})
c := make(chan bool)
go func() {
g.readStateUpdate.L.Lock()
defer g.readStateUpdate.L.Unlock()
for {
g.mu.Lock()
on := g.on
g.mu.Unlock()
select {
case c <- on:
case <-q:
close(c)
return
}
g.readStateUpdate.Wait()
}
}()
on := <-c
for {
if !on {
select {
case <-g.closed:
return 0, io.EOF
case on = <-c:
continue
}
}
select {
case <-g.closed:
return 0, io.EOF
case on = <-c:
continue
case g.remaining = <-g.incoming:
close(q)
n := copy(p, g.remaining)
g.remaining = g.remaining[n:]
return n, nil
}
}
}
// BroadcastMessage injects a message into the stream.
func (g *TermManager) BroadcastMessage(message string) {
g.mu.Lock()
defer g.mu.Unlock()
data := []byte("Teleport > " + message + "\r\n")
if g.lastWasBroadcast {
data = append([]byte("\r\n"), data...)
} else {
g.lastWasBroadcast = true
}
g.writeToClients(data)
}
// On allows data to flow through the manager.
func (g *TermManager) On() {
g.mu.Lock()
defer g.mu.Unlock()
g.on = true
g.readStateUpdate.Broadcast()
g.writeToClients(g.buffer)
}
// Off buffers incoming writes and reads until turned on again.
func (g *TermManager) Off() {
g.mu.Lock()
defer g.mu.Unlock()
g.on = false
g.readStateUpdate.Broadcast()
}
func (g *TermManager) AddWriter(name string, w io.Writer) {
g.mu.Lock()
defer g.mu.Unlock()
g.writers[name] = w
}
func (g *TermManager) DeleteWriter(name string) {
g.mu.Lock()
defer g.mu.Unlock()
delete(g.writers, name)
}
func (g *TermManager) AddReader(name string, r io.Reader) {
g.readerState[name] = false
go func() {
for {
buf := make([]byte, 1024)
n, err := r.Read(buf)
if err != nil {
log.Warnf("Failed to read from remote terminal: %v", err)
g.DeleteReader(name)
return
}
for _, b := range buf[:n] {
// This is the ASCII control code for CTRL+C.
if b == 0x03 {
g.mu.Lock()
if !g.on && !g.isClosed() {
select {
case g.terminateNotifier <- struct{}{}:
default:
}
}
g.mu.Unlock()
break
}
}
g.incoming <- buf[:n]
g.mu.Lock()
if g.isClosed() || g.readerState[name] {
g.mu.Unlock()
return
}
g.mu.Unlock()
}
}()
}
func (g *TermManager) DeleteReader(name string) {
g.mu.Lock()
defer g.mu.Unlock()
g.readerState[name] = true
}
func (g *TermManager) CountWritten() uint64 {
return atomic.LoadUint64(&g.countWritten)
}
func (g *TermManager) CountRead() uint64 {
return atomic.LoadUint64(&g.countRead)
}
func (g *TermManager) Close() {
g.mu.Lock()
defer g.mu.Unlock()
if !g.isClosed() {
close(g.closed)
close(g.terminateNotifier)
}
}
func (g *TermManager) isClosed() bool {
select {
case <-g.closed:
return true
default:
return false
}
}
func (g *TermManager) GetRecentHistory() []byte {
g.mu.Lock()
defer g.mu.Unlock()
data := make([]byte, 0, len(g.history))
data = append(data, g.history...)
return data
}
func truncateFront(slice []byte, max int) []byte {
if len(slice) > max {
return slice[len(slice)-max:]
}
return slice
}