-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathclient.go
488 lines (441 loc) · 14.4 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//go:build desktop_access_rdp
// +build desktop_access_rdp
/*
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 rdpclient
// Some implementation details that don't belong in the public godoc:
// This package wraps a Rust library based on https://crates.io/crates/rdp-rs.
//
// The Rust library is statically-compiled and called via CGO.
// The Go code sends and receives the CGO versions of Rust RDP events
// https://docs.rs/rdp-rs/0.1.0/rdp/core/event/index.html and translates them
// to the desktop protocol versions.
//
// The flow is roughly this:
// Go Rust
// ==============================================
// rdpclient.New -----------------> connect_rdp
// *connected*
//
// *register output callback*
// -----------------> read_rdp_output
// handleBitmap <----------------
// handleBitmap <----------------
// handleBitmap <----------------
// *output streaming continues...*
//
// *user input messages*
// InputMessage(MouseMove) ------> write_rdp_pointer
// InputMessage(MouseButton) ----> write_rdp_pointer
// InputMessage(KeyboardButton) -> write_rdp_keyboard
// *user input continues...*
//
// *connection closed (client or server side)*
// Wait -----------------> close_rdp
//
/*
// Flags to include the static Rust library.
#cgo linux,386 LDFLAGS: -L${SRCDIR}/../../../../../target/i686-unknown-linux-gnu/release
#cgo linux,amd64 LDFLAGS: -L${SRCDIR}/../../../../../target/x86_64-unknown-linux-gnu/release
#cgo linux,arm LDFLAGS: -L${SRCDIR}/../../../../../target/arm-unknown-linux-gnueabihf/release
#cgo linux,arm64 LDFLAGS: -L${SRCDIR}/../../../../../target/aarch64-unknown-linux-gnu/release
#cgo linux LDFLAGS: -l:librdp_client.a -lpthread -ldl -lm
#cgo darwin,amd64 LDFLAGS: -L${SRCDIR}/../../../../../target/x86_64-apple-darwin/release
#cgo darwin,arm64 LDFLAGS: -L${SRCDIR}/../../../../../target/aarch64-apple-darwin/release
#cgo darwin LDFLAGS: -framework CoreFoundation -framework Security -lrdp_client -lpthread -ldl -lm
#include <librdprs.h>
*/
import "C"
import (
"context"
"errors"
"image"
"io"
"os"
"runtime/cgo"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/gravitational/teleport/lib/srv/desktop/tdp"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
)
func init() {
// initialize the Rust logger by setting $RUST_LOG based
// on the logrus log level
// (unless RUST_LOG is already explicitly set, then we
// assume the user knows what they want)
if rl := os.Getenv("RUST_LOG"); rl == "" {
var rustLogLevel string
switch l := logrus.GetLevel(); l {
case logrus.TraceLevel:
rustLogLevel = "trace"
case logrus.DebugLevel:
rustLogLevel = "debug"
case logrus.InfoLevel:
rustLogLevel = "info"
case logrus.WarnLevel:
rustLogLevel = "warn"
default:
rustLogLevel = "error"
}
os.Setenv("RUST_LOG", rustLogLevel)
}
C.init()
}
// Client is the RDP client.
// It's lifecycle is:
//
// ```
// rdpc := New() // creates client and kicks off RDP connection
// rdpc.Wait() // waits for the duration of the connection
// ```
//
// rdpc.Wait() typically takes care of calling rdpc.Cleanup().
// However, if something fails between the call to New() and
// rdpc.Wait(), the caller MUST call rdpc.Cleanup() to ensure
// all memory is released.
type Client struct {
cfg Config
// Parameters read from the TDP stream.
clientWidth, clientHeight uint16
username string
// handle allows the rust code to call back into the client.
// Once it is created with cgo.NewHandle(), the original caller
// MUST release it with a call to handle.Delete().
handle cgo.Handle
// RDP client on the Rust side.
// Once it is created by assigning this field to the result of C.connect_rdp(),
// the caller SHOULD end the RDP connection by passing it to C.close_rdp(),
// and the caller MUST free its memory by passing it to C.free_rdp().
rustClient *C.Client
// Synchronization point to prevent input messages from being forwarded
// until the connection is established.
// Used with sync/atomic, 0 means false, 1 means true.
readyForInput uint32
// wg is used to wait for the input/output streaming
// goroutines to complete
wg sync.WaitGroup
cleanupOnce sync.Once
clientActivityMu sync.RWMutex
clientLastActive time.Time
}
// New creates and connects a new Client based on cfg.
func New(ctx context.Context, cfg Config) (*Client, error) {
if err := cfg.checkAndSetDefaults(); err != nil {
return nil, err
}
c := &Client{
cfg: cfg,
readyForInput: 0,
}
c.handle = cgo.NewHandle(c)
if err := c.readClientUsername(); err != nil {
return nil, trace.Wrap(err)
}
if err := cfg.AuthorizeFn(c.username); err != nil {
return nil, trace.Wrap(err)
}
if err := c.readClientSize(); err != nil {
return nil, trace.Wrap(err)
}
if err := c.connect(ctx); err != nil {
return nil, trace.Wrap(err)
}
c.start()
return c, nil
}
func (c *Client) readClientUsername() error {
for {
msg, err := c.cfg.Conn.InputMessage()
if err != nil {
return trace.Wrap(err)
}
u, ok := msg.(tdp.ClientUsername)
if !ok {
c.cfg.Log.Debugf("Expected ClientUsername message, got %T", msg)
continue
}
c.cfg.Log.Debugf("Got RDP username %q", u.Username)
c.username = u.Username
return nil
}
}
func (c *Client) readClientSize() error {
for {
msg, err := c.cfg.Conn.InputMessage()
if err != nil {
return trace.Wrap(err)
}
s, ok := msg.(tdp.ClientScreenSpec)
if !ok {
c.cfg.Log.Debugf("Expected ClientScreenSpec message, got %T", msg)
continue
}
c.cfg.Log.Debugf("Got RDP screen size %dx%d", s.Width, s.Height)
c.clientWidth = uint16(s.Width)
c.clientHeight = uint16(s.Height)
return nil
}
}
func (c *Client) connect(ctx context.Context) error {
userCertDER, userKeyDER, err := c.cfg.GenerateUserCert(ctx, c.username, c.cfg.CertTTL)
if err != nil {
return trace.Wrap(err)
}
// Addr and username strings only need to be valid for the duration of
// C.connect_rdp. They are copied on the Rust side and can be freed here.
addr := C.CString(c.cfg.Addr)
defer C.free(unsafe.Pointer(addr))
username := C.CString(c.username)
defer C.free(unsafe.Pointer(username))
res := C.connect_rdp(
C.uintptr_t(c.handle),
addr,
username,
// cert length and bytes.
C.uint32_t(len(userCertDER)),
(*C.uint8_t)(unsafe.Pointer(&userCertDER[0])),
// key length and bytes.
C.uint32_t(len(userKeyDER)),
(*C.uint8_t)(unsafe.Pointer(&userKeyDER[0])),
// screen size.
C.uint16_t(c.clientWidth),
C.uint16_t(c.clientHeight),
C.bool(c.cfg.AllowClipboard),
C.bool(c.cfg.AllowDirectorySharing),
)
if res.err != C.ErrCodeSuccess {
return trace.ConnectionProblem(nil, "RDP connection failed")
}
c.rustClient = res.client
return nil
}
// start kicks off goroutines for input/output streaming and returns right
// away. Use Wait to wait for them to finish.
func (c *Client) start() {
// Video output streaming worker goroutine.
c.wg.Add(1)
go func() {
defer c.wg.Done()
defer c.cfg.Log.Info("RDP output streaming finished")
// C.read_rdp_output blocks for the duration of the RDP connection and
// calls handle_bitmap repeatedly with the incoming bitmaps.
if err := C.read_rdp_output(c.rustClient); err != C.ErrCodeSuccess {
c.cfg.Log.Warningf("Failed reading RDP output frame: %v", err)
// close the TDP connection to the browser
// (without this the input streaming goroutine will hang
// waiting for user input)
c.cfg.Conn.SendError("There was an error reading data from the Windows Desktop")
c.cfg.Conn.Close()
}
}()
// User input streaming worker goroutine.
c.wg.Add(1)
go func() {
defer c.wg.Done()
defer c.cfg.Log.Info("TDP input streaming finished")
// Remember mouse coordinates to send them with all CGOPointer events.
var mouseX, mouseY uint32
for {
msg, err := c.cfg.Conn.InputMessage()
if errors.Is(err, io.EOF) {
return
} else if err != nil {
c.cfg.Log.Warningf("Failed reading TDP input message: %v", err)
return
}
if atomic.LoadUint32(&c.readyForInput) == 0 {
// Input not allowed yet, drop the message.
continue
}
c.UpdateClientActivity()
switch m := msg.(type) {
case tdp.MouseMove:
mouseX, mouseY = m.X, m.Y
if err := C.write_rdp_pointer(
c.rustClient,
C.CGOMousePointerEvent{
x: C.uint16_t(m.X),
y: C.uint16_t(m.Y),
button: C.PointerButtonNone,
wheel: C.PointerWheelNone,
},
); err != C.ErrCodeSuccess {
return
}
case tdp.MouseButton:
// Map the button to a C enum value.
var button C.CGOPointerButton
switch m.Button {
case tdp.LeftMouseButton:
button = C.PointerButtonLeft
case tdp.RightMouseButton:
button = C.PointerButtonRight
case tdp.MiddleMouseButton:
button = C.PointerButtonMiddle
default:
button = C.PointerButtonNone
}
if err := C.write_rdp_pointer(
c.rustClient,
C.CGOMousePointerEvent{
x: C.uint16_t(mouseX),
y: C.uint16_t(mouseY),
button: uint32(button),
down: m.State == tdp.ButtonPressed,
wheel: C.PointerWheelNone,
},
); err != C.ErrCodeSuccess {
return
}
case tdp.MouseWheel:
var wheel C.CGOPointerWheel
switch m.Axis {
case tdp.VerticalWheelAxis:
wheel = C.PointerWheelVertical
case tdp.HorizontalWheelAxis:
wheel = C.PointerWheelHorizontal
// TDP positive scroll deltas move towards top-left.
// RDP positive scroll deltas move towards top-right.
//
// Fix the scroll direction to match TDP, it's inverted for
// horizontal scroll in RDP.
m.Delta = -m.Delta
default:
wheel = C.PointerWheelNone
}
if err := C.write_rdp_pointer(
c.rustClient,
C.CGOMousePointerEvent{
x: C.uint16_t(mouseX),
y: C.uint16_t(mouseY),
button: C.PointerButtonNone,
wheel: uint32(wheel),
wheel_delta: C.int16_t(m.Delta),
},
); err != C.ErrCodeSuccess {
return
}
case tdp.KeyboardButton:
if err := C.write_rdp_keyboard(
c.rustClient,
C.CGOKeyboardEvent{
code: C.uint16_t(m.KeyCode),
down: m.State == tdp.ButtonPressed,
},
); err != C.ErrCodeSuccess {
return
}
case tdp.ClipboardData:
if len(m) > 0 {
if err := C.update_clipboard(
c.rustClient,
(*C.uint8_t)(unsafe.Pointer(&m[0])),
C.uint32_t(len(m)),
); err != C.ErrCodeSuccess {
return
}
} else {
c.cfg.Log.Warning("Recieved an empty clipboard message")
}
default:
c.cfg.Log.Warningf("Skipping unimplemented TDP message type %T", msg)
}
}
}()
}
//export handle_bitmap
func handle_bitmap(handle C.uintptr_t, cb *C.CGOBitmap) C.CGOErrCode {
return cgo.Handle(handle).Value().(*Client).handleBitmap(cb)
}
func (c *Client) handleBitmap(cb *C.CGOBitmap) C.CGOErrCode {
// Notify the input forwarding goroutine that we're ready for input.
// Input can only be sent after connection was established, which we infer
// from the fact that a bitmap was sent.
atomic.StoreUint32(&c.readyForInput, 1)
// use unsafe.Slice here instead of C.GoBytes, because unsafe.Slice
// creates a Go slice backed by data managed from Rust - it does not
// copy. This way we only need one copy into img.Pix below.
ptr := unsafe.Pointer(cb.data_ptr)
uptr := (*uint8)(ptr)
data := unsafe.Slice(uptr, C.int(cb.data_len))
// Convert BGRA to RGBA. It's likely due to Windows using uint32 values for
// pixels (ARGB) and encoding them as big endian. The image.RGBA type uses
// a byte slice with 4-byte segments representing pixels (RGBA).
//
// Also, always force Alpha value to 100% (opaque). On some Windows
// versions it's sent as 0% after decompression for some reason.
for i := 0; i < len(data); i += 4 {
data[i], data[i+2], data[i+3] = data[i+2], data[i], 255
}
img := image.NewNRGBA(image.Rectangle{
Min: image.Pt(int(cb.dest_left), int(cb.dest_top)),
Max: image.Pt(int(cb.dest_right)+1, int(cb.dest_bottom)+1),
})
copy(img.Pix, data)
if err := c.cfg.Conn.OutputMessage(tdp.NewPNG(img, c.cfg.Encoder)); err != nil {
c.cfg.Log.Errorf("failed to send PNG frame %v: %v", img.Rect, err)
return C.ErrCodeFailure
}
return C.ErrCodeSuccess
}
//export handle_remote_copy
func handle_remote_copy(handle C.uintptr_t, data *C.uint8_t, length C.uint32_t) C.CGOErrCode {
goData := C.GoBytes(unsafe.Pointer(data), C.int(length))
return cgo.Handle(handle).Value().(*Client).handleRemoteCopy(goData)
}
// handleRemoteCopy is called from Rust when data is copied
// on the remote desktop
func (c *Client) handleRemoteCopy(data []byte) C.CGOErrCode {
c.cfg.Log.Debugf("Received %d bytes of clipboard data from Windows desktop", len(data))
if err := c.cfg.Conn.OutputMessage(tdp.ClipboardData(data)); err != nil {
c.cfg.Log.Errorf("failed handling remote copy: %v", err)
return C.ErrCodeFailure
}
return C.ErrCodeSuccess
}
// Wait blocks until the client disconnects and runs the cleanup.
func (c *Client) Wait() {
c.wg.Wait()
c.Cleanup()
}
// Cleanup frees the memory of the cgo.Handle, closes the RDP client connection,
// and frees the Rust client.
func (c *Client) Cleanup() {
c.cleanupOnce.Do(func() {
// Release the memory of the cgo.Handle
c.handle.Delete()
// Close the RDP client
if err := C.close_rdp(c.rustClient); err != C.ErrCodeSuccess {
c.cfg.Log.Warningf("failed to close the RDP client")
}
// Let the Rust side free its data
C.free_rdp(c.rustClient)
})
}
// GetClientLastActive returns the time of the last recorded activity.
// For RDP, "activity" is defined as user-input messages
// (mouse move, button press, etc.)
func (c *Client) GetClientLastActive() time.Time {
c.clientActivityMu.RLock()
defer c.clientActivityMu.RUnlock()
return c.clientLastActive
}
// UpdateClientActivity updates the client activity timestamp.
func (c *Client) UpdateClientActivity() {
c.clientActivityMu.Lock()
c.clientLastActive = time.Now().UTC()
c.clientActivityMu.Unlock()
}