forked from saily/vnc2video
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
355 lines (303 loc) · 8.45 KB
/
client.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
package vnc2video
import (
"bufio"
"context"
"encoding/binary"
"fmt"
"net"
"sync"
"vnc2video/logger"
)
var (
// DefaultClientHandlers represents default client handlers
DefaultClientHandlers = []Handler{
&DefaultClientVersionHandler{},
&DefaultClientSecurityHandler{},
&DefaultClientClientInitHandler{},
&DefaultClientServerInitHandler{},
&DefaultClientMessageHandler{},
}
)
// Connect handshake with remote server using underlining net.Conn
func Connect(ctx context.Context, c net.Conn, cfg *ClientConfig) (*ClientConn, error) {
conn, err := NewClientConn(c, cfg)
if err != nil {
conn.Close()
cfg.ErrorCh <- err
return nil, err
}
if len(cfg.Handlers) == 0 {
cfg.Handlers = DefaultClientHandlers
}
for _, h := range cfg.Handlers {
if err := h.Handle(conn); err != nil {
logger.Error("Handshake failed, check that server is running: ", err)
conn.Close()
cfg.ErrorCh <- err
return nil, err
}
}
canvas := NewVncCanvas(int(conn.Width()), int(conn.Height()))
canvas.DrawCursor = cfg.DrawCursor
conn.Canvas = canvas
return conn, nil
}
var _ Conn = (*ClientConn)(nil)
// Config returns connection config
func (c *ClientConn) Config() interface{} {
return c.cfg
}
func (c *ClientConn) GetEncInstance(typ EncodingType) Encoding {
for _, enc := range c.encodings {
if enc.Type() == typ {
return enc
}
}
return nil
}
// Wait waiting for connection close
func (c *ClientConn) Wait() {
<-c.quit
}
// Conn return underlining net.Conn
func (c *ClientConn) Conn() net.Conn {
return c.c
}
// SetProtoVersion sets proto version
func (c *ClientConn) SetProtoVersion(pv string) {
c.protocol = pv
}
// SetEncodings write SetEncodings message
func (c *ClientConn) SetEncodings(encs []EncodingType) error {
msg := &SetEncodings{
EncNum: uint16(len(encs)),
Encodings: encs,
}
return msg.Write(c)
}
// Flush flushes data to conn
func (c *ClientConn) Flush() error {
return c.bw.Flush()
}
// Close closing conn
func (c *ClientConn) Close() error {
if c.quit != nil {
close(c.quit)
c.quit = nil
}
if c.quitCh != nil {
close(c.quitCh)
}
return c.c.Close()
}
// Read reads data from conn
func (c *ClientConn) Read(buf []byte) (int, error) {
return c.br.Read(buf)
}
// Write data to conn must be Flushed
func (c *ClientConn) Write(buf []byte) (int, error) {
return c.bw.Write(buf)
}
// ColorMap returns color map
func (c *ClientConn) ColorMap() ColorMap {
return c.colorMap
}
// SetColorMap sets color map
func (c *ClientConn) SetColorMap(cm ColorMap) {
c.colorMap = cm
}
// DesktopName returns connection desktop name
func (c *ClientConn) DesktopName() []byte {
return c.desktopName
}
// PixelFormat returns connection pixel format
func (c *ClientConn) PixelFormat() PixelFormat {
return c.pixelFormat
}
// SetDesktopName sets desktop name
func (c *ClientConn) SetDesktopName(name []byte) {
c.desktopName = name
}
// SetPixelFormat sets pixel format
func (c *ClientConn) SetPixelFormat(pf PixelFormat) error {
c.pixelFormat = pf
return nil
}
// Encodings returns client encodings
func (c *ClientConn) Encodings() []Encoding {
return c.encodings
}
// Width returns width
func (c *ClientConn) Width() uint16 {
return c.fbWidth
}
// Height returns height
func (c *ClientConn) Height() uint16 {
return c.fbHeight
}
// Protocol returns protocol
func (c *ClientConn) Protocol() string {
return c.protocol
}
// SetWidth sets width of client conn
func (c *ClientConn) SetWidth(width uint16) {
c.fbWidth = width
}
// SetHeight sets height of client conn
func (c *ClientConn) SetHeight(height uint16) {
c.fbHeight = height
}
// SecurityHandler returns security handler
func (c *ClientConn) SecurityHandler() SecurityHandler {
return c.securityHandler
}
// SetSecurityHandler sets security handler
func (c *ClientConn) SetSecurityHandler(sechandler SecurityHandler) error {
c.securityHandler = sechandler
return nil
}
// The ClientConn type holds client connection information
type ClientConn struct {
c net.Conn
br *bufio.Reader
bw *bufio.Writer
cfg *ClientConfig
protocol 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
Canvas *VncCanvas
// Name associated with the desktop, sent from the server.
desktopName []byte
// Encodings supported by the client. This should not be modified
// directly. Instead, SetEncodings() should be used.
encodings []Encoding
securityHandler SecurityHandler
// 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
quitCh chan struct{}
quit chan struct{}
errorCh chan error
}
func (cc *ClientConn) ResetAllEncodings() {
for _, enc := range cc.encodings {
enc.Reset()
}
}
// NewClientConn creates new client conn using config
func NewClientConn(c net.Conn, cfg *ClientConfig) (*ClientConn, error) {
if len(cfg.Encodings) == 0 {
return nil, fmt.Errorf("client can't handle encodings")
}
return &ClientConn{
c: c,
cfg: cfg,
br: bufio.NewReader(c),
bw: bufio.NewWriter(c),
encodings: cfg.Encodings,
quitCh: cfg.QuitCh,
errorCh: cfg.ErrorCh,
pixelFormat: cfg.PixelFormat,
quit: make(chan struct{}),
}, nil
}
// DefaultClientMessageHandler represents default client message handler
type DefaultClientMessageHandler struct{}
// Handle handles server messages.
func (*DefaultClientMessageHandler) Handle(c Conn) error {
logger.Trace("starting DefaultClientMessageHandler")
cfg := c.Config().(*ClientConfig)
var err error
var wg sync.WaitGroup
wg.Add(2)
//defer c.Close()
serverMessages := make(map[ServerMessageType]ServerMessage)
for _, m := range cfg.Messages {
serverMessages[m.Type()] = m
}
go func() {
defer wg.Done()
for {
select {
case msg := <-cfg.ClientMessageCh:
if err = msg.Write(c); err != nil {
cfg.ErrorCh <- err
return
}
}
}
}()
go func() {
defer wg.Done()
for {
select {
default:
var messageType ServerMessageType
if err = binary.Read(c, binary.BigEndian, &messageType); err != nil {
cfg.ErrorCh <- err
return
}
logger.Infof("========got server message, msgType=%d", messageType)
msg, ok := serverMessages[messageType]
if !ok {
err = fmt.Errorf("unknown message-type: %v", messageType)
cfg.ErrorCh <- err
return
}
canvas := c.(*ClientConn).Canvas
canvas.RemoveCursor()
parsedMsg, err := msg.Read(c)
canvas.PaintCursor()
//canvas.SwapBuffers()
logger.Debugf("============== End Message: type=%d ==============", messageType)
if err != nil {
cfg.ErrorCh <- err
return
}
cfg.ServerMessageCh <- parsedMsg
}
}
}()
//encodings := c.Encodings()
encTypes := make(map[EncodingType]EncodingType)
for _, myEnc := range c.Encodings() {
encTypes[myEnc.Type()] = myEnc.Type()
//encTypes = append(encTypes, myEnc.Type())
}
v := make([]EncodingType, 0, len(encTypes))
for _, value := range encTypes {
v = append(v, value)
}
logger.Tracef("setting encodings: %v", v)
c.SetEncodings(v)
firstMsg := FramebufferUpdateRequest{Inc: 0, X: 0, Y: 0, Width: c.Width(), Height: c.Height()}
logger.Tracef("sending initial req message: %v", firstMsg)
firstMsg.Write(c)
//wg.Wait()
return 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 {
Handlers []Handler
SecurityHandlers []SecurityHandler
Encodings []Encoding
PixelFormat PixelFormat
ColorMap ColorMap
ClientMessageCh chan ClientMessage
ServerMessageCh chan ServerMessage
Exclusive bool
DrawCursor bool
Messages []ServerMessage
QuitCh chan struct{}
ErrorCh chan error
quit chan struct{}
}