forked from mitchellh/go-vnc
-
Notifications
You must be signed in to change notification settings - Fork 16
/
vncclient.go
372 lines (324 loc) · 9.59 KB
/
vncclient.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// VNC client implementation.
package vnc
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"net"
"reflect"
"github.com/golang/glog"
"github.com/kward/go-vnc/go/metrics"
"github.com/kward/go-vnc/logging"
"github.com/kward/go-vnc/messages"
"golang.org/x/net/context"
)
// Connect negotiates a connection to a VNC server.
func Connect(ctx context.Context, c net.Conn, cfg *ClientConfig) (*ClientConn, error) {
conn := NewClientConn(c, cfg)
if err := conn.processContext(ctx); err != nil {
log.Fatalf("invalid context; %s", err)
}
if err := conn.protocolVersionHandshake(ctx); err != nil {
conn.Close()
return nil, err
}
if err := conn.securityHandshake(); err != nil {
conn.Close()
return nil, err
}
if err := conn.securityResultHandshake(); err != nil {
conn.Close()
return nil, err
}
if err := conn.clientInit(); err != nil {
conn.Close()
return nil, err
}
if err := conn.serverInit(); err != nil {
conn.Close()
return nil, err
}
// Send client-to-server messages.
encs := conn.encodings
if err := conn.SetEncodings(encs); err != nil {
conn.Close()
return nil, Errorf("failure calling SetEncodings; %s", err)
}
pf := conn.pixelFormat
if err := conn.SetPixelFormat(pf); err != nil {
conn.Close()
return nil, Errorf("failure calling SetPixelFormat; %s", err)
}
return conn, nil
}
// A ClientConfig structure is used to configure a ClientConn. After
// one has been passed to initialize a connection, it must not be modified.
type ClientConfig struct {
secType uint8 // The negotiated security type.
// A slice of ClientAuth methods. Only the first instance that is
// suitable by the server will be used to authenticate.
Auth []ClientAuth
// Password for servers that require authentication.
Password string
// Exclusive determines whether the connection is shared with other
// clients. If true, then all other clients connected will be
// disconnected when a connection is established to the VNC server.
Exclusive bool
// The channel that all messages received from the server will be
// sent on. If the channel blocks, then the goroutine reading data
// from the VNC server may block indefinitely. It is up to the user
// of the library to ensure that this channel is properly read.
// If this is not set, then all messages will be discarded.
ServerMessageCh chan ServerMessage
// A slice of supported messages that can be read from the server.
// This only needs to contain NEW server messages, and doesn't
// need to explicitly contain the RFC-required messages.
ServerMessages []ServerMessage
}
// NewClientConfig returns a populated ClientConfig.
func NewClientConfig(p string) *ClientConfig {
return &ClientConfig{
Auth: []ClientAuth{
&ClientAuthNone{},
&ClientAuthVNC{p},
},
Password: p,
ServerMessages: []ServerMessage{
&FramebufferUpdate{},
&SetColorMapEntries{},
&Bell{},
&ServerCutText{},
},
}
}
// The ClientConn type holds client connection information.
type ClientConn struct {
c net.Conn
config *ClientConfig
protocolVersion string
// If the pixel format uses a color map, then this is the color
// map that is used. This should not be modified directly, since
// the data comes from the server.
// Definition in §5 - Representation of Pixel Data.
colorMap ColorMap
// Name associated with the desktop, sent from the server.
desktopName string
// Encodings supported by the client. This should not be modified
// directly. Instead, SetEncodings() should be used.
encodings Encodings
// Height of the frame buffer in pixels, sent from the server.
fbHeight uint16
// Width of the frame buffer in pixels, sent from the server.
fbWidth uint16
// The pixel format associated with the connection. This shouldn't
// be modified. If you wish to set a new pixel format, use the
// SetPixelFormat method.
pixelFormat PixelFormat
// Track metrics on system performance.
metrics map[string]metrics.Metric
}
func NewClientConn(c net.Conn, cfg *ClientConfig) *ClientConn {
return &ClientConn{
c: c,
config: cfg,
encodings: Encodings{&RawEncoding{}},
pixelFormat: PixelFormat32bit,
metrics: map[string]metrics.Metric{
"bytes-received": &metrics.Gauge{},
"bytes-sent": &metrics.Gauge{},
},
}
}
// Close a connection to a VNC server.
func (c *ClientConn) Close() error {
log.Print("VNC Client connection closed.")
return c.c.Close()
}
// DesktopName returns the server provided desktop name.
func (c *ClientConn) DesktopName() string {
return c.desktopName
}
// setDesktopName stores the server provided desktop name.
func (c *ClientConn) setDesktopName(name string) {
if logging.V(logging.ResultLevel) {
glog.Infof("desktopName: %s", name)
}
c.desktopName = name
}
// Encodings returns the server provided encodings.
func (c *ClientConn) Encodings() Encodings {
return c.encodings
}
// FramebufferHeight returns the server provided framebuffer height.
func (c *ClientConn) FramebufferHeight() uint16 {
return c.fbHeight
}
// setFramebufferHeight stores the server provided framebuffer height.
func (c *ClientConn) setFramebufferHeight(height uint16) {
if logging.V(logging.ResultLevel) {
glog.Infof("height: %d", height)
}
c.fbHeight = height
}
// FramebufferWidth returns the server provided framebuffer width.
func (c *ClientConn) FramebufferWidth() uint16 {
return c.fbWidth
}
// setFramebufferWidth stores the server provided framebuffer width.
func (c *ClientConn) setFramebufferWidth(width uint16) {
if logging.V(logging.ResultLevel) {
glog.Infof("width: %d", width)
}
c.fbWidth = width
}
// ListenAndHandle listens to a VNC server and handles server messages.
func (c *ClientConn) ListenAndHandle() error {
if logging.V(logging.FnDeclLevel) {
glog.Info(logging.FnName())
}
defer c.Close()
if c.config.ServerMessages == nil {
return NewVNCError("Client config error: ServerMessages undefined")
}
serverMessages := make(map[messages.ServerMessage]ServerMessage)
for _, m := range c.config.ServerMessages {
serverMessages[m.Type()] = m
}
for {
var messageType messages.ServerMessage
if err := c.receive(&messageType); err != nil {
log.Print("error: reading from server")
break
}
if logging.V(logging.ResultLevel) {
glog.Infof("message-type: %s", messageType)
}
msg, ok := serverMessages[messageType]
if !ok {
// Unsupported message type! Bad!
log.Printf("error unsupported message-type: %v", messageType)
break
}
parsedMsg, err := msg.Read(c)
if err != nil {
log.Printf("error parsing message; %v", err)
break
}
if c.config.ServerMessageCh == nil {
log.Print("ignoring message; no server message channel")
continue
}
c.config.ServerMessageCh <- parsedMsg
}
return nil
}
// receive a packet from the network.
func (c *ClientConn) receive(data interface{}) error {
if err := binary.Read(c.c, binary.BigEndian, data); err != nil {
return err
}
c.metrics["bytes-received"].Adjust(int64(binary.Size(data)))
return nil
}
// receiveN receives N packets from the network.
func (c *ClientConn) receiveN(data interface{}, n int) error {
if logging.V(logging.FnDeclLevel) {
glog.Infof("ClientConn.%s", logging.FnName())
}
if n == 0 {
return nil
}
switch data.(type) {
case *[]uint8:
var v uint8
for i := 0; i < n; i++ {
if err := binary.Read(c.c, binary.BigEndian, &v); err != nil {
return err
}
slice := data.(*[]uint8)
*slice = append(*slice, v)
}
case *[]int32:
var v int32
for i := 0; i < n; i++ {
if err := binary.Read(c.c, binary.BigEndian, &v); err != nil {
return err
}
slice := data.(*[]int32)
*slice = append(*slice, v)
}
case *bytes.Buffer:
var v byte
for i := 0; i < n; i++ {
if err := binary.Read(c.c, binary.BigEndian, &v); err != nil {
return err
}
buf := data.(*bytes.Buffer)
buf.WriteByte(v)
}
default:
return NewVNCError(fmt.Sprintf("unrecognized data type %v", reflect.TypeOf(data)))
}
c.metrics["bytes-received"].Adjust(int64(binary.Size(data)))
return nil
}
// send a packet to the network.
func (c *ClientConn) send(data interface{}) error {
if logging.V(logging.SpamLevel) {
glog.Infof("ClientConn.%s", logging.FnNameWithArgs("%v", data))
}
if err := binary.Write(c.c, binary.BigEndian, data); err != nil {
return err
}
c.metrics["bytes-sent"].Adjust(int64(binary.Size(data)))
return nil
}
// sendN sends N packets to the network.
// func (c *ClientConn) sendN(data interface{}, n int) error {
// var buf bytes.Buffer
// switch data := data.(type) {
// case []uint8:
// for _, d := range data {
// if err := binary.Write(&buf, binary.BigEndian, &d); err != nil {
// return err
// }
// }
// case []int32:
// for _, d := range data {
// if err := binary.Write(&buf, binary.BigEndian, &d); err != nil {
// return err
// }
// }
// default:
// return NewVNCError(fmt.Sprintf("unable to send data; unrecognized data type %v", reflect.TypeOf(data)))
// }
// if err := binary.Write(c.c, binary.BigEndian, buf.Bytes()); err != nil {
// return err
// }
// c.metrics["bytes-sent"].Adjust(int64(binary.Size(data)))
// return nil
// }
func (c *ClientConn) processContext(ctx context.Context) error {
if mpv := ctx.Value("vnc_max_proto_version"); mpv != nil && mpv != "" {
log.Printf("vnc_max_proto_version: %v", mpv)
vers := []string{"3.3", "3.8"}
valid := false
for _, v := range vers {
if mpv == v {
valid = true
break
}
}
if !valid {
return fmt.Errorf("Invalid max protocol version %v; supported versions are %v", mpv, vers)
}
}
return nil
}
func (c *ClientConn) DebugMetrics() {
log.Println("Metrics:")
for name, metric := range c.metrics {
log.Printf(" %v: %v", name, metric.Value())
}
}