forked from wwt/guac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.go
274 lines (231 loc) · 6.41 KB
/
stream.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
package guac
import (
"fmt"
"net"
"time"
"github.com/sirupsen/logrus"
)
const (
SocketTimeout = 15 * time.Second
MaxGuacMessage = 8192 // TODO is this bytes or runes?
)
// Stream wraps the connection to Guacamole providing timeouts and reading
// a single instruction at a time (since returning partial instructions
// would be an error)
type Stream struct {
conn net.Conn
// ConnectionID is the ID Guacamole gives and can be used to reconnect or share sessions
ConnectionID string
timeout time.Duration
// if more than a single instruction is read, the rest are buffered here
parseStart int
buffer []rune
reset []rune
}
// NewStream creates a new stream
func NewStream(conn net.Conn, timeout time.Duration) (ret *Stream) {
buffer := make([]rune, 0, MaxGuacMessage*3)
return &Stream{
conn: conn,
timeout: timeout,
buffer: buffer,
reset: buffer[:cap(buffer)],
}
}
// Write sends messages to Guacamole with a timeout
func (s *Stream) Write(data []byte) (n int, err error) {
if err = s.conn.SetWriteDeadline(time.Now().Add(s.timeout)); err != nil {
logrus.Error(err)
return
}
return s.conn.Write(data)
}
// Available returns true if there are messages buffered
func (s *Stream) Available() bool {
return len(s.buffer) > 0
}
// Flush resets the internal buffer
func (s *Stream) Flush() {
copy(s.reset, s.buffer)
s.buffer = s.reset[:len(s.buffer)]
}
// ReadSome takes the next instruction (from the network or from the buffer) and returns it.
// io.Reader is not implemented because this seems like the right place to maintain a buffer.
func (s *Stream) ReadSome() (instruction []byte, err error) {
if err = s.conn.SetReadDeadline(time.Now().Add(s.timeout)); err != nil {
logrus.Error(err)
return
}
buffer := make([]byte, MaxGuacMessage)
var n int
// While we're blocking, or input is available
for {
// Length of element
var elementLength int
// Resume where we left off
i := s.parseStart
parseLoop:
// Parse instruction in buffer
for i < len(s.buffer) {
// ReadSome character
readChar := s.buffer[i]
i++
switch readChar {
// If digit, update length
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
elementLength = elementLength*10 + int(readChar-'0')
// If not digit, check for end-of-length character
case '.':
if i+elementLength >= len(s.buffer) {
// break for i < s.usedLength { ... }
// Otherwise, read more data
break parseLoop
}
// Check if element present in buffer
terminator := s.buffer[i+elementLength]
// Move to character after terminator
i += elementLength + 1
// Reset length
elementLength = 0
// Continue here if necessary
s.parseStart = i
// If terminator is semicolon, we have a full
// instruction.
switch terminator {
case ';':
instruction = []byte(string(s.buffer[0:i]))
s.parseStart = 0
s.buffer = s.buffer[i:]
return
case ',':
// keep going
default:
err = ErrServer.NewError("Element terminator of instruction was not ';' nor ','")
return
}
default:
// Otherwise, parse error
err = ErrServer.NewError("Non-numeric character in element length:", string(readChar))
return
}
}
n, err = s.conn.Read(buffer)
if err != nil && n == 0 {
switch err.(type) {
case net.Error:
ex := err.(net.Error)
if ex.Timeout() {
err = ErrUpstreamTimeout.NewError("Connection to guacd timed out.", err.Error())
} else {
err = ErrConnectionClosed.NewError("Connection to guacd is closed.", err.Error())
}
default:
err = ErrServer.NewError(err.Error())
}
return
}
if n == 0 {
err = ErrServer.NewError("read 0 bytes")
}
runes := []rune(string(buffer[:n]))
if cap(s.buffer)-len(s.buffer) < len(runes) {
s.Flush()
}
n = copy(s.buffer[len(s.buffer):cap(s.buffer)], runes)
// must reslice so len is changed
s.buffer = s.buffer[:len(s.buffer)+n]
}
}
// Close closes the underlying network connection
func (s *Stream) Close() error {
return s.conn.Close()
}
// Handshake configures the guacd session
func (s *Stream) Handshake(config *Config) error {
// Get protocol / connection ID
selectArg := config.ConnectionID
if len(selectArg) == 0 {
selectArg = config.Protocol
}
// Send requested protocol or connection ID
_, err := s.Write(NewInstruction("select", selectArg).Byte())
if err != nil {
return err
}
// Wait for server Args
args, err := s.AssertOpcode("args")
if err != nil {
return err
}
// Build Args list off provided names and config
argNameS := args.Args
argValueS := make([]string, 0, len(argNameS))
for _, argName := range argNameS {
// Retrieve argument name
// Get defined value for name
value := config.Parameters[argName]
// If value defined, set that value
if len(value) == 0 {
value = ""
}
argValueS = append(argValueS, value)
}
// Send size
_, err = s.Write(NewInstruction("size",
fmt.Sprintf("%v", config.OptimalScreenWidth),
fmt.Sprintf("%v", config.OptimalScreenHeight),
fmt.Sprintf("%v", config.OptimalResolution)).Byte(),
)
if err != nil {
return err
}
// Send supported audio formats
_, err = s.Write(NewInstruction("audio", config.AudioMimetypes...).Byte())
if err != nil {
return err
}
// Send supported video formats
_, err = s.Write(NewInstruction("video", config.VideoMimetypes...).Byte())
if err != nil {
return err
}
// Send supported image formats
_, err = s.Write(NewInstruction("image", config.ImageMimetypes...).Byte())
if err != nil {
return err
}
// Send Args
_, err = s.Write(NewInstruction("connect", argValueS...).Byte())
if err != nil {
return err
}
// Wait for ready, store ID
ready, err := s.AssertOpcode("ready")
if err != nil {
return err
}
readyArgs := ready.Args
if len(readyArgs) == 0 {
err = ErrServer.NewError("No connection ID received")
return err
}
s.Flush()
s.ConnectionID = readyArgs[0]
return nil
}
// AssertOpcode checks the next opcode in the stream matches what is expected. Useful during handshake.
func (s *Stream) AssertOpcode(opcode string) (instruction *Instruction, err error) {
instruction, err = ReadOne(s)
if err != nil {
return
}
if len(instruction.Opcode) == 0 {
err = ErrServer.NewError("End of stream while waiting for \"" + opcode + "\".")
return
}
if instruction.Opcode != opcode {
err = ErrServer.NewError("Expected \"" + opcode + "\" instruction but instead received \"" + instruction.Opcode + "\".")
return
}
return
}