@novnc/novnc 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/core/base64.js +104 -0
  2. package/core/crypto/aes.js +178 -0
  3. package/core/crypto/bigint.js +34 -0
  4. package/core/crypto/crypto.js +90 -0
  5. package/core/crypto/des.js +330 -0
  6. package/core/crypto/dh.js +55 -0
  7. package/core/crypto/md5.js +82 -0
  8. package/core/crypto/rsa.js +132 -0
  9. package/core/decoders/copyrect.js +27 -0
  10. package/core/decoders/h264.js +321 -0
  11. package/core/decoders/hextile.js +181 -0
  12. package/core/decoders/jpeg.js +161 -0
  13. package/core/decoders/raw.js +59 -0
  14. package/core/decoders/rre.js +44 -0
  15. package/core/decoders/tight.js +393 -0
  16. package/core/decoders/tightpng.js +27 -0
  17. package/core/decoders/zlib.js +51 -0
  18. package/core/decoders/zrle.js +185 -0
  19. package/core/deflator.js +84 -0
  20. package/core/display.js +578 -0
  21. package/core/encodings.js +54 -0
  22. package/core/inflator.js +65 -0
  23. package/core/input/domkeytable.js +311 -0
  24. package/core/input/fixedkeys.js +129 -0
  25. package/core/input/gesturehandler.js +567 -0
  26. package/core/input/keyboard.js +294 -0
  27. package/core/input/keysym.js +616 -0
  28. package/core/input/keysymdef.js +688 -0
  29. package/core/input/util.js +191 -0
  30. package/core/input/vkeys.js +116 -0
  31. package/core/input/xtscancodes.js +173 -0
  32. package/core/ra2.js +312 -0
  33. package/core/rfb.js +3411 -0
  34. package/core/util/browser.js +233 -0
  35. package/core/util/cursor.js +249 -0
  36. package/core/util/element.js +32 -0
  37. package/core/util/events.js +138 -0
  38. package/core/util/eventtarget.js +35 -0
  39. package/core/util/int.js +15 -0
  40. package/core/util/logging.js +56 -0
  41. package/core/util/strings.js +28 -0
  42. package/core/websock.js +369 -0
  43. package/docs/API.md +0 -5
  44. package/package.json +6 -10
  45. package/vendor/pako/LICENSE +21 -0
  46. package/vendor/pako/README.md +6 -0
  47. package/{lib/vendor → vendor}/pako/lib/utils/common.js +13 -23
  48. package/{lib/vendor → vendor}/pako/lib/zlib/adler32.js +12 -14
  49. package/vendor/pako/lib/zlib/constants.js +47 -0
  50. package/{lib/vendor → vendor}/pako/lib/zlib/crc32.js +15 -14
  51. package/{lib/vendor → vendor}/pako/lib/zlib/deflate.js +459 -334
  52. package/{lib/vendor → vendor}/pako/lib/zlib/gzheader.js +13 -19
  53. package/{lib/vendor → vendor}/pako/lib/zlib/inffast.js +116 -119
  54. package/vendor/pako/lib/zlib/inflate.js +1527 -0
  55. package/{lib/vendor → vendor}/pako/lib/zlib/inftrees.js +103 -91
  56. package/vendor/pako/lib/zlib/messages.js +11 -0
  57. package/{lib/vendor → vendor}/pako/lib/zlib/trees.js +313 -268
  58. package/{lib/vendor → vendor}/pako/lib/zlib/zstream.js +4 -10
  59. package/lib/base64.js +0 -100
  60. package/lib/crypto/aes.js +0 -481
  61. package/lib/crypto/bigint.js +0 -41
  62. package/lib/crypto/crypto.js +0 -109
  63. package/lib/crypto/des.js +0 -374
  64. package/lib/crypto/dh.js +0 -81
  65. package/lib/crypto/md5.js +0 -97
  66. package/lib/crypto/rsa.js +0 -312
  67. package/lib/decoders/copyrect.js +0 -40
  68. package/lib/decoders/h264.js +0 -349
  69. package/lib/decoders/hextile.js +0 -195
  70. package/lib/decoders/jpeg.js +0 -175
  71. package/lib/decoders/raw.js +0 -66
  72. package/lib/decoders/rre.js +0 -52
  73. package/lib/decoders/tight.js +0 -363
  74. package/lib/decoders/tightpng.js +0 -51
  75. package/lib/decoders/zlib.js +0 -57
  76. package/lib/decoders/zrle.js +0 -192
  77. package/lib/deflator.js +0 -88
  78. package/lib/display.js +0 -588
  79. package/lib/encodings.js +0 -70
  80. package/lib/inflator.js +0 -77
  81. package/lib/input/domkeytable.js +0 -313
  82. package/lib/input/fixedkeys.js +0 -127
  83. package/lib/input/gesturehandler.js +0 -573
  84. package/lib/input/keyboard.js +0 -293
  85. package/lib/input/keysym.js +0 -878
  86. package/lib/input/keysymdef.js +0 -1351
  87. package/lib/input/util.js +0 -217
  88. package/lib/input/vkeys.js +0 -121
  89. package/lib/input/xtscancodes.js +0 -343
  90. package/lib/ra2.js +0 -535
  91. package/lib/rfb.js +0 -3398
  92. package/lib/util/browser.js +0 -239
  93. package/lib/util/cursor.js +0 -269
  94. package/lib/util/element.js +0 -41
  95. package/lib/util/events.js +0 -133
  96. package/lib/util/eventtarget.js +0 -53
  97. package/lib/util/int.js +0 -21
  98. package/lib/util/logging.js +0 -56
  99. package/lib/util/strings.js +0 -36
  100. package/lib/vendor/pako/lib/zlib/constants.js +0 -47
  101. package/lib/vendor/pako/lib/zlib/inflate.js +0 -1602
  102. package/lib/vendor/pako/lib/zlib/messages.js +0 -25
  103. package/lib/websock.js +0 -395
package/core/rfb.js ADDED
@@ -0,0 +1,3411 @@
1
+ /*
2
+ * noVNC: HTML5 VNC client
3
+ * Copyright (C) 2020 The noVNC authors
4
+ * Licensed under MPL 2.0 (see LICENSE.txt)
5
+ *
6
+ * See README.md for usage and integration instructions.
7
+ *
8
+ */
9
+
10
+ import { toUnsigned32bit, toSigned32bit } from './util/int.js';
11
+ import * as Log from './util/logging.js';
12
+ import { encodeUTF8, decodeUTF8 } from './util/strings.js';
13
+ import { dragThreshold, supportsWebCodecsH264Decode } from './util/browser.js';
14
+ import { clientToElement } from './util/element.js';
15
+ import { setCapture } from './util/events.js';
16
+ import EventTargetMixin from './util/eventtarget.js';
17
+ import Display from "./display.js";
18
+ import Inflator from "./inflator.js";
19
+ import Deflator from "./deflator.js";
20
+ import Keyboard from "./input/keyboard.js";
21
+ import GestureHandler from "./input/gesturehandler.js";
22
+ import Cursor from "./util/cursor.js";
23
+ import Websock from "./websock.js";
24
+ import KeyTable from "./input/keysym.js";
25
+ import XtScancode from "./input/xtscancodes.js";
26
+ import { encodings } from "./encodings.js";
27
+ import RSAAESAuthenticationState from "./ra2.js";
28
+ import legacyCrypto from "./crypto/crypto.js";
29
+
30
+ import RawDecoder from "./decoders/raw.js";
31
+ import CopyRectDecoder from "./decoders/copyrect.js";
32
+ import RREDecoder from "./decoders/rre.js";
33
+ import HextileDecoder from "./decoders/hextile.js";
34
+ import ZlibDecoder from './decoders/zlib.js';
35
+ import TightDecoder from "./decoders/tight.js";
36
+ import TightPNGDecoder from "./decoders/tightpng.js";
37
+ import ZRLEDecoder from "./decoders/zrle.js";
38
+ import JPEGDecoder from "./decoders/jpeg.js";
39
+ import H264Decoder from "./decoders/h264.js";
40
+
41
+ // How many seconds to wait for a disconnect to finish
42
+ const DISCONNECT_TIMEOUT = 3;
43
+ const DEFAULT_BACKGROUND = 'rgb(40, 40, 40)';
44
+
45
+ // Minimum wait (ms) between two mouse moves
46
+ const MOUSE_MOVE_DELAY = 17;
47
+
48
+ // Wheel thresholds
49
+ const WHEEL_STEP = 50; // Pixels needed for one step
50
+ const WHEEL_LINE_HEIGHT = 19; // Assumed pixels for one line step
51
+
52
+ // Gesture thresholds
53
+ const GESTURE_ZOOMSENS = 75;
54
+ const GESTURE_SCRLSENS = 50;
55
+ const DOUBLE_TAP_TIMEOUT = 1000;
56
+ const DOUBLE_TAP_THRESHOLD = 50;
57
+
58
+ // Security types
59
+ const securityTypeNone = 1;
60
+ const securityTypeVNCAuth = 2;
61
+ const securityTypeRA2ne = 6;
62
+ const securityTypeTight = 16;
63
+ const securityTypeVeNCrypt = 19;
64
+ const securityTypeXVP = 22;
65
+ const securityTypeARD = 30;
66
+ const securityTypeMSLogonII = 113;
67
+
68
+ // Special Tight security types
69
+ const securityTypeUnixLogon = 129;
70
+
71
+ // VeNCrypt security types
72
+ const securityTypePlain = 256;
73
+
74
+ // Extended clipboard pseudo-encoding formats
75
+ const extendedClipboardFormatText = 1;
76
+ /*eslint-disable no-unused-vars */
77
+ const extendedClipboardFormatRtf = 1 << 1;
78
+ const extendedClipboardFormatHtml = 1 << 2;
79
+ const extendedClipboardFormatDib = 1 << 3;
80
+ const extendedClipboardFormatFiles = 1 << 4;
81
+ /*eslint-enable */
82
+
83
+ // Extended clipboard pseudo-encoding actions
84
+ const extendedClipboardActionCaps = 1 << 24;
85
+ const extendedClipboardActionRequest = 1 << 25;
86
+ const extendedClipboardActionPeek = 1 << 26;
87
+ const extendedClipboardActionNotify = 1 << 27;
88
+ const extendedClipboardActionProvide = 1 << 28;
89
+
90
+ export default class RFB extends EventTargetMixin {
91
+ constructor(target, urlOrChannel, options) {
92
+ if (!target) {
93
+ throw new Error("Must specify target");
94
+ }
95
+ if (!urlOrChannel) {
96
+ throw new Error("Must specify URL, WebSocket or RTCDataChannel");
97
+ }
98
+
99
+ // We rely on modern APIs which might not be available in an
100
+ // insecure context
101
+ if (!window.isSecureContext) {
102
+ Log.Error("noVNC requires a secure context (TLS). Expect crashes!");
103
+ }
104
+
105
+ super();
106
+
107
+ this._target = target;
108
+
109
+ if (typeof urlOrChannel === "string") {
110
+ this._url = urlOrChannel;
111
+ } else {
112
+ this._url = null;
113
+ this._rawChannel = urlOrChannel;
114
+ }
115
+
116
+ // Connection details
117
+ options = options || {};
118
+ this._rfbCredentials = options.credentials || {};
119
+ this._shared = 'shared' in options ? !!options.shared : true;
120
+ this._repeaterID = options.repeaterID || '';
121
+ this._wsProtocols = options.wsProtocols || [];
122
+
123
+ // Internal state
124
+ this._rfbConnectionState = '';
125
+ this._rfbInitState = '';
126
+ this._rfbAuthScheme = -1;
127
+ this._rfbCleanDisconnect = true;
128
+ this._rfbRSAAESAuthenticationState = null;
129
+
130
+ // Server capabilities
131
+ this._rfbVersion = 0;
132
+ this._rfbMaxVersion = 3.8;
133
+ this._rfbTightVNC = false;
134
+ this._rfbVeNCryptState = 0;
135
+ this._rfbXvpVer = 0;
136
+
137
+ this._fbWidth = 0;
138
+ this._fbHeight = 0;
139
+
140
+ this._fbName = "";
141
+
142
+ this._capabilities = { power: false };
143
+
144
+ this._supportsFence = false;
145
+
146
+ this._supportsContinuousUpdates = false;
147
+ this._enabledContinuousUpdates = false;
148
+
149
+ this._supportsSetDesktopSize = false;
150
+ this._screenID = 0;
151
+ this._screenFlags = 0;
152
+ this._pendingRemoteResize = false;
153
+ this._lastResize = 0;
154
+
155
+ this._qemuExtKeyEventSupported = false;
156
+
157
+ this._extendedPointerEventSupported = false;
158
+
159
+ this._clipboardText = null;
160
+ this._clipboardServerCapabilitiesActions = {};
161
+ this._clipboardServerCapabilitiesFormats = {};
162
+
163
+ // Internal objects
164
+ this._sock = null; // Websock object
165
+ this._display = null; // Display object
166
+ this._flushing = false; // Display flushing state
167
+ this._keyboard = null; // Keyboard input handler object
168
+ this._gestures = null; // Gesture input handler object
169
+ this._resizeObserver = null; // Resize observer object
170
+
171
+ // Timers
172
+ this._disconnTimer = null; // disconnection timer
173
+ this._resizeTimeout = null; // resize rate limiting
174
+ this._mouseMoveTimer = null;
175
+
176
+ // Decoder states
177
+ this._decoders = {};
178
+
179
+ this._FBU = {
180
+ rects: 0,
181
+ x: 0,
182
+ y: 0,
183
+ width: 0,
184
+ height: 0,
185
+ encoding: null,
186
+ };
187
+
188
+ // Mouse state
189
+ this._mousePos = {};
190
+ this._mouseButtonMask = 0;
191
+ this._mouseLastMoveTime = 0;
192
+ this._viewportDragging = false;
193
+ this._viewportDragPos = {};
194
+ this._viewportHasMoved = false;
195
+ this._accumulatedWheelDeltaX = 0;
196
+ this._accumulatedWheelDeltaY = 0;
197
+
198
+ // Gesture state
199
+ this._gestureLastTapTime = null;
200
+ this._gestureFirstDoubleTapEv = null;
201
+ this._gestureLastMagnitudeX = 0;
202
+ this._gestureLastMagnitudeY = 0;
203
+
204
+ // Bound event handlers
205
+ this._eventHandlers = {
206
+ focusCanvas: this._focusCanvas.bind(this),
207
+ handleResize: this._handleResize.bind(this),
208
+ handleMouse: this._handleMouse.bind(this),
209
+ handleWheel: this._handleWheel.bind(this),
210
+ handleGesture: this._handleGesture.bind(this),
211
+ handleRSAAESCredentialsRequired: this._handleRSAAESCredentialsRequired.bind(this),
212
+ handleRSAAESServerVerification: this._handleRSAAESServerVerification.bind(this),
213
+ };
214
+
215
+ // main setup
216
+ Log.Debug(">> RFB.constructor");
217
+
218
+ // Create DOM elements
219
+ this._screen = document.createElement('div');
220
+ this._screen.style.display = 'flex';
221
+ this._screen.style.width = '100%';
222
+ this._screen.style.height = '100%';
223
+ this._screen.style.overflow = 'auto';
224
+ this._screen.style.background = DEFAULT_BACKGROUND;
225
+ this._canvas = document.createElement('canvas');
226
+ this._canvas.style.margin = 'auto';
227
+ // Some browsers add an outline on focus
228
+ this._canvas.style.outline = 'none';
229
+ this._canvas.width = 0;
230
+ this._canvas.height = 0;
231
+ this._canvas.tabIndex = -1;
232
+ this._screen.appendChild(this._canvas);
233
+
234
+ // Cursor
235
+ this._cursor = new Cursor();
236
+
237
+ // XXX: TightVNC 2.8.11 sends no cursor at all until Windows changes
238
+ // it. Result: no cursor at all until a window border or an edit field
239
+ // is hit blindly. But there are also VNC servers that draw the cursor
240
+ // in the framebuffer and don't send the empty local cursor. There is
241
+ // no way to satisfy both sides.
242
+ //
243
+ // The spec is unclear on this "initial cursor" issue. Many other
244
+ // viewers (TigerVNC, RealVNC, Remmina) display an arrow as the
245
+ // initial cursor instead.
246
+ this._cursorImage = RFB.cursors.none;
247
+
248
+ // populate decoder array with objects
249
+ this._decoders[encodings.encodingRaw] = new RawDecoder();
250
+ this._decoders[encodings.encodingCopyRect] = new CopyRectDecoder();
251
+ this._decoders[encodings.encodingRRE] = new RREDecoder();
252
+ this._decoders[encodings.encodingHextile] = new HextileDecoder();
253
+ this._decoders[encodings.encodingZlib] = new ZlibDecoder();
254
+ this._decoders[encodings.encodingTight] = new TightDecoder();
255
+ this._decoders[encodings.encodingTightPNG] = new TightPNGDecoder();
256
+ this._decoders[encodings.encodingZRLE] = new ZRLEDecoder();
257
+ this._decoders[encodings.encodingJPEG] = new JPEGDecoder();
258
+ this._decoders[encodings.encodingH264] = new H264Decoder();
259
+
260
+ // NB: nothing that needs explicit teardown should be done
261
+ // before this point, since this can throw an exception
262
+ try {
263
+ this._display = new Display(this._canvas);
264
+ } catch (exc) {
265
+ Log.Error("Display exception: " + exc);
266
+ throw exc;
267
+ }
268
+
269
+ this._keyboard = new Keyboard(this._canvas);
270
+ this._keyboard.onkeyevent = this._handleKeyEvent.bind(this);
271
+ this._remoteCapsLock = null; // Null indicates unknown or irrelevant
272
+ this._remoteNumLock = null;
273
+
274
+ this._gestures = new GestureHandler();
275
+
276
+ this._sock = new Websock();
277
+ this._sock.on('open', this._socketOpen.bind(this));
278
+ this._sock.on('close', this._socketClose.bind(this));
279
+ this._sock.on('message', this._handleMessage.bind(this));
280
+ this._sock.on('error', this._socketError.bind(this));
281
+
282
+ this._expectedClientWidth = null;
283
+ this._expectedClientHeight = null;
284
+ this._resizeObserver = new ResizeObserver(this._eventHandlers.handleResize);
285
+
286
+ // All prepared, kick off the connection
287
+ this._updateConnectionState('connecting');
288
+
289
+ Log.Debug("<< RFB.constructor");
290
+
291
+ // ===== PROPERTIES =====
292
+
293
+ this.dragViewport = false;
294
+ this.focusOnClick = true;
295
+
296
+ this._viewOnly = false;
297
+ this._clipViewport = false;
298
+ this._clippingViewport = false;
299
+ this._scaleViewport = false;
300
+ this._resizeSession = false;
301
+
302
+ this._showDotCursor = false;
303
+
304
+ this._qualityLevel = 6;
305
+ this._compressionLevel = 2;
306
+ }
307
+
308
+ // ===== PROPERTIES =====
309
+
310
+ get viewOnly() { return this._viewOnly; }
311
+ set viewOnly(viewOnly) {
312
+ this._viewOnly = viewOnly;
313
+
314
+ if (this._rfbConnectionState === "connecting" ||
315
+ this._rfbConnectionState === "connected") {
316
+ if (viewOnly) {
317
+ this._keyboard.ungrab();
318
+ } else {
319
+ this._keyboard.grab();
320
+ }
321
+ }
322
+ }
323
+
324
+ get capabilities() { return this._capabilities; }
325
+
326
+ get clippingViewport() { return this._clippingViewport; }
327
+ _setClippingViewport(on) {
328
+ if (on === this._clippingViewport) {
329
+ return;
330
+ }
331
+ this._clippingViewport = on;
332
+ this.dispatchEvent(new CustomEvent("clippingviewport",
333
+ { detail: this._clippingViewport }));
334
+ }
335
+
336
+ get touchButton() { return 0; }
337
+ set touchButton(button) { Log.Warn("Using old API!"); }
338
+
339
+ get clipViewport() { return this._clipViewport; }
340
+ set clipViewport(viewport) {
341
+ this._clipViewport = viewport;
342
+ this._updateClip();
343
+ }
344
+
345
+ get scaleViewport() { return this._scaleViewport; }
346
+ set scaleViewport(scale) {
347
+ this._scaleViewport = scale;
348
+ // Scaling trumps clipping, so we may need to adjust
349
+ // clipping when enabling or disabling scaling
350
+ if (scale && this._clipViewport) {
351
+ this._updateClip();
352
+ }
353
+ this._updateScale();
354
+ if (!scale && this._clipViewport) {
355
+ this._updateClip();
356
+ }
357
+ }
358
+
359
+ get resizeSession() { return this._resizeSession; }
360
+ set resizeSession(resize) {
361
+ this._resizeSession = resize;
362
+ if (resize) {
363
+ this._requestRemoteResize();
364
+ }
365
+ }
366
+
367
+ get showDotCursor() { return this._showDotCursor; }
368
+ set showDotCursor(show) {
369
+ this._showDotCursor = show;
370
+ this._refreshCursor();
371
+ }
372
+
373
+ get background() { return this._screen.style.background; }
374
+ set background(cssValue) { this._screen.style.background = cssValue; }
375
+
376
+ get qualityLevel() {
377
+ return this._qualityLevel;
378
+ }
379
+ set qualityLevel(qualityLevel) {
380
+ if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) {
381
+ Log.Error("qualityLevel must be an integer between 0 and 9");
382
+ return;
383
+ }
384
+
385
+ if (this._qualityLevel === qualityLevel) {
386
+ return;
387
+ }
388
+
389
+ this._qualityLevel = qualityLevel;
390
+
391
+ if (this._rfbConnectionState === 'connected') {
392
+ this._sendEncodings();
393
+ }
394
+ }
395
+
396
+ get compressionLevel() {
397
+ return this._compressionLevel;
398
+ }
399
+ set compressionLevel(compressionLevel) {
400
+ if (!Number.isInteger(compressionLevel) || compressionLevel < 0 || compressionLevel > 9) {
401
+ Log.Error("compressionLevel must be an integer between 0 and 9");
402
+ return;
403
+ }
404
+
405
+ if (this._compressionLevel === compressionLevel) {
406
+ return;
407
+ }
408
+
409
+ this._compressionLevel = compressionLevel;
410
+
411
+ if (this._rfbConnectionState === 'connected') {
412
+ this._sendEncodings();
413
+ }
414
+ }
415
+
416
+ // ===== PUBLIC METHODS =====
417
+
418
+ disconnect() {
419
+ this._updateConnectionState('disconnecting');
420
+ this._sock.off('error');
421
+ this._sock.off('message');
422
+ this._sock.off('open');
423
+ if (this._rfbRSAAESAuthenticationState !== null) {
424
+ this._rfbRSAAESAuthenticationState.disconnect();
425
+ }
426
+ }
427
+
428
+ approveServer() {
429
+ if (this._rfbRSAAESAuthenticationState !== null) {
430
+ this._rfbRSAAESAuthenticationState.approveServer();
431
+ }
432
+ }
433
+
434
+ sendCredentials(creds) {
435
+ this._rfbCredentials = creds;
436
+ this._resumeAuthentication();
437
+ }
438
+
439
+ sendCtrlAltDel() {
440
+ if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; }
441
+ Log.Info("Sending Ctrl-Alt-Del");
442
+
443
+ this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true);
444
+ this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true);
445
+ this.sendKey(KeyTable.XK_Delete, "Delete", true);
446
+ this.sendKey(KeyTable.XK_Delete, "Delete", false);
447
+ this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false);
448
+ this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false);
449
+ }
450
+
451
+ machineShutdown() {
452
+ this._xvpOp(1, 2);
453
+ }
454
+
455
+ machineReboot() {
456
+ this._xvpOp(1, 3);
457
+ }
458
+
459
+ machineReset() {
460
+ this._xvpOp(1, 4);
461
+ }
462
+
463
+ // Send a key press. If 'down' is not specified then send a down key
464
+ // followed by an up key.
465
+ sendKey(keysym, code, down) {
466
+ if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; }
467
+
468
+ if (down === undefined) {
469
+ this.sendKey(keysym, code, true);
470
+ this.sendKey(keysym, code, false);
471
+ return;
472
+ }
473
+
474
+ const scancode = XtScancode[code];
475
+
476
+ if (this._qemuExtKeyEventSupported && scancode) {
477
+ // 0 is NoSymbol
478
+ keysym = keysym || 0;
479
+
480
+ Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode);
481
+
482
+ RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode);
483
+ } else {
484
+ if (!keysym) {
485
+ return;
486
+ }
487
+ Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym);
488
+ RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0);
489
+ }
490
+ }
491
+
492
+ focus(options) {
493
+ this._canvas.focus(options);
494
+ }
495
+
496
+ blur() {
497
+ this._canvas.blur();
498
+ }
499
+
500
+ clipboardPasteFrom(text) {
501
+ if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; }
502
+
503
+ if (this._clipboardServerCapabilitiesFormats[extendedClipboardFormatText] &&
504
+ this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) {
505
+
506
+ this._clipboardText = text;
507
+ RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]);
508
+ } else {
509
+ let length, i;
510
+ let data;
511
+
512
+ length = 0;
513
+ // eslint-disable-next-line no-unused-vars
514
+ for (let codePoint of text) {
515
+ length++;
516
+ }
517
+
518
+ data = new Uint8Array(length);
519
+
520
+ i = 0;
521
+ for (let codePoint of text) {
522
+ let code = codePoint.codePointAt(0);
523
+
524
+ /* Only ISO 8859-1 is supported */
525
+ if (code > 0xff) {
526
+ code = 0x3f; // '?'
527
+ }
528
+
529
+ data[i++] = code;
530
+ }
531
+
532
+ RFB.messages.clientCutText(this._sock, data);
533
+ }
534
+ }
535
+
536
+ getImageData() {
537
+ return this._display.getImageData();
538
+ }
539
+
540
+ toDataURL(type, encoderOptions) {
541
+ return this._display.toDataURL(type, encoderOptions);
542
+ }
543
+
544
+ toBlob(callback, type, quality) {
545
+ return this._display.toBlob(callback, type, quality);
546
+ }
547
+
548
+ // ===== PRIVATE METHODS =====
549
+
550
+ _connect() {
551
+ Log.Debug(">> RFB.connect");
552
+
553
+ if (this._url) {
554
+ Log.Info(`connecting to ${this._url}`);
555
+ this._sock.open(this._url, this._wsProtocols);
556
+ } else {
557
+ Log.Info(`attaching ${this._rawChannel} to Websock`);
558
+ this._sock.attach(this._rawChannel);
559
+
560
+ if (this._sock.readyState === 'closed') {
561
+ throw Error("Cannot use already closed WebSocket/RTCDataChannel");
562
+ }
563
+
564
+ if (this._sock.readyState === 'open') {
565
+ // FIXME: _socketOpen() can in theory call _fail(), which
566
+ // isn't allowed this early, but I'm not sure that can
567
+ // happen without a bug messing up our state variables
568
+ this._socketOpen();
569
+ }
570
+ }
571
+
572
+ // Make our elements part of the page
573
+ this._target.appendChild(this._screen);
574
+
575
+ this._gestures.attach(this._canvas);
576
+
577
+ this._cursor.attach(this._canvas);
578
+ this._refreshCursor();
579
+
580
+ // Monitor size changes of the screen element
581
+ this._resizeObserver.observe(this._screen);
582
+
583
+ // Always grab focus on some kind of click event
584
+ this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas);
585
+ this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas);
586
+
587
+ // Mouse events
588
+ this._canvas.addEventListener('mousedown', this._eventHandlers.handleMouse);
589
+ this._canvas.addEventListener('mouseup', this._eventHandlers.handleMouse);
590
+ this._canvas.addEventListener('mousemove', this._eventHandlers.handleMouse);
591
+ // Prevent middle-click pasting (see handler for why we bind to document)
592
+ this._canvas.addEventListener('click', this._eventHandlers.handleMouse);
593
+ // preventDefault() on mousedown doesn't stop this event for some
594
+ // reason so we have to explicitly block it
595
+ this._canvas.addEventListener('contextmenu', this._eventHandlers.handleMouse);
596
+
597
+ // Wheel events
598
+ this._canvas.addEventListener("wheel", this._eventHandlers.handleWheel);
599
+
600
+ // Gesture events
601
+ this._canvas.addEventListener("gesturestart", this._eventHandlers.handleGesture);
602
+ this._canvas.addEventListener("gesturemove", this._eventHandlers.handleGesture);
603
+ this._canvas.addEventListener("gestureend", this._eventHandlers.handleGesture);
604
+
605
+ Log.Debug("<< RFB.connect");
606
+ }
607
+
608
+ _disconnect() {
609
+ Log.Debug(">> RFB.disconnect");
610
+ this._cursor.detach();
611
+ this._canvas.removeEventListener("gesturestart", this._eventHandlers.handleGesture);
612
+ this._canvas.removeEventListener("gesturemove", this._eventHandlers.handleGesture);
613
+ this._canvas.removeEventListener("gestureend", this._eventHandlers.handleGesture);
614
+ this._canvas.removeEventListener("wheel", this._eventHandlers.handleWheel);
615
+ this._canvas.removeEventListener('mousedown', this._eventHandlers.handleMouse);
616
+ this._canvas.removeEventListener('mouseup', this._eventHandlers.handleMouse);
617
+ this._canvas.removeEventListener('mousemove', this._eventHandlers.handleMouse);
618
+ this._canvas.removeEventListener('click', this._eventHandlers.handleMouse);
619
+ this._canvas.removeEventListener('contextmenu', this._eventHandlers.handleMouse);
620
+ this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas);
621
+ this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas);
622
+ this._resizeObserver.disconnect();
623
+ this._keyboard.ungrab();
624
+ this._gestures.detach();
625
+ this._sock.close();
626
+ try {
627
+ this._target.removeChild(this._screen);
628
+ } catch (e) {
629
+ if (e.name === 'NotFoundError') {
630
+ // Some cases where the initial connection fails
631
+ // can disconnect before the _screen is created
632
+ } else {
633
+ throw e;
634
+ }
635
+ }
636
+ clearTimeout(this._resizeTimeout);
637
+ clearTimeout(this._mouseMoveTimer);
638
+ Log.Debug("<< RFB.disconnect");
639
+ }
640
+
641
+ _socketOpen() {
642
+ if ((this._rfbConnectionState === 'connecting') &&
643
+ (this._rfbInitState === '')) {
644
+ this._rfbInitState = 'ProtocolVersion';
645
+ Log.Debug("Starting VNC handshake");
646
+ } else {
647
+ this._fail("Unexpected server connection while " +
648
+ this._rfbConnectionState);
649
+ }
650
+ }
651
+
652
+ _socketClose(e) {
653
+ Log.Debug("WebSocket on-close event");
654
+ let msg = "";
655
+ if (e.code) {
656
+ msg = "(code: " + e.code;
657
+ if (e.reason) {
658
+ msg += ", reason: " + e.reason;
659
+ }
660
+ msg += ")";
661
+ }
662
+ switch (this._rfbConnectionState) {
663
+ case 'connecting':
664
+ this._fail("Connection closed " + msg);
665
+ break;
666
+ case 'connected':
667
+ // Handle disconnects that were initiated server-side
668
+ this._updateConnectionState('disconnecting');
669
+ this._updateConnectionState('disconnected');
670
+ break;
671
+ case 'disconnecting':
672
+ // Normal disconnection path
673
+ this._updateConnectionState('disconnected');
674
+ break;
675
+ case 'disconnected':
676
+ this._fail("Unexpected server disconnect " +
677
+ "when already disconnected " + msg);
678
+ break;
679
+ default:
680
+ this._fail("Unexpected server disconnect before connecting " +
681
+ msg);
682
+ break;
683
+ }
684
+ this._sock.off('close');
685
+ // Delete reference to raw channel to allow cleanup.
686
+ this._rawChannel = null;
687
+ }
688
+
689
+ _socketError(e) {
690
+ Log.Warn("WebSocket on-error event");
691
+ }
692
+
693
+ _focusCanvas(event) {
694
+ if (!this.focusOnClick) {
695
+ return;
696
+ }
697
+
698
+ this.focus({ preventScroll: true });
699
+ }
700
+
701
+ _setDesktopName(name) {
702
+ this._fbName = name;
703
+ this.dispatchEvent(new CustomEvent(
704
+ "desktopname",
705
+ { detail: { name: this._fbName } }));
706
+ }
707
+
708
+ _saveExpectedClientSize() {
709
+ this._expectedClientWidth = this._screen.clientWidth;
710
+ this._expectedClientHeight = this._screen.clientHeight;
711
+ }
712
+
713
+ _currentClientSize() {
714
+ return [this._screen.clientWidth, this._screen.clientHeight];
715
+ }
716
+
717
+ _clientHasExpectedSize() {
718
+ const [currentWidth, currentHeight] = this._currentClientSize();
719
+ return currentWidth == this._expectedClientWidth &&
720
+ currentHeight == this._expectedClientHeight;
721
+ }
722
+
723
+ // Handle browser window resizes
724
+ _handleResize() {
725
+ // Don't change anything if the client size is already as expected
726
+ if (this._clientHasExpectedSize()) {
727
+ return;
728
+ }
729
+ // If the window resized then our screen element might have
730
+ // as well. Update the viewport dimensions.
731
+ window.requestAnimationFrame(() => {
732
+ this._updateClip();
733
+ this._updateScale();
734
+ this._saveExpectedClientSize();
735
+ });
736
+
737
+ // Request changing the resolution of the remote display to
738
+ // the size of the local browser viewport.
739
+ this._requestRemoteResize();
740
+ }
741
+
742
+ // Update state of clipping in Display object, and make sure the
743
+ // configured viewport matches the current screen size
744
+ _updateClip() {
745
+ const curClip = this._display.clipViewport;
746
+ let newClip = this._clipViewport;
747
+
748
+ if (this._scaleViewport) {
749
+ // Disable viewport clipping if we are scaling
750
+ newClip = false;
751
+ }
752
+
753
+ if (curClip !== newClip) {
754
+ this._display.clipViewport = newClip;
755
+ }
756
+
757
+ if (newClip) {
758
+ // When clipping is enabled, the screen is limited to
759
+ // the size of the container.
760
+ const size = this._screenSize();
761
+ this._display.viewportChangeSize(size.w, size.h);
762
+ this._fixScrollbars();
763
+ this._setClippingViewport(size.w < this._display.width ||
764
+ size.h < this._display.height);
765
+ } else {
766
+ this._setClippingViewport(false);
767
+ }
768
+
769
+ // When changing clipping we might show or hide scrollbars.
770
+ // This causes the expected client dimensions to change.
771
+ if (curClip !== newClip) {
772
+ this._saveExpectedClientSize();
773
+ }
774
+ }
775
+
776
+ _updateScale() {
777
+ if (!this._scaleViewport) {
778
+ this._display.scale = 1.0;
779
+ } else {
780
+ const size = this._screenSize();
781
+ this._display.autoscale(size.w, size.h);
782
+ }
783
+ this._fixScrollbars();
784
+ }
785
+
786
+ // Requests a change of remote desktop size. This message is an extension
787
+ // and may only be sent if we have received an ExtendedDesktopSize message
788
+ _requestRemoteResize() {
789
+ if (!this._resizeSession) {
790
+ return;
791
+ }
792
+ if (this._viewOnly) {
793
+ return;
794
+ }
795
+ if (!this._supportsSetDesktopSize) {
796
+ return;
797
+ }
798
+
799
+ // Rate limit to one pending resize at a time
800
+ if (this._pendingRemoteResize) {
801
+ return;
802
+ }
803
+
804
+ // And no more than once every 100ms
805
+ if ((Date.now() - this._lastResize) < 100) {
806
+ clearTimeout(this._resizeTimeout);
807
+ this._resizeTimeout = setTimeout(this._requestRemoteResize.bind(this),
808
+ 100 - (Date.now() - this._lastResize));
809
+ return;
810
+ }
811
+ this._resizeTimeout = null;
812
+
813
+ const size = this._screenSize();
814
+
815
+ // Do we actually change anything?
816
+ if (size.w === this._fbWidth && size.h === this._fbHeight) {
817
+ return;
818
+ }
819
+
820
+ this._pendingRemoteResize = true;
821
+ this._lastResize = Date.now();
822
+ RFB.messages.setDesktopSize(this._sock,
823
+ Math.floor(size.w), Math.floor(size.h),
824
+ this._screenID, this._screenFlags);
825
+
826
+ Log.Debug('Requested new desktop size: ' +
827
+ size.w + 'x' + size.h);
828
+ }
829
+
830
+ // Gets the the size of the available screen
831
+ _screenSize() {
832
+ let r = this._screen.getBoundingClientRect();
833
+ return { w: r.width, h: r.height };
834
+ }
835
+
836
+ _fixScrollbars() {
837
+ // This is a hack because Safari on macOS screws up the calculation
838
+ // for when scrollbars are needed. We get scrollbars when making the
839
+ // browser smaller, despite remote resize being enabled. So to fix it
840
+ // we temporarily toggle them off and on.
841
+ const orig = this._screen.style.overflow;
842
+ this._screen.style.overflow = 'hidden';
843
+ // Force Safari to recalculate the layout by asking for
844
+ // an element's dimensions
845
+ this._screen.getBoundingClientRect();
846
+ this._screen.style.overflow = orig;
847
+ }
848
+
849
+ /*
850
+ * Connection states:
851
+ * connecting
852
+ * connected
853
+ * disconnecting
854
+ * disconnected - permanent state
855
+ */
856
+ _updateConnectionState(state) {
857
+ const oldstate = this._rfbConnectionState;
858
+
859
+ if (state === oldstate) {
860
+ Log.Debug("Already in state '" + state + "', ignoring");
861
+ return;
862
+ }
863
+
864
+ // The 'disconnected' state is permanent for each RFB object
865
+ if (oldstate === 'disconnected') {
866
+ Log.Error("Tried changing state of a disconnected RFB object");
867
+ return;
868
+ }
869
+
870
+ // Ensure proper transitions before doing anything
871
+ switch (state) {
872
+ case 'connected':
873
+ if (oldstate !== 'connecting') {
874
+ Log.Error("Bad transition to connected state, " +
875
+ "previous connection state: " + oldstate);
876
+ return;
877
+ }
878
+ break;
879
+
880
+ case 'disconnected':
881
+ if (oldstate !== 'disconnecting') {
882
+ Log.Error("Bad transition to disconnected state, " +
883
+ "previous connection state: " + oldstate);
884
+ return;
885
+ }
886
+ break;
887
+
888
+ case 'connecting':
889
+ if (oldstate !== '') {
890
+ Log.Error("Bad transition to connecting state, " +
891
+ "previous connection state: " + oldstate);
892
+ return;
893
+ }
894
+ break;
895
+
896
+ case 'disconnecting':
897
+ if (oldstate !== 'connected' && oldstate !== 'connecting') {
898
+ Log.Error("Bad transition to disconnecting state, " +
899
+ "previous connection state: " + oldstate);
900
+ return;
901
+ }
902
+ break;
903
+
904
+ default:
905
+ Log.Error("Unknown connection state: " + state);
906
+ return;
907
+ }
908
+
909
+ // State change actions
910
+
911
+ this._rfbConnectionState = state;
912
+
913
+ Log.Debug("New state '" + state + "', was '" + oldstate + "'.");
914
+
915
+ if (this._disconnTimer && state !== 'disconnecting') {
916
+ Log.Debug("Clearing disconnect timer");
917
+ clearTimeout(this._disconnTimer);
918
+ this._disconnTimer = null;
919
+
920
+ // make sure we don't get a double event
921
+ this._sock.off('close');
922
+ }
923
+
924
+ switch (state) {
925
+ case 'connecting':
926
+ this._connect();
927
+ break;
928
+
929
+ case 'connected':
930
+ this.dispatchEvent(new CustomEvent("connect", { detail: {} }));
931
+ break;
932
+
933
+ case 'disconnecting':
934
+ this._disconnect();
935
+
936
+ this._disconnTimer = setTimeout(() => {
937
+ Log.Error("Disconnection timed out.");
938
+ this._updateConnectionState('disconnected');
939
+ }, DISCONNECT_TIMEOUT * 1000);
940
+ break;
941
+
942
+ case 'disconnected':
943
+ this.dispatchEvent(new CustomEvent(
944
+ "disconnect", { detail:
945
+ { clean: this._rfbCleanDisconnect } }));
946
+ break;
947
+ }
948
+ }
949
+
950
+ /* Print errors and disconnect
951
+ *
952
+ * The parameter 'details' is used for information that
953
+ * should be logged but not sent to the user interface.
954
+ */
955
+ _fail(details) {
956
+ switch (this._rfbConnectionState) {
957
+ case 'disconnecting':
958
+ Log.Error("Failed when disconnecting: " + details);
959
+ break;
960
+ case 'connected':
961
+ Log.Error("Failed while connected: " + details);
962
+ break;
963
+ case 'connecting':
964
+ Log.Error("Failed when connecting: " + details);
965
+ break;
966
+ default:
967
+ Log.Error("RFB failure: " + details);
968
+ break;
969
+ }
970
+ this._rfbCleanDisconnect = false; //This is sent to the UI
971
+
972
+ // Transition to disconnected without waiting for socket to close
973
+ this._updateConnectionState('disconnecting');
974
+ this._updateConnectionState('disconnected');
975
+
976
+ return false;
977
+ }
978
+
979
+ _setCapability(cap, val) {
980
+ this._capabilities[cap] = val;
981
+ this.dispatchEvent(new CustomEvent("capabilities",
982
+ { detail: { capabilities: this._capabilities } }));
983
+ }
984
+
985
+ _handleMessage() {
986
+ if (this._sock.rQwait("message", 1)) {
987
+ Log.Warn("handleMessage called on an empty receive queue");
988
+ return;
989
+ }
990
+
991
+ switch (this._rfbConnectionState) {
992
+ case 'disconnected':
993
+ Log.Error("Got data while disconnected");
994
+ break;
995
+ case 'connected':
996
+ while (true) {
997
+ if (this._flushing) {
998
+ break;
999
+ }
1000
+ if (!this._normalMsg()) {
1001
+ break;
1002
+ }
1003
+ if (this._sock.rQwait("message", 1)) {
1004
+ break;
1005
+ }
1006
+ }
1007
+ break;
1008
+ case 'connecting':
1009
+ while (this._rfbConnectionState === 'connecting') {
1010
+ if (!this._initMsg()) {
1011
+ break;
1012
+ }
1013
+ }
1014
+ break;
1015
+ default:
1016
+ Log.Error("Got data while in an invalid state");
1017
+ break;
1018
+ }
1019
+ }
1020
+
1021
+ _handleKeyEvent(keysym, code, down, numlock, capslock) {
1022
+ // If remote state of capslock is known, and it doesn't match the local led state of
1023
+ // the keyboard, we send a capslock keypress first to bring it into sync.
1024
+ // If we just pressed CapsLock, or we toggled it remotely due to it being out of sync
1025
+ // we clear the remote state so that we don't send duplicate or spurious fixes,
1026
+ // since it may take some time to receive the new remote CapsLock state.
1027
+ if (code == 'CapsLock' && down) {
1028
+ this._remoteCapsLock = null;
1029
+ }
1030
+ if (this._remoteCapsLock !== null && capslock !== null && this._remoteCapsLock !== capslock && down) {
1031
+ Log.Debug("Fixing remote caps lock");
1032
+
1033
+ this.sendKey(KeyTable.XK_Caps_Lock, 'CapsLock', true);
1034
+ this.sendKey(KeyTable.XK_Caps_Lock, 'CapsLock', false);
1035
+ // We clear the remote capsLock state when we do this to prevent issues with doing this twice
1036
+ // before we receive an update of the the remote state.
1037
+ this._remoteCapsLock = null;
1038
+ }
1039
+
1040
+ // Logic for numlock is exactly the same.
1041
+ if (code == 'NumLock' && down) {
1042
+ this._remoteNumLock = null;
1043
+ }
1044
+ if (this._remoteNumLock !== null && numlock !== null && this._remoteNumLock !== numlock && down) {
1045
+ Log.Debug("Fixing remote num lock");
1046
+ this.sendKey(KeyTable.XK_Num_Lock, 'NumLock', true);
1047
+ this.sendKey(KeyTable.XK_Num_Lock, 'NumLock', false);
1048
+ this._remoteNumLock = null;
1049
+ }
1050
+ this.sendKey(keysym, code, down);
1051
+ }
1052
+
1053
+ static _convertButtonMask(buttons) {
1054
+ /* The bits in MouseEvent.buttons property correspond
1055
+ * to the following mouse buttons:
1056
+ * 0: Left
1057
+ * 1: Right
1058
+ * 2: Middle
1059
+ * 3: Back
1060
+ * 4: Forward
1061
+ *
1062
+ * These bits needs to be converted to what they are defined as
1063
+ * in the RFB protocol.
1064
+ */
1065
+
1066
+ const buttonMaskMap = {
1067
+ 0: 1 << 0, // Left
1068
+ 1: 1 << 2, // Right
1069
+ 2: 1 << 1, // Middle
1070
+ 3: 1 << 7, // Back
1071
+ 4: 1 << 8, // Forward
1072
+ };
1073
+
1074
+ let bmask = 0;
1075
+ for (let i = 0; i < 5; i++) {
1076
+ if (buttons & (1 << i)) {
1077
+ bmask |= buttonMaskMap[i];
1078
+ }
1079
+ }
1080
+ return bmask;
1081
+ }
1082
+
1083
+ _handleMouse(ev) {
1084
+ /*
1085
+ * We don't check connection status or viewOnly here as the
1086
+ * mouse events might be used to control the viewport
1087
+ */
1088
+
1089
+ if (ev.type === 'click') {
1090
+ /*
1091
+ * Note: This is only needed for the 'click' event as it fails
1092
+ * to fire properly for the target element so we have
1093
+ * to listen on the document element instead.
1094
+ */
1095
+ if (ev.target !== this._canvas) {
1096
+ return;
1097
+ }
1098
+ }
1099
+
1100
+ // FIXME: if we're in view-only and not dragging,
1101
+ // should we stop events?
1102
+ ev.stopPropagation();
1103
+ ev.preventDefault();
1104
+
1105
+ if ((ev.type === 'click') || (ev.type === 'contextmenu')) {
1106
+ return;
1107
+ }
1108
+
1109
+ let pos = clientToElement(ev.clientX, ev.clientY,
1110
+ this._canvas);
1111
+
1112
+ let bmask = RFB._convertButtonMask(ev.buttons);
1113
+
1114
+ let down = ev.type == 'mousedown';
1115
+ switch (ev.type) {
1116
+ case 'mousedown':
1117
+ case 'mouseup':
1118
+ if (this.dragViewport) {
1119
+ if (down && !this._viewportDragging) {
1120
+ this._viewportDragging = true;
1121
+ this._viewportDragPos = {'x': pos.x, 'y': pos.y};
1122
+ this._viewportHasMoved = false;
1123
+
1124
+ this._flushMouseMoveTimer(pos.x, pos.y);
1125
+
1126
+ // Skip sending mouse events, instead save the current
1127
+ // mouse mask so we can send it later.
1128
+ this._mouseButtonMask = bmask;
1129
+ break;
1130
+ } else {
1131
+ this._viewportDragging = false;
1132
+
1133
+ // If we actually performed a drag then we are done
1134
+ // here and should not send any mouse events
1135
+ if (this._viewportHasMoved) {
1136
+ this._mouseButtonMask = bmask;
1137
+ break;
1138
+ }
1139
+ // Otherwise we treat this as a mouse click event.
1140
+ // Send the previously saved button mask, followed
1141
+ // by the current button mask at the end of this
1142
+ // function.
1143
+ this._sendMouse(pos.x, pos.y, this._mouseButtonMask);
1144
+ }
1145
+ }
1146
+ if (down) {
1147
+ setCapture(this._canvas);
1148
+ }
1149
+ this._handleMouseButton(pos.x, pos.y, bmask);
1150
+ break;
1151
+ case 'mousemove':
1152
+ if (this._viewportDragging) {
1153
+ const deltaX = this._viewportDragPos.x - pos.x;
1154
+ const deltaY = this._viewportDragPos.y - pos.y;
1155
+
1156
+ if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
1157
+ Math.abs(deltaY) > dragThreshold)) {
1158
+ this._viewportHasMoved = true;
1159
+
1160
+ this._viewportDragPos = {'x': pos.x, 'y': pos.y};
1161
+ this._display.viewportChangePos(deltaX, deltaY);
1162
+ }
1163
+
1164
+ // Skip sending mouse events
1165
+ break;
1166
+ }
1167
+ this._handleMouseMove(pos.x, pos.y);
1168
+ break;
1169
+ }
1170
+ }
1171
+
1172
+ _handleMouseButton(x, y, bmask) {
1173
+ // Flush waiting move event first
1174
+ this._flushMouseMoveTimer(x, y);
1175
+
1176
+ this._mouseButtonMask = bmask;
1177
+ this._sendMouse(x, y, this._mouseButtonMask);
1178
+ }
1179
+
1180
+ _handleMouseMove(x, y) {
1181
+ this._mousePos = { 'x': x, 'y': y };
1182
+
1183
+ // Limit many mouse move events to one every MOUSE_MOVE_DELAY ms
1184
+ if (this._mouseMoveTimer == null) {
1185
+
1186
+ const timeSinceLastMove = Date.now() - this._mouseLastMoveTime;
1187
+ if (timeSinceLastMove > MOUSE_MOVE_DELAY) {
1188
+ this._sendMouse(x, y, this._mouseButtonMask);
1189
+ this._mouseLastMoveTime = Date.now();
1190
+ } else {
1191
+ // Too soon since the latest move, wait the remaining time
1192
+ this._mouseMoveTimer = setTimeout(() => {
1193
+ this._handleDelayedMouseMove();
1194
+ }, MOUSE_MOVE_DELAY - timeSinceLastMove);
1195
+ }
1196
+ }
1197
+ }
1198
+
1199
+ _handleDelayedMouseMove() {
1200
+ this._mouseMoveTimer = null;
1201
+ this._sendMouse(this._mousePos.x, this._mousePos.y,
1202
+ this._mouseButtonMask);
1203
+ this._mouseLastMoveTime = Date.now();
1204
+ }
1205
+
1206
+ _sendMouse(x, y, mask) {
1207
+ if (this._rfbConnectionState !== 'connected') { return; }
1208
+ if (this._viewOnly) { return; } // View only, skip mouse events
1209
+
1210
+ // Highest bit in mask is never sent to the server
1211
+ if (mask & 0x8000) {
1212
+ throw new Error("Illegal mouse button mask (mask: " + mask + ")");
1213
+ }
1214
+
1215
+ let extendedMouseButtons = mask & 0x7f80;
1216
+
1217
+ if (this._extendedPointerEventSupported && extendedMouseButtons) {
1218
+ RFB.messages.extendedPointerEvent(this._sock, this._display.absX(x),
1219
+ this._display.absY(y), mask);
1220
+ } else {
1221
+ RFB.messages.pointerEvent(this._sock, this._display.absX(x),
1222
+ this._display.absY(y), mask);
1223
+ }
1224
+ }
1225
+
1226
+ _handleWheel(ev) {
1227
+ if (this._rfbConnectionState !== 'connected') { return; }
1228
+ if (this._viewOnly) { return; } // View only, skip mouse events
1229
+
1230
+ ev.stopPropagation();
1231
+ ev.preventDefault();
1232
+
1233
+ let pos = clientToElement(ev.clientX, ev.clientY,
1234
+ this._canvas);
1235
+
1236
+ let bmask = RFB._convertButtonMask(ev.buttons);
1237
+ let dX = ev.deltaX;
1238
+ let dY = ev.deltaY;
1239
+
1240
+ // Pixel units unless it's non-zero.
1241
+ // Note that if deltamode is line or page won't matter since we aren't
1242
+ // sending the mouse wheel delta to the server anyway.
1243
+ // The difference between pixel and line can be important however since
1244
+ // we have a threshold that can be smaller than the line height.
1245
+ if (ev.deltaMode !== 0) {
1246
+ dX *= WHEEL_LINE_HEIGHT;
1247
+ dY *= WHEEL_LINE_HEIGHT;
1248
+ }
1249
+
1250
+ // Mouse wheel events are sent in steps over VNC. This means that the VNC
1251
+ // protocol can't handle a wheel event with specific distance or speed.
1252
+ // Therefor, if we get a lot of small mouse wheel events we combine them.
1253
+ this._accumulatedWheelDeltaX += dX;
1254
+ this._accumulatedWheelDeltaY += dY;
1255
+
1256
+
1257
+ // Generate a mouse wheel step event when the accumulated delta
1258
+ // for one of the axes is large enough.
1259
+ if (Math.abs(this._accumulatedWheelDeltaX) >= WHEEL_STEP) {
1260
+ if (this._accumulatedWheelDeltaX < 0) {
1261
+ this._handleMouseButton(pos.x, pos.y, bmask | 1 << 5);
1262
+ this._handleMouseButton(pos.x, pos.y, bmask);
1263
+ } else if (this._accumulatedWheelDeltaX > 0) {
1264
+ this._handleMouseButton(pos.x, pos.y, bmask | 1 << 6);
1265
+ this._handleMouseButton(pos.x, pos.y, bmask);
1266
+ }
1267
+
1268
+ this._accumulatedWheelDeltaX = 0;
1269
+ }
1270
+ if (Math.abs(this._accumulatedWheelDeltaY) >= WHEEL_STEP) {
1271
+ if (this._accumulatedWheelDeltaY < 0) {
1272
+ this._handleMouseButton(pos.x, pos.y, bmask | 1 << 3);
1273
+ this._handleMouseButton(pos.x, pos.y, bmask);
1274
+ } else if (this._accumulatedWheelDeltaY > 0) {
1275
+ this._handleMouseButton(pos.x, pos.y, bmask | 1 << 4);
1276
+ this._handleMouseButton(pos.x, pos.y, bmask);
1277
+ }
1278
+
1279
+ this._accumulatedWheelDeltaY = 0;
1280
+ }
1281
+ }
1282
+
1283
+ _fakeMouseMove(ev, elementX, elementY) {
1284
+ this._handleMouseMove(elementX, elementY);
1285
+ this._cursor.move(ev.detail.clientX, ev.detail.clientY);
1286
+ }
1287
+
1288
+ _handleTapEvent(ev, bmask) {
1289
+ let pos = clientToElement(ev.detail.clientX, ev.detail.clientY,
1290
+ this._canvas);
1291
+
1292
+ // If the user quickly taps multiple times we assume they meant to
1293
+ // hit the same spot, so slightly adjust coordinates
1294
+
1295
+ if ((this._gestureLastTapTime !== null) &&
1296
+ ((Date.now() - this._gestureLastTapTime) < DOUBLE_TAP_TIMEOUT) &&
1297
+ (this._gestureFirstDoubleTapEv.detail.type === ev.detail.type)) {
1298
+ let dx = this._gestureFirstDoubleTapEv.detail.clientX - ev.detail.clientX;
1299
+ let dy = this._gestureFirstDoubleTapEv.detail.clientY - ev.detail.clientY;
1300
+ let distance = Math.hypot(dx, dy);
1301
+
1302
+ if (distance < DOUBLE_TAP_THRESHOLD) {
1303
+ pos = clientToElement(this._gestureFirstDoubleTapEv.detail.clientX,
1304
+ this._gestureFirstDoubleTapEv.detail.clientY,
1305
+ this._canvas);
1306
+ } else {
1307
+ this._gestureFirstDoubleTapEv = ev;
1308
+ }
1309
+ } else {
1310
+ this._gestureFirstDoubleTapEv = ev;
1311
+ }
1312
+ this._gestureLastTapTime = Date.now();
1313
+
1314
+ this._fakeMouseMove(this._gestureFirstDoubleTapEv, pos.x, pos.y);
1315
+ this._handleMouseButton(pos.x, pos.y, bmask);
1316
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1317
+ }
1318
+
1319
+ _handleGesture(ev) {
1320
+ let magnitude;
1321
+
1322
+ let pos = clientToElement(ev.detail.clientX, ev.detail.clientY,
1323
+ this._canvas);
1324
+ switch (ev.type) {
1325
+ case 'gesturestart':
1326
+ switch (ev.detail.type) {
1327
+ case 'onetap':
1328
+ this._handleTapEvent(ev, 0x1);
1329
+ break;
1330
+ case 'twotap':
1331
+ this._handleTapEvent(ev, 0x4);
1332
+ break;
1333
+ case 'threetap':
1334
+ this._handleTapEvent(ev, 0x2);
1335
+ break;
1336
+ case 'drag':
1337
+ if (this.dragViewport) {
1338
+ this._viewportHasMoved = false;
1339
+ this._viewportDragging = true;
1340
+ this._viewportDragPos = {'x': pos.x, 'y': pos.y};
1341
+ } else {
1342
+ this._fakeMouseMove(ev, pos.x, pos.y);
1343
+ this._handleMouseButton(pos.x, pos.y, 0x1);
1344
+ }
1345
+ break;
1346
+ case 'longpress':
1347
+ if (this.dragViewport) {
1348
+ // If dragViewport is true, we need to wait to see
1349
+ // if we have dragged outside the threshold before
1350
+ // sending any events to the server.
1351
+ this._viewportHasMoved = false;
1352
+ this._viewportDragPos = {'x': pos.x, 'y': pos.y};
1353
+ } else {
1354
+ this._fakeMouseMove(ev, pos.x, pos.y);
1355
+ this._handleMouseButton(pos.x, pos.y, 0x4);
1356
+ }
1357
+ break;
1358
+ case 'twodrag':
1359
+ this._gestureLastMagnitudeX = ev.detail.magnitudeX;
1360
+ this._gestureLastMagnitudeY = ev.detail.magnitudeY;
1361
+ this._fakeMouseMove(ev, pos.x, pos.y);
1362
+ break;
1363
+ case 'pinch':
1364
+ this._gestureLastMagnitudeX = Math.hypot(ev.detail.magnitudeX,
1365
+ ev.detail.magnitudeY);
1366
+ this._fakeMouseMove(ev, pos.x, pos.y);
1367
+ break;
1368
+ }
1369
+ break;
1370
+
1371
+ case 'gesturemove':
1372
+ switch (ev.detail.type) {
1373
+ case 'onetap':
1374
+ case 'twotap':
1375
+ case 'threetap':
1376
+ break;
1377
+ case 'drag':
1378
+ case 'longpress':
1379
+ if (this.dragViewport) {
1380
+ this._viewportDragging = true;
1381
+ const deltaX = this._viewportDragPos.x - pos.x;
1382
+ const deltaY = this._viewportDragPos.y - pos.y;
1383
+
1384
+ if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
1385
+ Math.abs(deltaY) > dragThreshold)) {
1386
+ this._viewportHasMoved = true;
1387
+
1388
+ this._viewportDragPos = {'x': pos.x, 'y': pos.y};
1389
+ this._display.viewportChangePos(deltaX, deltaY);
1390
+ }
1391
+ } else {
1392
+ this._fakeMouseMove(ev, pos.x, pos.y);
1393
+ }
1394
+ break;
1395
+ case 'twodrag':
1396
+ // Always scroll in the same position.
1397
+ // We don't know if the mouse was moved so we need to move it
1398
+ // every update.
1399
+ this._fakeMouseMove(ev, pos.x, pos.y);
1400
+ while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) > GESTURE_SCRLSENS) {
1401
+ this._handleMouseButton(pos.x, pos.y, 0x8);
1402
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1403
+ this._gestureLastMagnitudeY += GESTURE_SCRLSENS;
1404
+ }
1405
+ while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) < -GESTURE_SCRLSENS) {
1406
+ this._handleMouseButton(pos.x, pos.y, 0x10);
1407
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1408
+ this._gestureLastMagnitudeY -= GESTURE_SCRLSENS;
1409
+ }
1410
+ while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) > GESTURE_SCRLSENS) {
1411
+ this._handleMouseButton(pos.x, pos.y, 0x20);
1412
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1413
+ this._gestureLastMagnitudeX += GESTURE_SCRLSENS;
1414
+ }
1415
+ while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) < -GESTURE_SCRLSENS) {
1416
+ this._handleMouseButton(pos.x, pos.y, 0x40);
1417
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1418
+ this._gestureLastMagnitudeX -= GESTURE_SCRLSENS;
1419
+ }
1420
+ break;
1421
+ case 'pinch':
1422
+ // Always scroll in the same position.
1423
+ // We don't know if the mouse was moved so we need to move it
1424
+ // every update.
1425
+ this._fakeMouseMove(ev, pos.x, pos.y);
1426
+ magnitude = Math.hypot(ev.detail.magnitudeX, ev.detail.magnitudeY);
1427
+ if (Math.abs(magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) {
1428
+ this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
1429
+ while ((magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) {
1430
+ this._handleMouseButton(pos.x, pos.y, 0x8);
1431
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1432
+ this._gestureLastMagnitudeX += GESTURE_ZOOMSENS;
1433
+ }
1434
+ while ((magnitude - this._gestureLastMagnitudeX) < -GESTURE_ZOOMSENS) {
1435
+ this._handleMouseButton(pos.x, pos.y, 0x10);
1436
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1437
+ this._gestureLastMagnitudeX -= GESTURE_ZOOMSENS;
1438
+ }
1439
+ }
1440
+ this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", false);
1441
+ break;
1442
+ }
1443
+ break;
1444
+
1445
+ case 'gestureend':
1446
+ switch (ev.detail.type) {
1447
+ case 'onetap':
1448
+ case 'twotap':
1449
+ case 'threetap':
1450
+ case 'pinch':
1451
+ case 'twodrag':
1452
+ break;
1453
+ case 'drag':
1454
+ if (this.dragViewport) {
1455
+ this._viewportDragging = false;
1456
+ } else {
1457
+ this._fakeMouseMove(ev, pos.x, pos.y);
1458
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1459
+ }
1460
+ break;
1461
+ case 'longpress':
1462
+ if (this._viewportHasMoved) {
1463
+ // We don't want to send any events if we have moved
1464
+ // our viewport
1465
+ break;
1466
+ }
1467
+
1468
+ if (this.dragViewport && !this._viewportHasMoved) {
1469
+ this._fakeMouseMove(ev, pos.x, pos.y);
1470
+ // If dragViewport is true, we need to wait to see
1471
+ // if we have dragged outside the threshold before
1472
+ // sending any events to the server.
1473
+ this._handleMouseButton(pos.x, pos.y, 0x4);
1474
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1475
+ this._viewportDragging = false;
1476
+ } else {
1477
+ this._fakeMouseMove(ev, pos.x, pos.y);
1478
+ this._handleMouseButton(pos.x, pos.y, 0x0);
1479
+ }
1480
+ break;
1481
+ }
1482
+ break;
1483
+ }
1484
+ }
1485
+
1486
+ _flushMouseMoveTimer(x, y) {
1487
+ if (this._mouseMoveTimer !== null) {
1488
+ clearTimeout(this._mouseMoveTimer);
1489
+ this._mouseMoveTimer = null;
1490
+ this._sendMouse(x, y, this._mouseButtonMask);
1491
+ }
1492
+ }
1493
+
1494
+ // Message handlers
1495
+
1496
+ _negotiateProtocolVersion() {
1497
+ if (this._sock.rQwait("version", 12)) {
1498
+ return false;
1499
+ }
1500
+
1501
+ const sversion = this._sock.rQshiftStr(12).substr(4, 7);
1502
+ Log.Info("Server ProtocolVersion: " + sversion);
1503
+ let isRepeater = 0;
1504
+ switch (sversion) {
1505
+ case "000.000": // UltraVNC repeater
1506
+ isRepeater = 1;
1507
+ break;
1508
+ case "003.003":
1509
+ case "003.006": // UltraVNC
1510
+ this._rfbVersion = 3.3;
1511
+ break;
1512
+ case "003.007":
1513
+ this._rfbVersion = 3.7;
1514
+ break;
1515
+ case "003.008":
1516
+ case "003.889": // Apple Remote Desktop
1517
+ case "004.000": // Intel AMT KVM
1518
+ case "004.001": // RealVNC 4.6
1519
+ case "005.000": // RealVNC 5.3
1520
+ this._rfbVersion = 3.8;
1521
+ break;
1522
+ default:
1523
+ return this._fail("Invalid server version " + sversion);
1524
+ }
1525
+
1526
+ if (isRepeater) {
1527
+ let repeaterID = "ID:" + this._repeaterID;
1528
+ while (repeaterID.length < 250) {
1529
+ repeaterID += "\0";
1530
+ }
1531
+ this._sock.sQpushString(repeaterID);
1532
+ this._sock.flush();
1533
+ return true;
1534
+ }
1535
+
1536
+ if (this._rfbVersion > this._rfbMaxVersion) {
1537
+ this._rfbVersion = this._rfbMaxVersion;
1538
+ }
1539
+
1540
+ const cversion = "00" + parseInt(this._rfbVersion, 10) +
1541
+ ".00" + ((this._rfbVersion * 10) % 10);
1542
+ this._sock.sQpushString("RFB " + cversion + "\n");
1543
+ this._sock.flush();
1544
+ Log.Debug('Sent ProtocolVersion: ' + cversion);
1545
+
1546
+ this._rfbInitState = 'Security';
1547
+ }
1548
+
1549
+ _isSupportedSecurityType(type) {
1550
+ const clientTypes = [
1551
+ securityTypeNone,
1552
+ securityTypeVNCAuth,
1553
+ securityTypeRA2ne,
1554
+ securityTypeTight,
1555
+ securityTypeVeNCrypt,
1556
+ securityTypeXVP,
1557
+ securityTypeARD,
1558
+ securityTypeMSLogonII,
1559
+ securityTypePlain,
1560
+ ];
1561
+
1562
+ return clientTypes.includes(type);
1563
+ }
1564
+
1565
+ _negotiateSecurity() {
1566
+ if (this._rfbVersion >= 3.7) {
1567
+ // Server sends supported list, client decides
1568
+ const numTypes = this._sock.rQshift8();
1569
+ if (this._sock.rQwait("security type", numTypes, 1)) { return false; }
1570
+
1571
+ if (numTypes === 0) {
1572
+ this._rfbInitState = "SecurityReason";
1573
+ this._securityContext = "no security types";
1574
+ this._securityStatus = 1;
1575
+ return true;
1576
+ }
1577
+
1578
+ const types = this._sock.rQshiftBytes(numTypes);
1579
+ Log.Debug("Server security types: " + types);
1580
+
1581
+ // Look for a matching security type in the order that the
1582
+ // server prefers
1583
+ this._rfbAuthScheme = -1;
1584
+ for (let type of types) {
1585
+ if (this._isSupportedSecurityType(type)) {
1586
+ this._rfbAuthScheme = type;
1587
+ break;
1588
+ }
1589
+ }
1590
+
1591
+ if (this._rfbAuthScheme === -1) {
1592
+ return this._fail("Unsupported security types (types: " + types + ")");
1593
+ }
1594
+
1595
+ this._sock.sQpush8(this._rfbAuthScheme);
1596
+ this._sock.flush();
1597
+ } else {
1598
+ // Server decides
1599
+ if (this._sock.rQwait("security scheme", 4)) { return false; }
1600
+ this._rfbAuthScheme = this._sock.rQshift32();
1601
+
1602
+ if (this._rfbAuthScheme == 0) {
1603
+ this._rfbInitState = "SecurityReason";
1604
+ this._securityContext = "authentication scheme";
1605
+ this._securityStatus = 1;
1606
+ return true;
1607
+ }
1608
+ }
1609
+
1610
+ this._rfbInitState = 'Authentication';
1611
+ Log.Debug('Authenticating using scheme: ' + this._rfbAuthScheme);
1612
+
1613
+ return true;
1614
+ }
1615
+
1616
+ _handleSecurityReason() {
1617
+ if (this._sock.rQwait("reason length", 4)) {
1618
+ return false;
1619
+ }
1620
+ const strlen = this._sock.rQshift32();
1621
+ let reason = "";
1622
+
1623
+ if (strlen > 0) {
1624
+ if (this._sock.rQwait("reason", strlen, 4)) { return false; }
1625
+ reason = this._sock.rQshiftStr(strlen);
1626
+ }
1627
+
1628
+ if (reason !== "") {
1629
+ this.dispatchEvent(new CustomEvent(
1630
+ "securityfailure",
1631
+ { detail: { status: this._securityStatus,
1632
+ reason: reason } }));
1633
+
1634
+ return this._fail("Security negotiation failed on " +
1635
+ this._securityContext +
1636
+ " (reason: " + reason + ")");
1637
+ } else {
1638
+ this.dispatchEvent(new CustomEvent(
1639
+ "securityfailure",
1640
+ { detail: { status: this._securityStatus } }));
1641
+
1642
+ return this._fail("Security negotiation failed on " +
1643
+ this._securityContext);
1644
+ }
1645
+ }
1646
+
1647
+ // authentication
1648
+ _negotiateXvpAuth() {
1649
+ if (this._rfbCredentials.username === undefined ||
1650
+ this._rfbCredentials.password === undefined ||
1651
+ this._rfbCredentials.target === undefined) {
1652
+ this.dispatchEvent(new CustomEvent(
1653
+ "credentialsrequired",
1654
+ { detail: { types: ["username", "password", "target"] } }));
1655
+ return false;
1656
+ }
1657
+
1658
+ this._sock.sQpush8(this._rfbCredentials.username.length);
1659
+ this._sock.sQpush8(this._rfbCredentials.target.length);
1660
+ this._sock.sQpushString(this._rfbCredentials.username);
1661
+ this._sock.sQpushString(this._rfbCredentials.target);
1662
+
1663
+ this._sock.flush();
1664
+
1665
+ this._rfbAuthScheme = securityTypeVNCAuth;
1666
+
1667
+ return this._negotiateAuthentication();
1668
+ }
1669
+
1670
+ // VeNCrypt authentication, currently only supports version 0.2 and only Plain subtype
1671
+ _negotiateVeNCryptAuth() {
1672
+
1673
+ // waiting for VeNCrypt version
1674
+ if (this._rfbVeNCryptState == 0) {
1675
+ if (this._sock.rQwait("vencrypt version", 2)) { return false; }
1676
+
1677
+ const major = this._sock.rQshift8();
1678
+ const minor = this._sock.rQshift8();
1679
+
1680
+ if (!(major == 0 && minor == 2)) {
1681
+ return this._fail("Unsupported VeNCrypt version " + major + "." + minor);
1682
+ }
1683
+
1684
+ this._sock.sQpush8(0);
1685
+ this._sock.sQpush8(2);
1686
+ this._sock.flush();
1687
+ this._rfbVeNCryptState = 1;
1688
+ }
1689
+
1690
+ // waiting for ACK
1691
+ if (this._rfbVeNCryptState == 1) {
1692
+ if (this._sock.rQwait("vencrypt ack", 1)) { return false; }
1693
+
1694
+ const res = this._sock.rQshift8();
1695
+
1696
+ if (res != 0) {
1697
+ return this._fail("VeNCrypt failure " + res);
1698
+ }
1699
+
1700
+ this._rfbVeNCryptState = 2;
1701
+ }
1702
+ // must fall through here (i.e. no "else if"), beacause we may have already received
1703
+ // the subtypes length and won't be called again
1704
+
1705
+ if (this._rfbVeNCryptState == 2) { // waiting for subtypes length
1706
+ if (this._sock.rQwait("vencrypt subtypes length", 1)) { return false; }
1707
+
1708
+ const subtypesLength = this._sock.rQshift8();
1709
+ if (subtypesLength < 1) {
1710
+ return this._fail("VeNCrypt subtypes empty");
1711
+ }
1712
+
1713
+ this._rfbVeNCryptSubtypesLength = subtypesLength;
1714
+ this._rfbVeNCryptState = 3;
1715
+ }
1716
+
1717
+ // waiting for subtypes list
1718
+ if (this._rfbVeNCryptState == 3) {
1719
+ if (this._sock.rQwait("vencrypt subtypes", 4 * this._rfbVeNCryptSubtypesLength)) { return false; }
1720
+
1721
+ const subtypes = [];
1722
+ for (let i = 0; i < this._rfbVeNCryptSubtypesLength; i++) {
1723
+ subtypes.push(this._sock.rQshift32());
1724
+ }
1725
+
1726
+ // Look for a matching security type in the order that the
1727
+ // server prefers
1728
+ this._rfbAuthScheme = -1;
1729
+ for (let type of subtypes) {
1730
+ // Avoid getting in to a loop
1731
+ if (type === securityTypeVeNCrypt) {
1732
+ continue;
1733
+ }
1734
+
1735
+ if (this._isSupportedSecurityType(type)) {
1736
+ this._rfbAuthScheme = type;
1737
+ break;
1738
+ }
1739
+ }
1740
+
1741
+ if (this._rfbAuthScheme === -1) {
1742
+ return this._fail("Unsupported security types (types: " + subtypes + ")");
1743
+ }
1744
+
1745
+ this._sock.sQpush32(this._rfbAuthScheme);
1746
+ this._sock.flush();
1747
+
1748
+ this._rfbVeNCryptState = 4;
1749
+ return true;
1750
+ }
1751
+ }
1752
+
1753
+ _negotiatePlainAuth() {
1754
+ if (this._rfbCredentials.username === undefined ||
1755
+ this._rfbCredentials.password === undefined) {
1756
+ this.dispatchEvent(new CustomEvent(
1757
+ "credentialsrequired",
1758
+ { detail: { types: ["username", "password"] } }));
1759
+ return false;
1760
+ }
1761
+
1762
+ const user = encodeUTF8(this._rfbCredentials.username);
1763
+ const pass = encodeUTF8(this._rfbCredentials.password);
1764
+
1765
+ this._sock.sQpush32(user.length);
1766
+ this._sock.sQpush32(pass.length);
1767
+ this._sock.sQpushString(user);
1768
+ this._sock.sQpushString(pass);
1769
+ this._sock.flush();
1770
+
1771
+ this._rfbInitState = "SecurityResult";
1772
+ return true;
1773
+ }
1774
+
1775
+ _negotiateStdVNCAuth() {
1776
+ if (this._sock.rQwait("auth challenge", 16)) { return false; }
1777
+
1778
+ if (this._rfbCredentials.password === undefined) {
1779
+ this.dispatchEvent(new CustomEvent(
1780
+ "credentialsrequired",
1781
+ { detail: { types: ["password"] } }));
1782
+ return false;
1783
+ }
1784
+
1785
+ // TODO(directxman12): make genDES not require an Array
1786
+ const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
1787
+ const response = RFB.genDES(this._rfbCredentials.password, challenge);
1788
+ this._sock.sQpushBytes(response);
1789
+ this._sock.flush();
1790
+ this._rfbInitState = "SecurityResult";
1791
+ return true;
1792
+ }
1793
+
1794
+ _negotiateARDAuth() {
1795
+
1796
+ if (this._rfbCredentials.username === undefined ||
1797
+ this._rfbCredentials.password === undefined) {
1798
+ this.dispatchEvent(new CustomEvent(
1799
+ "credentialsrequired",
1800
+ { detail: { types: ["username", "password"] } }));
1801
+ return false;
1802
+ }
1803
+
1804
+ if (this._rfbCredentials.ardPublicKey != undefined &&
1805
+ this._rfbCredentials.ardCredentials != undefined) {
1806
+ // if the async web crypto is done return the results
1807
+ this._sock.sQpushBytes(this._rfbCredentials.ardCredentials);
1808
+ this._sock.sQpushBytes(this._rfbCredentials.ardPublicKey);
1809
+ this._sock.flush();
1810
+ this._rfbCredentials.ardCredentials = null;
1811
+ this._rfbCredentials.ardPublicKey = null;
1812
+ this._rfbInitState = "SecurityResult";
1813
+ return true;
1814
+ }
1815
+
1816
+ if (this._sock.rQwait("read ard", 4)) { return false; }
1817
+
1818
+ let generator = this._sock.rQshiftBytes(2); // DH base generator value
1819
+
1820
+ let keyLength = this._sock.rQshift16();
1821
+
1822
+ if (this._sock.rQwait("read ard keylength", keyLength*2, 4)) { return false; }
1823
+
1824
+ // read the server values
1825
+ let prime = this._sock.rQshiftBytes(keyLength); // predetermined prime modulus
1826
+ let serverPublicKey = this._sock.rQshiftBytes(keyLength); // other party's public key
1827
+
1828
+ let clientKey = legacyCrypto.generateKey(
1829
+ { name: "DH", g: generator, p: prime }, false, ["deriveBits"]);
1830
+ this._negotiateARDAuthAsync(keyLength, serverPublicKey, clientKey);
1831
+
1832
+ return false;
1833
+ }
1834
+
1835
+ async _negotiateARDAuthAsync(keyLength, serverPublicKey, clientKey) {
1836
+ const clientPublicKey = legacyCrypto.exportKey("raw", clientKey.publicKey);
1837
+ const sharedKey = legacyCrypto.deriveBits(
1838
+ { name: "DH", public: serverPublicKey }, clientKey.privateKey, keyLength * 8);
1839
+
1840
+ const username = encodeUTF8(this._rfbCredentials.username).substring(0, 63);
1841
+ const password = encodeUTF8(this._rfbCredentials.password).substring(0, 63);
1842
+
1843
+ const credentials = window.crypto.getRandomValues(new Uint8Array(128));
1844
+ for (let i = 0; i < username.length; i++) {
1845
+ credentials[i] = username.charCodeAt(i);
1846
+ }
1847
+ credentials[username.length] = 0;
1848
+ for (let i = 0; i < password.length; i++) {
1849
+ credentials[64 + i] = password.charCodeAt(i);
1850
+ }
1851
+ credentials[64 + password.length] = 0;
1852
+
1853
+ const key = await legacyCrypto.digest("MD5", sharedKey);
1854
+ const cipher = await legacyCrypto.importKey(
1855
+ "raw", key, { name: "AES-ECB" }, false, ["encrypt"]);
1856
+ const encrypted = await legacyCrypto.encrypt({ name: "AES-ECB" }, cipher, credentials);
1857
+
1858
+ this._rfbCredentials.ardCredentials = encrypted;
1859
+ this._rfbCredentials.ardPublicKey = clientPublicKey;
1860
+
1861
+ this._resumeAuthentication();
1862
+ }
1863
+
1864
+ _negotiateTightUnixAuth() {
1865
+ if (this._rfbCredentials.username === undefined ||
1866
+ this._rfbCredentials.password === undefined) {
1867
+ this.dispatchEvent(new CustomEvent(
1868
+ "credentialsrequired",
1869
+ { detail: { types: ["username", "password"] } }));
1870
+ return false;
1871
+ }
1872
+
1873
+ this._sock.sQpush32(this._rfbCredentials.username.length);
1874
+ this._sock.sQpush32(this._rfbCredentials.password.length);
1875
+ this._sock.sQpushString(this._rfbCredentials.username);
1876
+ this._sock.sQpushString(this._rfbCredentials.password);
1877
+ this._sock.flush();
1878
+
1879
+ this._rfbInitState = "SecurityResult";
1880
+ return true;
1881
+ }
1882
+
1883
+ _negotiateTightTunnels(numTunnels) {
1884
+ const clientSupportedTunnelTypes = {
1885
+ 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
1886
+ };
1887
+ const serverSupportedTunnelTypes = {};
1888
+ // receive tunnel capabilities
1889
+ for (let i = 0; i < numTunnels; i++) {
1890
+ const capCode = this._sock.rQshift32();
1891
+ const capVendor = this._sock.rQshiftStr(4);
1892
+ const capSignature = this._sock.rQshiftStr(8);
1893
+ serverSupportedTunnelTypes[capCode] = { vendor: capVendor, signature: capSignature };
1894
+ }
1895
+
1896
+ Log.Debug("Server Tight tunnel types: " + serverSupportedTunnelTypes);
1897
+
1898
+ // Siemens touch panels have a VNC server that supports NOTUNNEL,
1899
+ // but forgets to advertise it. Try to detect such servers by
1900
+ // looking for their custom tunnel type.
1901
+ if (serverSupportedTunnelTypes[1] &&
1902
+ (serverSupportedTunnelTypes[1].vendor === "SICR") &&
1903
+ (serverSupportedTunnelTypes[1].signature === "SCHANNEL")) {
1904
+ Log.Debug("Detected Siemens server. Assuming NOTUNNEL support.");
1905
+ serverSupportedTunnelTypes[0] = { vendor: 'TGHT', signature: 'NOTUNNEL' };
1906
+ }
1907
+
1908
+ // choose the notunnel type
1909
+ if (serverSupportedTunnelTypes[0]) {
1910
+ if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
1911
+ serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
1912
+ return this._fail("Client's tunnel type had the incorrect " +
1913
+ "vendor or signature");
1914
+ }
1915
+ Log.Debug("Selected tunnel type: " + clientSupportedTunnelTypes[0]);
1916
+ this._sock.sQpush32(0); // use NOTUNNEL
1917
+ this._sock.flush();
1918
+ return false; // wait until we receive the sub auth count to continue
1919
+ } else {
1920
+ return this._fail("Server wanted tunnels, but doesn't support " +
1921
+ "the notunnel type");
1922
+ }
1923
+ }
1924
+
1925
+ _negotiateTightAuth() {
1926
+ if (!this._rfbTightVNC) { // first pass, do the tunnel negotiation
1927
+ if (this._sock.rQwait("num tunnels", 4)) { return false; }
1928
+ const numTunnels = this._sock.rQshift32();
1929
+ if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
1930
+
1931
+ this._rfbTightVNC = true;
1932
+
1933
+ if (numTunnels > 0) {
1934
+ this._negotiateTightTunnels(numTunnels);
1935
+ return false; // wait until we receive the sub auth to continue
1936
+ }
1937
+ }
1938
+
1939
+ // second pass, do the sub-auth negotiation
1940
+ if (this._sock.rQwait("sub auth count", 4)) { return false; }
1941
+ const subAuthCount = this._sock.rQshift32();
1942
+ if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
1943
+ this._rfbInitState = 'SecurityResult';
1944
+ return true;
1945
+ }
1946
+
1947
+ if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
1948
+
1949
+ const clientSupportedTypes = {
1950
+ 'STDVNOAUTH__': 1,
1951
+ 'STDVVNCAUTH_': 2,
1952
+ 'TGHTULGNAUTH': 129
1953
+ };
1954
+
1955
+ const serverSupportedTypes = [];
1956
+
1957
+ for (let i = 0; i < subAuthCount; i++) {
1958
+ this._sock.rQshift32(); // capNum
1959
+ const capabilities = this._sock.rQshiftStr(12);
1960
+ serverSupportedTypes.push(capabilities);
1961
+ }
1962
+
1963
+ Log.Debug("Server Tight authentication types: " + serverSupportedTypes);
1964
+
1965
+ for (let authType in clientSupportedTypes) {
1966
+ if (serverSupportedTypes.indexOf(authType) != -1) {
1967
+ this._sock.sQpush32(clientSupportedTypes[authType]);
1968
+ this._sock.flush();
1969
+ Log.Debug("Selected authentication type: " + authType);
1970
+
1971
+ switch (authType) {
1972
+ case 'STDVNOAUTH__': // no auth
1973
+ this._rfbInitState = 'SecurityResult';
1974
+ return true;
1975
+ case 'STDVVNCAUTH_':
1976
+ this._rfbAuthScheme = securityTypeVNCAuth;
1977
+ return true;
1978
+ case 'TGHTULGNAUTH':
1979
+ this._rfbAuthScheme = securityTypeUnixLogon;
1980
+ return true;
1981
+ default:
1982
+ return this._fail("Unsupported tiny auth scheme " +
1983
+ "(scheme: " + authType + ")");
1984
+ }
1985
+ }
1986
+ }
1987
+
1988
+ return this._fail("No supported sub-auth types!");
1989
+ }
1990
+
1991
+ _handleRSAAESCredentialsRequired(event) {
1992
+ this.dispatchEvent(event);
1993
+ }
1994
+
1995
+ _handleRSAAESServerVerification(event) {
1996
+ this.dispatchEvent(event);
1997
+ }
1998
+
1999
+ _negotiateRA2neAuth() {
2000
+ if (this._rfbRSAAESAuthenticationState === null) {
2001
+ this._rfbRSAAESAuthenticationState = new RSAAESAuthenticationState(this._sock, () => this._rfbCredentials);
2002
+ this._rfbRSAAESAuthenticationState.addEventListener(
2003
+ "serververification", this._eventHandlers.handleRSAAESServerVerification);
2004
+ this._rfbRSAAESAuthenticationState.addEventListener(
2005
+ "credentialsrequired", this._eventHandlers.handleRSAAESCredentialsRequired);
2006
+ }
2007
+ this._rfbRSAAESAuthenticationState.checkInternalEvents();
2008
+ if (!this._rfbRSAAESAuthenticationState.hasStarted) {
2009
+ this._rfbRSAAESAuthenticationState.negotiateRA2neAuthAsync()
2010
+ .catch((e) => {
2011
+ if (e.message !== "disconnect normally") {
2012
+ this._fail(e.message);
2013
+ }
2014
+ })
2015
+ .then(() => {
2016
+ this._rfbInitState = "SecurityResult";
2017
+ return true;
2018
+ }).finally(() => {
2019
+ this._rfbRSAAESAuthenticationState.removeEventListener(
2020
+ "serververification", this._eventHandlers.handleRSAAESServerVerification);
2021
+ this._rfbRSAAESAuthenticationState.removeEventListener(
2022
+ "credentialsrequired", this._eventHandlers.handleRSAAESCredentialsRequired);
2023
+ this._rfbRSAAESAuthenticationState = null;
2024
+ });
2025
+ }
2026
+ return false;
2027
+ }
2028
+
2029
+ _negotiateMSLogonIIAuth() {
2030
+ if (this._sock.rQwait("mslogonii dh param", 24)) { return false; }
2031
+
2032
+ if (this._rfbCredentials.username === undefined ||
2033
+ this._rfbCredentials.password === undefined) {
2034
+ this.dispatchEvent(new CustomEvent(
2035
+ "credentialsrequired",
2036
+ { detail: { types: ["username", "password"] } }));
2037
+ return false;
2038
+ }
2039
+
2040
+ const g = this._sock.rQshiftBytes(8);
2041
+ const p = this._sock.rQshiftBytes(8);
2042
+ const A = this._sock.rQshiftBytes(8);
2043
+ const dhKey = legacyCrypto.generateKey({ name: "DH", g: g, p: p }, true, ["deriveBits"]);
2044
+ const B = legacyCrypto.exportKey("raw", dhKey.publicKey);
2045
+ const secret = legacyCrypto.deriveBits({ name: "DH", public: A }, dhKey.privateKey, 64);
2046
+
2047
+ const key = legacyCrypto.importKey("raw", secret, { name: "DES-CBC" }, false, ["encrypt"]);
2048
+ const username = encodeUTF8(this._rfbCredentials.username).substring(0, 255);
2049
+ const password = encodeUTF8(this._rfbCredentials.password).substring(0, 63);
2050
+ let usernameBytes = new Uint8Array(256);
2051
+ let passwordBytes = new Uint8Array(64);
2052
+ window.crypto.getRandomValues(usernameBytes);
2053
+ window.crypto.getRandomValues(passwordBytes);
2054
+ for (let i = 0; i < username.length; i++) {
2055
+ usernameBytes[i] = username.charCodeAt(i);
2056
+ }
2057
+ usernameBytes[username.length] = 0;
2058
+ for (let i = 0; i < password.length; i++) {
2059
+ passwordBytes[i] = password.charCodeAt(i);
2060
+ }
2061
+ passwordBytes[password.length] = 0;
2062
+ usernameBytes = legacyCrypto.encrypt({ name: "DES-CBC", iv: secret }, key, usernameBytes);
2063
+ passwordBytes = legacyCrypto.encrypt({ name: "DES-CBC", iv: secret }, key, passwordBytes);
2064
+ this._sock.sQpushBytes(B);
2065
+ this._sock.sQpushBytes(usernameBytes);
2066
+ this._sock.sQpushBytes(passwordBytes);
2067
+ this._sock.flush();
2068
+ this._rfbInitState = "SecurityResult";
2069
+ return true;
2070
+ }
2071
+
2072
+ _negotiateAuthentication() {
2073
+ switch (this._rfbAuthScheme) {
2074
+ case securityTypeNone:
2075
+ if (this._rfbVersion >= 3.8) {
2076
+ this._rfbInitState = 'SecurityResult';
2077
+ } else {
2078
+ this._rfbInitState = 'ClientInitialisation';
2079
+ }
2080
+ return true;
2081
+
2082
+ case securityTypeXVP:
2083
+ return this._negotiateXvpAuth();
2084
+
2085
+ case securityTypeARD:
2086
+ return this._negotiateARDAuth();
2087
+
2088
+ case securityTypeVNCAuth:
2089
+ return this._negotiateStdVNCAuth();
2090
+
2091
+ case securityTypeTight:
2092
+ return this._negotiateTightAuth();
2093
+
2094
+ case securityTypeVeNCrypt:
2095
+ return this._negotiateVeNCryptAuth();
2096
+
2097
+ case securityTypePlain:
2098
+ return this._negotiatePlainAuth();
2099
+
2100
+ case securityTypeUnixLogon:
2101
+ return this._negotiateTightUnixAuth();
2102
+
2103
+ case securityTypeRA2ne:
2104
+ return this._negotiateRA2neAuth();
2105
+
2106
+ case securityTypeMSLogonII:
2107
+ return this._negotiateMSLogonIIAuth();
2108
+
2109
+ default:
2110
+ return this._fail("Unsupported auth scheme (scheme: " +
2111
+ this._rfbAuthScheme + ")");
2112
+ }
2113
+ }
2114
+
2115
+ _handleSecurityResult() {
2116
+ if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
2117
+
2118
+ const status = this._sock.rQshift32();
2119
+
2120
+ if (status === 0) { // OK
2121
+ this._rfbInitState = 'ClientInitialisation';
2122
+ Log.Debug('Authentication OK');
2123
+ return true;
2124
+ } else {
2125
+ if (this._rfbVersion >= 3.8) {
2126
+ this._rfbInitState = "SecurityReason";
2127
+ this._securityContext = "security result";
2128
+ this._securityStatus = status;
2129
+ return true;
2130
+ } else {
2131
+ this.dispatchEvent(new CustomEvent(
2132
+ "securityfailure",
2133
+ { detail: { status: status } }));
2134
+
2135
+ return this._fail("Security handshake failed");
2136
+ }
2137
+ }
2138
+ }
2139
+
2140
+ _negotiateServerInit() {
2141
+ if (this._sock.rQwait("server initialization", 24)) { return false; }
2142
+
2143
+ /* Screen size */
2144
+ const width = this._sock.rQshift16();
2145
+ const height = this._sock.rQshift16();
2146
+
2147
+ /* PIXEL_FORMAT */
2148
+ const bpp = this._sock.rQshift8();
2149
+ const depth = this._sock.rQshift8();
2150
+ const bigEndian = this._sock.rQshift8();
2151
+ const trueColor = this._sock.rQshift8();
2152
+
2153
+ const redMax = this._sock.rQshift16();
2154
+ const greenMax = this._sock.rQshift16();
2155
+ const blueMax = this._sock.rQshift16();
2156
+ const redShift = this._sock.rQshift8();
2157
+ const greenShift = this._sock.rQshift8();
2158
+ const blueShift = this._sock.rQshift8();
2159
+ this._sock.rQskipBytes(3); // padding
2160
+
2161
+ // NB(directxman12): we don't want to call any callbacks or print messages until
2162
+ // *after* we're past the point where we could backtrack
2163
+
2164
+ /* Connection name/title */
2165
+ const nameLength = this._sock.rQshift32();
2166
+ if (this._sock.rQwait('server init name', nameLength, 24)) { return false; }
2167
+ let name = this._sock.rQshiftStr(nameLength);
2168
+ name = decodeUTF8(name, true);
2169
+
2170
+ if (this._rfbTightVNC) {
2171
+ if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + nameLength)) { return false; }
2172
+ // In TightVNC mode, ServerInit message is extended
2173
+ const numServerMessages = this._sock.rQshift16();
2174
+ const numClientMessages = this._sock.rQshift16();
2175
+ const numEncodings = this._sock.rQshift16();
2176
+ this._sock.rQskipBytes(2); // padding
2177
+
2178
+ const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
2179
+ if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + nameLength)) { return false; }
2180
+
2181
+ // we don't actually do anything with the capability information that TIGHT sends,
2182
+ // so we just skip the all of this.
2183
+
2184
+ // TIGHT server message capabilities
2185
+ this._sock.rQskipBytes(16 * numServerMessages);
2186
+
2187
+ // TIGHT client message capabilities
2188
+ this._sock.rQskipBytes(16 * numClientMessages);
2189
+
2190
+ // TIGHT encoding capabilities
2191
+ this._sock.rQskipBytes(16 * numEncodings);
2192
+ }
2193
+
2194
+ // NB(directxman12): these are down here so that we don't run them multiple times
2195
+ // if we backtrack
2196
+ Log.Info("Screen: " + width + "x" + height +
2197
+ ", bpp: " + bpp + ", depth: " + depth +
2198
+ ", bigEndian: " + bigEndian +
2199
+ ", trueColor: " + trueColor +
2200
+ ", redMax: " + redMax +
2201
+ ", greenMax: " + greenMax +
2202
+ ", blueMax: " + blueMax +
2203
+ ", redShift: " + redShift +
2204
+ ", greenShift: " + greenShift +
2205
+ ", blueShift: " + blueShift);
2206
+
2207
+ // we're past the point where we could backtrack, so it's safe to call this
2208
+ this._setDesktopName(name);
2209
+ this._resize(width, height);
2210
+
2211
+ if (!this._viewOnly) { this._keyboard.grab(); }
2212
+
2213
+ this._fbDepth = 24;
2214
+
2215
+ if (this._fbName === "Intel(r) AMT KVM") {
2216
+ Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
2217
+ this._fbDepth = 8;
2218
+ }
2219
+
2220
+ RFB.messages.pixelFormat(this._sock, this._fbDepth, true);
2221
+ this._sendEncodings();
2222
+ RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fbWidth, this._fbHeight);
2223
+
2224
+ this._updateConnectionState('connected');
2225
+ return true;
2226
+ }
2227
+
2228
+ _sendEncodings() {
2229
+ const encs = [];
2230
+
2231
+ // In preference order
2232
+ encs.push(encodings.encodingCopyRect);
2233
+ // Only supported with full depth support
2234
+ if (this._fbDepth == 24) {
2235
+ if (supportsWebCodecsH264Decode) {
2236
+ encs.push(encodings.encodingH264);
2237
+ }
2238
+ encs.push(encodings.encodingTight);
2239
+ encs.push(encodings.encodingTightPNG);
2240
+ encs.push(encodings.encodingZRLE);
2241
+ encs.push(encodings.encodingJPEG);
2242
+ encs.push(encodings.encodingHextile);
2243
+ encs.push(encodings.encodingRRE);
2244
+ encs.push(encodings.encodingZlib);
2245
+ }
2246
+ encs.push(encodings.encodingRaw);
2247
+
2248
+ // Psuedo-encoding settings
2249
+ encs.push(encodings.pseudoEncodingQualityLevel0 + this._qualityLevel);
2250
+ encs.push(encodings.pseudoEncodingCompressLevel0 + this._compressionLevel);
2251
+
2252
+ encs.push(encodings.pseudoEncodingDesktopSize);
2253
+ encs.push(encodings.pseudoEncodingLastRect);
2254
+ encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
2255
+ encs.push(encodings.pseudoEncodingQEMULedEvent);
2256
+ encs.push(encodings.pseudoEncodingExtendedDesktopSize);
2257
+ encs.push(encodings.pseudoEncodingXvp);
2258
+ encs.push(encodings.pseudoEncodingFence);
2259
+ encs.push(encodings.pseudoEncodingContinuousUpdates);
2260
+ encs.push(encodings.pseudoEncodingDesktopName);
2261
+ encs.push(encodings.pseudoEncodingExtendedClipboard);
2262
+ encs.push(encodings.pseudoEncodingExtendedMouseButtons);
2263
+
2264
+ if (this._fbDepth == 24) {
2265
+ encs.push(encodings.pseudoEncodingVMwareCursor);
2266
+ encs.push(encodings.pseudoEncodingCursor);
2267
+ }
2268
+
2269
+ RFB.messages.clientEncodings(this._sock, encs);
2270
+ }
2271
+
2272
+ /* RFB protocol initialization states:
2273
+ * ProtocolVersion
2274
+ * Security
2275
+ * Authentication
2276
+ * SecurityResult
2277
+ * ClientInitialization - not triggered by server message
2278
+ * ServerInitialization
2279
+ */
2280
+ _initMsg() {
2281
+ switch (this._rfbInitState) {
2282
+ case 'ProtocolVersion':
2283
+ return this._negotiateProtocolVersion();
2284
+
2285
+ case 'Security':
2286
+ return this._negotiateSecurity();
2287
+
2288
+ case 'Authentication':
2289
+ return this._negotiateAuthentication();
2290
+
2291
+ case 'SecurityResult':
2292
+ return this._handleSecurityResult();
2293
+
2294
+ case 'SecurityReason':
2295
+ return this._handleSecurityReason();
2296
+
2297
+ case 'ClientInitialisation':
2298
+ this._sock.sQpush8(this._shared ? 1 : 0); // ClientInitialisation
2299
+ this._sock.flush();
2300
+ this._rfbInitState = 'ServerInitialisation';
2301
+ return true;
2302
+
2303
+ case 'ServerInitialisation':
2304
+ return this._negotiateServerInit();
2305
+
2306
+ default:
2307
+ return this._fail("Unknown init state (state: " +
2308
+ this._rfbInitState + ")");
2309
+ }
2310
+ }
2311
+
2312
+ // Resume authentication handshake after it was paused for some
2313
+ // reason, e.g. waiting for a password from the user
2314
+ _resumeAuthentication() {
2315
+ // We use setTimeout() so it's run in its own context, just like
2316
+ // it originally did via the WebSocket's event handler
2317
+ setTimeout(this._initMsg.bind(this), 0);
2318
+ }
2319
+
2320
+ _handleSetColourMapMsg() {
2321
+ Log.Debug("SetColorMapEntries");
2322
+
2323
+ return this._fail("Unexpected SetColorMapEntries message");
2324
+ }
2325
+
2326
+ _handleServerCutText() {
2327
+ Log.Debug("ServerCutText");
2328
+
2329
+ if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
2330
+
2331
+ this._sock.rQskipBytes(3); // Padding
2332
+
2333
+ let length = this._sock.rQshift32();
2334
+ length = toSigned32bit(length);
2335
+
2336
+ if (this._sock.rQwait("ServerCutText content", Math.abs(length), 8)) { return false; }
2337
+
2338
+ if (length >= 0) {
2339
+ //Standard msg
2340
+ const text = this._sock.rQshiftStr(length);
2341
+ if (this._viewOnly) {
2342
+ return true;
2343
+ }
2344
+
2345
+ this.dispatchEvent(new CustomEvent(
2346
+ "clipboard",
2347
+ { detail: { text: text } }));
2348
+
2349
+ } else {
2350
+ //Extended msg.
2351
+ length = Math.abs(length);
2352
+ const flags = this._sock.rQshift32();
2353
+ let formats = flags & 0x0000FFFF;
2354
+ let actions = flags & 0xFF000000;
2355
+
2356
+ let isCaps = (!!(actions & extendedClipboardActionCaps));
2357
+ if (isCaps) {
2358
+ this._clipboardServerCapabilitiesFormats = {};
2359
+ this._clipboardServerCapabilitiesActions = {};
2360
+
2361
+ // Update our server capabilities for Formats
2362
+ for (let i = 0; i <= 15; i++) {
2363
+ let index = 1 << i;
2364
+
2365
+ // Check if format flag is set.
2366
+ if ((formats & index)) {
2367
+ this._clipboardServerCapabilitiesFormats[index] = true;
2368
+ // We don't send unsolicited clipboard, so we
2369
+ // ignore the size
2370
+ this._sock.rQshift32();
2371
+ }
2372
+ }
2373
+
2374
+ // Update our server capabilities for Actions
2375
+ for (let i = 24; i <= 31; i++) {
2376
+ let index = 1 << i;
2377
+ this._clipboardServerCapabilitiesActions[index] = !!(actions & index);
2378
+ }
2379
+
2380
+ /* Caps handling done, send caps with the clients
2381
+ capabilities set as a response */
2382
+ let clientActions = [
2383
+ extendedClipboardActionCaps,
2384
+ extendedClipboardActionRequest,
2385
+ extendedClipboardActionPeek,
2386
+ extendedClipboardActionNotify,
2387
+ extendedClipboardActionProvide
2388
+ ];
2389
+ RFB.messages.extendedClipboardCaps(this._sock, clientActions, {extendedClipboardFormatText: 0});
2390
+
2391
+ } else if (actions === extendedClipboardActionRequest) {
2392
+ if (this._viewOnly) {
2393
+ return true;
2394
+ }
2395
+
2396
+ // Check if server has told us it can handle Provide and there is clipboard data to send.
2397
+ if (this._clipboardText != null &&
2398
+ this._clipboardServerCapabilitiesActions[extendedClipboardActionProvide]) {
2399
+
2400
+ if (formats & extendedClipboardFormatText) {
2401
+ RFB.messages.extendedClipboardProvide(this._sock, [extendedClipboardFormatText], [this._clipboardText]);
2402
+ }
2403
+ }
2404
+
2405
+ } else if (actions === extendedClipboardActionPeek) {
2406
+ if (this._viewOnly) {
2407
+ return true;
2408
+ }
2409
+
2410
+ if (this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) {
2411
+
2412
+ if (this._clipboardText != null) {
2413
+ RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]);
2414
+ } else {
2415
+ RFB.messages.extendedClipboardNotify(this._sock, []);
2416
+ }
2417
+ }
2418
+
2419
+ } else if (actions === extendedClipboardActionNotify) {
2420
+ if (this._viewOnly) {
2421
+ return true;
2422
+ }
2423
+
2424
+ if (this._clipboardServerCapabilitiesActions[extendedClipboardActionRequest]) {
2425
+
2426
+ if (formats & extendedClipboardFormatText) {
2427
+ RFB.messages.extendedClipboardRequest(this._sock, [extendedClipboardFormatText]);
2428
+ }
2429
+ }
2430
+
2431
+ } else if (actions === extendedClipboardActionProvide) {
2432
+ if (this._viewOnly) {
2433
+ return true;
2434
+ }
2435
+
2436
+ if (!(formats & extendedClipboardFormatText)) {
2437
+ return true;
2438
+ }
2439
+ // Ignore what we had in our clipboard client side.
2440
+ this._clipboardText = null;
2441
+
2442
+ // FIXME: Should probably verify that this data was actually requested
2443
+ let zlibStream = this._sock.rQshiftBytes(length - 4);
2444
+ let streamInflator = new Inflator();
2445
+ let textData = null;
2446
+
2447
+ streamInflator.setInput(zlibStream);
2448
+ for (let i = 0; i <= 15; i++) {
2449
+ let format = 1 << i;
2450
+
2451
+ if (formats & format) {
2452
+
2453
+ let size = 0x00;
2454
+ let sizeArray = streamInflator.inflate(4);
2455
+
2456
+ size |= (sizeArray[0] << 24);
2457
+ size |= (sizeArray[1] << 16);
2458
+ size |= (sizeArray[2] << 8);
2459
+ size |= (sizeArray[3]);
2460
+ let chunk = streamInflator.inflate(size);
2461
+
2462
+ if (format === extendedClipboardFormatText) {
2463
+ textData = chunk;
2464
+ }
2465
+ }
2466
+ }
2467
+ streamInflator.setInput(null);
2468
+
2469
+ if (textData !== null) {
2470
+ let tmpText = "";
2471
+ for (let i = 0; i < textData.length; i++) {
2472
+ tmpText += String.fromCharCode(textData[i]);
2473
+ }
2474
+ textData = tmpText;
2475
+
2476
+ textData = decodeUTF8(textData);
2477
+ if ((textData.length > 0) && "\0" === textData.charAt(textData.length - 1)) {
2478
+ textData = textData.slice(0, -1);
2479
+ }
2480
+
2481
+ textData = textData.replaceAll("\r\n", "\n");
2482
+
2483
+ this.dispatchEvent(new CustomEvent(
2484
+ "clipboard",
2485
+ { detail: { text: textData } }));
2486
+ }
2487
+ } else {
2488
+ return this._fail("Unexpected action in extended clipboard message: " + actions);
2489
+ }
2490
+ }
2491
+ return true;
2492
+ }
2493
+
2494
+ _handleServerFenceMsg() {
2495
+ if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
2496
+ this._sock.rQskipBytes(3); // Padding
2497
+ let flags = this._sock.rQshift32();
2498
+ let length = this._sock.rQshift8();
2499
+
2500
+ if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
2501
+
2502
+ if (length > 64) {
2503
+ Log.Warn("Bad payload length (" + length + ") in fence response");
2504
+ length = 64;
2505
+ }
2506
+
2507
+ const payload = this._sock.rQshiftStr(length);
2508
+
2509
+ this._supportsFence = true;
2510
+
2511
+ /*
2512
+ * Fence flags
2513
+ *
2514
+ * (1<<0) - BlockBefore
2515
+ * (1<<1) - BlockAfter
2516
+ * (1<<2) - SyncNext
2517
+ * (1<<31) - Request
2518
+ */
2519
+
2520
+ if (!(flags & (1<<31))) {
2521
+ return this._fail("Unexpected fence response");
2522
+ }
2523
+
2524
+ // Filter out unsupported flags
2525
+ // FIXME: support syncNext
2526
+ flags &= (1<<0) | (1<<1);
2527
+
2528
+ // BlockBefore and BlockAfter are automatically handled by
2529
+ // the fact that we process each incoming message
2530
+ // synchronuosly.
2531
+ RFB.messages.clientFence(this._sock, flags, payload);
2532
+
2533
+ return true;
2534
+ }
2535
+
2536
+ _handleXvpMsg() {
2537
+ if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
2538
+ this._sock.rQskipBytes(1); // Padding
2539
+ const xvpVer = this._sock.rQshift8();
2540
+ const xvpMsg = this._sock.rQshift8();
2541
+
2542
+ switch (xvpMsg) {
2543
+ case 0: // XVP_FAIL
2544
+ Log.Error("XVP operation failed");
2545
+ break;
2546
+ case 1: // XVP_INIT
2547
+ this._rfbXvpVer = xvpVer;
2548
+ Log.Info("XVP extensions enabled (version " + this._rfbXvpVer + ")");
2549
+ this._setCapability("power", true);
2550
+ break;
2551
+ default:
2552
+ this._fail("Illegal server XVP message (msg: " + xvpMsg + ")");
2553
+ break;
2554
+ }
2555
+
2556
+ return true;
2557
+ }
2558
+
2559
+ _normalMsg() {
2560
+ let msgType;
2561
+ if (this._FBU.rects > 0) {
2562
+ msgType = 0;
2563
+ } else {
2564
+ msgType = this._sock.rQshift8();
2565
+ }
2566
+
2567
+ let first, ret;
2568
+ switch (msgType) {
2569
+ case 0: // FramebufferUpdate
2570
+ ret = this._framebufferUpdate();
2571
+ if (ret && !this._enabledContinuousUpdates) {
2572
+ RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
2573
+ this._fbWidth, this._fbHeight);
2574
+ }
2575
+ return ret;
2576
+
2577
+ case 1: // SetColorMapEntries
2578
+ return this._handleSetColourMapMsg();
2579
+
2580
+ case 2: // Bell
2581
+ Log.Debug("Bell");
2582
+ this.dispatchEvent(new CustomEvent(
2583
+ "bell",
2584
+ { detail: {} }));
2585
+ return true;
2586
+
2587
+ case 3: // ServerCutText
2588
+ return this._handleServerCutText();
2589
+
2590
+ case 150: // EndOfContinuousUpdates
2591
+ first = !this._supportsContinuousUpdates;
2592
+ this._supportsContinuousUpdates = true;
2593
+ this._enabledContinuousUpdates = false;
2594
+ if (first) {
2595
+ this._enabledContinuousUpdates = true;
2596
+ this._updateContinuousUpdates();
2597
+ Log.Info("Enabling continuous updates.");
2598
+ } else {
2599
+ // FIXME: We need to send a framebufferupdaterequest here
2600
+ // if we add support for turning off continuous updates
2601
+ }
2602
+ return true;
2603
+
2604
+ case 248: // ServerFence
2605
+ return this._handleServerFenceMsg();
2606
+
2607
+ case 250: // XVP
2608
+ return this._handleXvpMsg();
2609
+
2610
+ default:
2611
+ this._fail("Unexpected server message (type " + msgType + ")");
2612
+ Log.Debug("sock.rQpeekBytes(30): " + this._sock.rQpeekBytes(30));
2613
+ return true;
2614
+ }
2615
+ }
2616
+
2617
+ _framebufferUpdate() {
2618
+ if (this._FBU.rects === 0) {
2619
+ if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
2620
+ this._sock.rQskipBytes(1); // Padding
2621
+ this._FBU.rects = this._sock.rQshift16();
2622
+
2623
+ // Make sure the previous frame is fully rendered first
2624
+ // to avoid building up an excessive queue
2625
+ if (this._display.pending()) {
2626
+ this._flushing = true;
2627
+ this._display.flush()
2628
+ .then(() => {
2629
+ this._flushing = false;
2630
+ // Resume processing
2631
+ if (!this._sock.rQwait("message", 1)) {
2632
+ this._handleMessage();
2633
+ }
2634
+ });
2635
+ return false;
2636
+ }
2637
+ }
2638
+
2639
+ while (this._FBU.rects > 0) {
2640
+ if (this._FBU.encoding === null) {
2641
+ if (this._sock.rQwait("rect header", 12)) { return false; }
2642
+ /* New FramebufferUpdate */
2643
+
2644
+ this._FBU.x = this._sock.rQshift16();
2645
+ this._FBU.y = this._sock.rQshift16();
2646
+ this._FBU.width = this._sock.rQshift16();
2647
+ this._FBU.height = this._sock.rQshift16();
2648
+ this._FBU.encoding = this._sock.rQshift32();
2649
+ /* Encodings are signed */
2650
+ this._FBU.encoding >>= 0;
2651
+ }
2652
+
2653
+ if (!this._handleRect()) {
2654
+ return false;
2655
+ }
2656
+
2657
+ this._FBU.rects--;
2658
+ this._FBU.encoding = null;
2659
+ }
2660
+
2661
+ this._display.flip();
2662
+
2663
+ return true; // We finished this FBU
2664
+ }
2665
+
2666
+ _handleRect() {
2667
+ switch (this._FBU.encoding) {
2668
+ case encodings.pseudoEncodingLastRect:
2669
+ this._FBU.rects = 1; // Will be decreased when we return
2670
+ return true;
2671
+
2672
+ case encodings.pseudoEncodingVMwareCursor:
2673
+ return this._handleVMwareCursor();
2674
+
2675
+ case encodings.pseudoEncodingCursor:
2676
+ return this._handleCursor();
2677
+
2678
+ case encodings.pseudoEncodingQEMUExtendedKeyEvent:
2679
+ this._qemuExtKeyEventSupported = true;
2680
+ return true;
2681
+
2682
+ case encodings.pseudoEncodingDesktopName:
2683
+ return this._handleDesktopName();
2684
+
2685
+ case encodings.pseudoEncodingDesktopSize:
2686
+ this._resize(this._FBU.width, this._FBU.height);
2687
+ return true;
2688
+
2689
+ case encodings.pseudoEncodingExtendedDesktopSize:
2690
+ return this._handleExtendedDesktopSize();
2691
+
2692
+ case encodings.pseudoEncodingExtendedMouseButtons:
2693
+ this._extendedPointerEventSupported = true;
2694
+ return true;
2695
+
2696
+ case encodings.pseudoEncodingQEMULedEvent:
2697
+ return this._handleLedEvent();
2698
+
2699
+ default:
2700
+ return this._handleDataRect();
2701
+ }
2702
+ }
2703
+
2704
+ _handleVMwareCursor() {
2705
+ const hotx = this._FBU.x; // hotspot-x
2706
+ const hoty = this._FBU.y; // hotspot-y
2707
+ const w = this._FBU.width;
2708
+ const h = this._FBU.height;
2709
+ if (this._sock.rQwait("VMware cursor encoding", 1)) {
2710
+ return false;
2711
+ }
2712
+
2713
+ const cursorType = this._sock.rQshift8();
2714
+
2715
+ this._sock.rQshift8(); //Padding
2716
+
2717
+ let rgba;
2718
+ const bytesPerPixel = 4;
2719
+
2720
+ //Classic cursor
2721
+ if (cursorType == 0) {
2722
+ //Used to filter away unimportant bits.
2723
+ //OR is used for correct conversion in js.
2724
+ const PIXEL_MASK = 0xffffff00 | 0;
2725
+ rgba = new Array(w * h * bytesPerPixel);
2726
+
2727
+ if (this._sock.rQwait("VMware cursor classic encoding",
2728
+ (w * h * bytesPerPixel) * 2, 2)) {
2729
+ return false;
2730
+ }
2731
+
2732
+ let andMask = new Array(w * h);
2733
+ for (let pixel = 0; pixel < (w * h); pixel++) {
2734
+ andMask[pixel] = this._sock.rQshift32();
2735
+ }
2736
+
2737
+ let xorMask = new Array(w * h);
2738
+ for (let pixel = 0; pixel < (w * h); pixel++) {
2739
+ xorMask[pixel] = this._sock.rQshift32();
2740
+ }
2741
+
2742
+ for (let pixel = 0; pixel < (w * h); pixel++) {
2743
+ if (andMask[pixel] == 0) {
2744
+ //Fully opaque pixel
2745
+ let bgr = xorMask[pixel];
2746
+ let r = bgr >> 8 & 0xff;
2747
+ let g = bgr >> 16 & 0xff;
2748
+ let b = bgr >> 24 & 0xff;
2749
+
2750
+ rgba[(pixel * bytesPerPixel) ] = r; //r
2751
+ rgba[(pixel * bytesPerPixel) + 1 ] = g; //g
2752
+ rgba[(pixel * bytesPerPixel) + 2 ] = b; //b
2753
+ rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; //a
2754
+
2755
+ } else if ((andMask[pixel] & PIXEL_MASK) ==
2756
+ PIXEL_MASK) {
2757
+ //Only screen value matters, no mouse colouring
2758
+ if (xorMask[pixel] == 0) {
2759
+ //Transparent pixel
2760
+ rgba[(pixel * bytesPerPixel) ] = 0x00;
2761
+ rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
2762
+ rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
2763
+ rgba[(pixel * bytesPerPixel) + 3 ] = 0x00;
2764
+
2765
+ } else if ((xorMask[pixel] & PIXEL_MASK) ==
2766
+ PIXEL_MASK) {
2767
+ //Inverted pixel, not supported in browsers.
2768
+ //Fully opaque instead.
2769
+ rgba[(pixel * bytesPerPixel) ] = 0x00;
2770
+ rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
2771
+ rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
2772
+ rgba[(pixel * bytesPerPixel) + 3 ] = 0xff;
2773
+
2774
+ } else {
2775
+ //Unhandled xorMask
2776
+ rgba[(pixel * bytesPerPixel) ] = 0x00;
2777
+ rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
2778
+ rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
2779
+ rgba[(pixel * bytesPerPixel) + 3 ] = 0xff;
2780
+ }
2781
+
2782
+ } else {
2783
+ //Unhandled andMask
2784
+ rgba[(pixel * bytesPerPixel) ] = 0x00;
2785
+ rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
2786
+ rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
2787
+ rgba[(pixel * bytesPerPixel) + 3 ] = 0xff;
2788
+ }
2789
+ }
2790
+
2791
+ //Alpha cursor.
2792
+ } else if (cursorType == 1) {
2793
+ if (this._sock.rQwait("VMware cursor alpha encoding",
2794
+ (w * h * 4), 2)) {
2795
+ return false;
2796
+ }
2797
+
2798
+ rgba = new Array(w * h * bytesPerPixel);
2799
+
2800
+ for (let pixel = 0; pixel < (w * h); pixel++) {
2801
+ let data = this._sock.rQshift32();
2802
+
2803
+ rgba[(pixel * 4) ] = data >> 24 & 0xff; //r
2804
+ rgba[(pixel * 4) + 1 ] = data >> 16 & 0xff; //g
2805
+ rgba[(pixel * 4) + 2 ] = data >> 8 & 0xff; //b
2806
+ rgba[(pixel * 4) + 3 ] = data & 0xff; //a
2807
+ }
2808
+
2809
+ } else {
2810
+ Log.Warn("The given cursor type is not supported: "
2811
+ + cursorType + " given.");
2812
+ return false;
2813
+ }
2814
+
2815
+ this._updateCursor(rgba, hotx, hoty, w, h);
2816
+
2817
+ return true;
2818
+ }
2819
+
2820
+ _handleCursor() {
2821
+ const hotx = this._FBU.x; // hotspot-x
2822
+ const hoty = this._FBU.y; // hotspot-y
2823
+ const w = this._FBU.width;
2824
+ const h = this._FBU.height;
2825
+
2826
+ const pixelslength = w * h * 4;
2827
+ const masklength = Math.ceil(w / 8) * h;
2828
+
2829
+ let bytes = pixelslength + masklength;
2830
+ if (this._sock.rQwait("cursor encoding", bytes)) {
2831
+ return false;
2832
+ }
2833
+
2834
+ // Decode from BGRX pixels + bit mask to RGBA
2835
+ const pixels = this._sock.rQshiftBytes(pixelslength);
2836
+ const mask = this._sock.rQshiftBytes(masklength);
2837
+ let rgba = new Uint8Array(w * h * 4);
2838
+
2839
+ let pixIdx = 0;
2840
+ for (let y = 0; y < h; y++) {
2841
+ for (let x = 0; x < w; x++) {
2842
+ let maskIdx = y * Math.ceil(w / 8) + Math.floor(x / 8);
2843
+ let alpha = (mask[maskIdx] << (x % 8)) & 0x80 ? 255 : 0;
2844
+ rgba[pixIdx ] = pixels[pixIdx + 2];
2845
+ rgba[pixIdx + 1] = pixels[pixIdx + 1];
2846
+ rgba[pixIdx + 2] = pixels[pixIdx];
2847
+ rgba[pixIdx + 3] = alpha;
2848
+ pixIdx += 4;
2849
+ }
2850
+ }
2851
+
2852
+ this._updateCursor(rgba, hotx, hoty, w, h);
2853
+
2854
+ return true;
2855
+ }
2856
+
2857
+ _handleDesktopName() {
2858
+ if (this._sock.rQwait("DesktopName", 4)) {
2859
+ return false;
2860
+ }
2861
+
2862
+ let length = this._sock.rQshift32();
2863
+
2864
+ if (this._sock.rQwait("DesktopName", length, 4)) {
2865
+ return false;
2866
+ }
2867
+
2868
+ let name = this._sock.rQshiftStr(length);
2869
+ name = decodeUTF8(name, true);
2870
+
2871
+ this._setDesktopName(name);
2872
+
2873
+ return true;
2874
+ }
2875
+
2876
+ _handleLedEvent() {
2877
+ if (this._sock.rQwait("LED status", 1)) {
2878
+ return false;
2879
+ }
2880
+
2881
+ let data = this._sock.rQshift8();
2882
+ // ScrollLock state can be retrieved with data & 1. This is currently not needed.
2883
+ let numLock = data & 2 ? true : false;
2884
+ let capsLock = data & 4 ? true : false;
2885
+ this._remoteCapsLock = capsLock;
2886
+ this._remoteNumLock = numLock;
2887
+
2888
+ return true;
2889
+ }
2890
+
2891
+ _handleExtendedDesktopSize() {
2892
+ if (this._sock.rQwait("ExtendedDesktopSize", 4)) {
2893
+ return false;
2894
+ }
2895
+
2896
+ const numberOfScreens = this._sock.rQpeek8();
2897
+
2898
+ let bytes = 4 + (numberOfScreens * 16);
2899
+ if (this._sock.rQwait("ExtendedDesktopSize", bytes)) {
2900
+ return false;
2901
+ }
2902
+
2903
+ const firstUpdate = !this._supportsSetDesktopSize;
2904
+ this._supportsSetDesktopSize = true;
2905
+
2906
+ this._sock.rQskipBytes(1); // number-of-screens
2907
+ this._sock.rQskipBytes(3); // padding
2908
+
2909
+ for (let i = 0; i < numberOfScreens; i += 1) {
2910
+ // Save the id and flags of the first screen
2911
+ if (i === 0) {
2912
+ this._screenID = this._sock.rQshift32(); // id
2913
+ this._sock.rQskipBytes(2); // x-position
2914
+ this._sock.rQskipBytes(2); // y-position
2915
+ this._sock.rQskipBytes(2); // width
2916
+ this._sock.rQskipBytes(2); // height
2917
+ this._screenFlags = this._sock.rQshift32(); // flags
2918
+ } else {
2919
+ this._sock.rQskipBytes(16);
2920
+ }
2921
+ }
2922
+
2923
+ /*
2924
+ * The x-position indicates the reason for the change:
2925
+ *
2926
+ * 0 - server resized on its own
2927
+ * 1 - this client requested the resize
2928
+ * 2 - another client requested the resize
2929
+ */
2930
+
2931
+ if (this._FBU.x === 1) {
2932
+ this._pendingRemoteResize = false;
2933
+ }
2934
+
2935
+ // We need to handle errors when we requested the resize.
2936
+ if (this._FBU.x === 1 && this._FBU.y !== 0) {
2937
+ let msg = "";
2938
+ // The y-position indicates the status code from the server
2939
+ switch (this._FBU.y) {
2940
+ case 1:
2941
+ msg = "Resize is administratively prohibited";
2942
+ break;
2943
+ case 2:
2944
+ msg = "Out of resources";
2945
+ break;
2946
+ case 3:
2947
+ msg = "Invalid screen layout";
2948
+ break;
2949
+ default:
2950
+ msg = "Unknown reason";
2951
+ break;
2952
+ }
2953
+ Log.Warn("Server did not accept the resize request: "
2954
+ + msg);
2955
+ } else {
2956
+ this._resize(this._FBU.width, this._FBU.height);
2957
+ }
2958
+
2959
+ // Normally we only apply the current resize mode after a
2960
+ // window resize event. However there is no such trigger on the
2961
+ // initial connect. And we don't know if the server supports
2962
+ // resizing until we've gotten here.
2963
+ if (firstUpdate) {
2964
+ this._requestRemoteResize();
2965
+ }
2966
+
2967
+ if (this._FBU.x === 1 && this._FBU.y === 0) {
2968
+ // We might have resized again whilst waiting for the
2969
+ // previous request, so check if we are in sync
2970
+ this._requestRemoteResize();
2971
+ }
2972
+
2973
+ return true;
2974
+ }
2975
+
2976
+ _handleDataRect() {
2977
+ let decoder = this._decoders[this._FBU.encoding];
2978
+ if (!decoder) {
2979
+ this._fail("Unsupported encoding (encoding: " +
2980
+ this._FBU.encoding + ")");
2981
+ return false;
2982
+ }
2983
+
2984
+ try {
2985
+ return decoder.decodeRect(this._FBU.x, this._FBU.y,
2986
+ this._FBU.width, this._FBU.height,
2987
+ this._sock, this._display,
2988
+ this._fbDepth);
2989
+ } catch (err) {
2990
+ this._fail("Error decoding rect: " + err);
2991
+ return false;
2992
+ }
2993
+ }
2994
+
2995
+ _updateContinuousUpdates() {
2996
+ if (!this._enabledContinuousUpdates) { return; }
2997
+
2998
+ RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
2999
+ this._fbWidth, this._fbHeight);
3000
+ }
3001
+
3002
+ // Handle resize-messages from the server
3003
+ _resize(width, height) {
3004
+ this._fbWidth = width;
3005
+ this._fbHeight = height;
3006
+
3007
+ this._display.resize(this._fbWidth, this._fbHeight);
3008
+
3009
+ // Adjust the visible viewport based on the new dimensions
3010
+ this._updateClip();
3011
+ this._updateScale();
3012
+
3013
+ this._updateContinuousUpdates();
3014
+
3015
+ // Keep this size until browser client size changes
3016
+ this._saveExpectedClientSize();
3017
+ }
3018
+
3019
+ _xvpOp(ver, op) {
3020
+ if (this._rfbXvpVer < ver) { return; }
3021
+ Log.Info("Sending XVP operation " + op + " (version " + ver + ")");
3022
+ RFB.messages.xvpOp(this._sock, ver, op);
3023
+ }
3024
+
3025
+ _updateCursor(rgba, hotx, hoty, w, h) {
3026
+ this._cursorImage = {
3027
+ rgbaPixels: rgba,
3028
+ hotx: hotx, hoty: hoty, w: w, h: h,
3029
+ };
3030
+ this._refreshCursor();
3031
+ }
3032
+
3033
+ _shouldShowDotCursor() {
3034
+ // Called when this._cursorImage is updated
3035
+ if (!this._showDotCursor) {
3036
+ // User does not want to see the dot, so...
3037
+ return false;
3038
+ }
3039
+
3040
+ // The dot should not be shown if the cursor is already visible,
3041
+ // i.e. contains at least one not-fully-transparent pixel.
3042
+ // So iterate through all alpha bytes in rgba and stop at the
3043
+ // first non-zero.
3044
+ for (let i = 3; i < this._cursorImage.rgbaPixels.length; i += 4) {
3045
+ if (this._cursorImage.rgbaPixels[i]) {
3046
+ return false;
3047
+ }
3048
+ }
3049
+
3050
+ // At this point, we know that the cursor is fully transparent, and
3051
+ // the user wants to see the dot instead of this.
3052
+ return true;
3053
+ }
3054
+
3055
+ _refreshCursor() {
3056
+ if (this._rfbConnectionState !== "connecting" &&
3057
+ this._rfbConnectionState !== "connected") {
3058
+ return;
3059
+ }
3060
+ const image = this._shouldShowDotCursor() ? RFB.cursors.dot : this._cursorImage;
3061
+ this._cursor.change(image.rgbaPixels,
3062
+ image.hotx, image.hoty,
3063
+ image.w, image.h
3064
+ );
3065
+ }
3066
+
3067
+ static genDES(password, challenge) {
3068
+ const passwordChars = password.split('').map(c => c.charCodeAt(0));
3069
+ const key = legacyCrypto.importKey(
3070
+ "raw", passwordChars, { name: "DES-ECB" }, false, ["encrypt"]);
3071
+ return legacyCrypto.encrypt({ name: "DES-ECB" }, key, challenge);
3072
+ }
3073
+ }
3074
+
3075
+ // Class Methods
3076
+ RFB.messages = {
3077
+ keyEvent(sock, keysym, down) {
3078
+ sock.sQpush8(4); // msg-type
3079
+ sock.sQpush8(down);
3080
+
3081
+ sock.sQpush16(0);
3082
+
3083
+ sock.sQpush32(keysym);
3084
+
3085
+ sock.flush();
3086
+ },
3087
+
3088
+ QEMUExtendedKeyEvent(sock, keysym, down, keycode) {
3089
+ function getRFBkeycode(xtScanCode) {
3090
+ const upperByte = (keycode >> 8);
3091
+ const lowerByte = (keycode & 0x00ff);
3092
+ if (upperByte === 0xe0 && lowerByte < 0x7f) {
3093
+ return lowerByte | 0x80;
3094
+ }
3095
+ return xtScanCode;
3096
+ }
3097
+
3098
+ sock.sQpush8(255); // msg-type
3099
+ sock.sQpush8(0); // sub msg-type
3100
+
3101
+ sock.sQpush16(down);
3102
+
3103
+ sock.sQpush32(keysym);
3104
+
3105
+ const RFBkeycode = getRFBkeycode(keycode);
3106
+
3107
+ sock.sQpush32(RFBkeycode);
3108
+
3109
+ sock.flush();
3110
+ },
3111
+
3112
+ pointerEvent(sock, x, y, mask) {
3113
+ sock.sQpush8(5); // msg-type
3114
+
3115
+ // Marker bit must be set to 0, otherwise the server might
3116
+ // confuse the marker bit with the highest bit in a normal
3117
+ // PointerEvent message.
3118
+ mask = mask & 0x7f;
3119
+ sock.sQpush8(mask);
3120
+
3121
+ sock.sQpush16(x);
3122
+ sock.sQpush16(y);
3123
+
3124
+ sock.flush();
3125
+ },
3126
+
3127
+ extendedPointerEvent(sock, x, y, mask) {
3128
+ sock.sQpush8(5); // msg-type
3129
+
3130
+ let higherBits = (mask >> 7) & 0xff;
3131
+
3132
+ // Bits 2-7 are reserved
3133
+ if (higherBits & 0xfc) {
3134
+ throw new Error("Invalid mouse button mask: " + mask);
3135
+ }
3136
+
3137
+ let lowerBits = mask & 0x7f;
3138
+ lowerBits |= 0x80; // Set marker bit to 1
3139
+
3140
+ sock.sQpush8(lowerBits);
3141
+ sock.sQpush16(x);
3142
+ sock.sQpush16(y);
3143
+ sock.sQpush8(higherBits);
3144
+
3145
+ sock.flush();
3146
+ },
3147
+
3148
+ // Used to build Notify and Request data.
3149
+ _buildExtendedClipboardFlags(actions, formats) {
3150
+ let data = new Uint8Array(4);
3151
+ let formatFlag = 0x00000000;
3152
+ let actionFlag = 0x00000000;
3153
+
3154
+ for (let i = 0; i < actions.length; i++) {
3155
+ actionFlag |= actions[i];
3156
+ }
3157
+
3158
+ for (let i = 0; i < formats.length; i++) {
3159
+ formatFlag |= formats[i];
3160
+ }
3161
+
3162
+ data[0] = actionFlag >> 24; // Actions
3163
+ data[1] = 0x00; // Reserved
3164
+ data[2] = 0x00; // Reserved
3165
+ data[3] = formatFlag; // Formats
3166
+
3167
+ return data;
3168
+ },
3169
+
3170
+ extendedClipboardProvide(sock, formats, inData) {
3171
+ // Deflate incomming data and their sizes
3172
+ let deflator = new Deflator();
3173
+ let dataToDeflate = [];
3174
+
3175
+ for (let i = 0; i < formats.length; i++) {
3176
+ // We only support the format Text at this time
3177
+ if (formats[i] != extendedClipboardFormatText) {
3178
+ throw new Error("Unsupported extended clipboard format for Provide message.");
3179
+ }
3180
+
3181
+ // Change lone \r or \n into \r\n as defined in rfbproto
3182
+ inData[i] = inData[i].replace(/\r\n|\r|\n/gm, "\r\n");
3183
+
3184
+ // Check if it already has \0
3185
+ let text = encodeUTF8(inData[i] + "\0");
3186
+
3187
+ dataToDeflate.push( (text.length >> 24) & 0xFF,
3188
+ (text.length >> 16) & 0xFF,
3189
+ (text.length >> 8) & 0xFF,
3190
+ (text.length & 0xFF));
3191
+
3192
+ for (let j = 0; j < text.length; j++) {
3193
+ dataToDeflate.push(text.charCodeAt(j));
3194
+ }
3195
+ }
3196
+
3197
+ let deflatedData = deflator.deflate(new Uint8Array(dataToDeflate));
3198
+
3199
+ // Build data to send
3200
+ let data = new Uint8Array(4 + deflatedData.length);
3201
+ data.set(RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionProvide],
3202
+ formats));
3203
+ data.set(deflatedData, 4);
3204
+
3205
+ RFB.messages.clientCutText(sock, data, true);
3206
+ },
3207
+
3208
+ extendedClipboardNotify(sock, formats) {
3209
+ let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionNotify],
3210
+ formats);
3211
+ RFB.messages.clientCutText(sock, flags, true);
3212
+ },
3213
+
3214
+ extendedClipboardRequest(sock, formats) {
3215
+ let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionRequest],
3216
+ formats);
3217
+ RFB.messages.clientCutText(sock, flags, true);
3218
+ },
3219
+
3220
+ extendedClipboardCaps(sock, actions, formats) {
3221
+ let formatKeys = Object.keys(formats);
3222
+ let data = new Uint8Array(4 + (4 * formatKeys.length));
3223
+
3224
+ formatKeys.map(x => parseInt(x));
3225
+ formatKeys.sort((a, b) => a - b);
3226
+
3227
+ data.set(RFB.messages._buildExtendedClipboardFlags(actions, []));
3228
+
3229
+ let loopOffset = 4;
3230
+ for (let i = 0; i < formatKeys.length; i++) {
3231
+ data[loopOffset] = formats[formatKeys[i]] >> 24;
3232
+ data[loopOffset + 1] = formats[formatKeys[i]] >> 16;
3233
+ data[loopOffset + 2] = formats[formatKeys[i]] >> 8;
3234
+ data[loopOffset + 3] = formats[formatKeys[i]] >> 0;
3235
+
3236
+ loopOffset += 4;
3237
+ data[3] |= (1 << formatKeys[i]); // Update our format flags
3238
+ }
3239
+
3240
+ RFB.messages.clientCutText(sock, data, true);
3241
+ },
3242
+
3243
+ clientCutText(sock, data, extended = false) {
3244
+ sock.sQpush8(6); // msg-type
3245
+
3246
+ sock.sQpush8(0); // padding
3247
+ sock.sQpush8(0); // padding
3248
+ sock.sQpush8(0); // padding
3249
+
3250
+ let length;
3251
+ if (extended) {
3252
+ length = toUnsigned32bit(-data.length);
3253
+ } else {
3254
+ length = data.length;
3255
+ }
3256
+
3257
+ sock.sQpush32(length);
3258
+ sock.sQpushBytes(data);
3259
+ sock.flush();
3260
+ },
3261
+
3262
+ setDesktopSize(sock, width, height, id, flags) {
3263
+ sock.sQpush8(251); // msg-type
3264
+
3265
+ sock.sQpush8(0); // padding
3266
+
3267
+ sock.sQpush16(width);
3268
+ sock.sQpush16(height);
3269
+
3270
+ sock.sQpush8(1); // number-of-screens
3271
+
3272
+ sock.sQpush8(0); // padding
3273
+
3274
+ // screen array
3275
+ sock.sQpush32(id);
3276
+ sock.sQpush16(0); // x-position
3277
+ sock.sQpush16(0); // y-position
3278
+ sock.sQpush16(width);
3279
+ sock.sQpush16(height);
3280
+ sock.sQpush32(flags);
3281
+
3282
+ sock.flush();
3283
+ },
3284
+
3285
+ clientFence(sock, flags, payload) {
3286
+ sock.sQpush8(248); // msg-type
3287
+
3288
+ sock.sQpush8(0); // padding
3289
+ sock.sQpush8(0); // padding
3290
+ sock.sQpush8(0); // padding
3291
+
3292
+ sock.sQpush32(flags);
3293
+
3294
+ sock.sQpush8(payload.length);
3295
+ sock.sQpushString(payload);
3296
+
3297
+ sock.flush();
3298
+ },
3299
+
3300
+ enableContinuousUpdates(sock, enable, x, y, width, height) {
3301
+ sock.sQpush8(150); // msg-type
3302
+
3303
+ sock.sQpush8(enable);
3304
+
3305
+ sock.sQpush16(x);
3306
+ sock.sQpush16(y);
3307
+ sock.sQpush16(width);
3308
+ sock.sQpush16(height);
3309
+
3310
+ sock.flush();
3311
+ },
3312
+
3313
+ pixelFormat(sock, depth, trueColor) {
3314
+ let bpp;
3315
+
3316
+ if (depth > 16) {
3317
+ bpp = 32;
3318
+ } else if (depth > 8) {
3319
+ bpp = 16;
3320
+ } else {
3321
+ bpp = 8;
3322
+ }
3323
+
3324
+ const bits = Math.floor(depth/3);
3325
+
3326
+ sock.sQpush8(0); // msg-type
3327
+
3328
+ sock.sQpush8(0); // padding
3329
+ sock.sQpush8(0); // padding
3330
+ sock.sQpush8(0); // padding
3331
+
3332
+ sock.sQpush8(bpp);
3333
+ sock.sQpush8(depth);
3334
+ sock.sQpush8(0); // little-endian
3335
+ sock.sQpush8(trueColor ? 1 : 0);
3336
+
3337
+ sock.sQpush16((1 << bits) - 1); // red-max
3338
+ sock.sQpush16((1 << bits) - 1); // green-max
3339
+ sock.sQpush16((1 << bits) - 1); // blue-max
3340
+
3341
+ sock.sQpush8(bits * 0); // red-shift
3342
+ sock.sQpush8(bits * 1); // green-shift
3343
+ sock.sQpush8(bits * 2); // blue-shift
3344
+
3345
+ sock.sQpush8(0); // padding
3346
+ sock.sQpush8(0); // padding
3347
+ sock.sQpush8(0); // padding
3348
+
3349
+ sock.flush();
3350
+ },
3351
+
3352
+ clientEncodings(sock, encodings) {
3353
+ sock.sQpush8(2); // msg-type
3354
+
3355
+ sock.sQpush8(0); // padding
3356
+
3357
+ sock.sQpush16(encodings.length);
3358
+ for (let i = 0; i < encodings.length; i++) {
3359
+ sock.sQpush32(encodings[i]);
3360
+ }
3361
+
3362
+ sock.flush();
3363
+ },
3364
+
3365
+ fbUpdateRequest(sock, incremental, x, y, w, h) {
3366
+ if (typeof(x) === "undefined") { x = 0; }
3367
+ if (typeof(y) === "undefined") { y = 0; }
3368
+
3369
+ sock.sQpush8(3); // msg-type
3370
+
3371
+ sock.sQpush8(incremental ? 1 : 0);
3372
+
3373
+ sock.sQpush16(x);
3374
+ sock.sQpush16(y);
3375
+ sock.sQpush16(w);
3376
+ sock.sQpush16(h);
3377
+
3378
+ sock.flush();
3379
+ },
3380
+
3381
+ xvpOp(sock, ver, op) {
3382
+ sock.sQpush8(250); // msg-type
3383
+
3384
+ sock.sQpush8(0); // padding
3385
+
3386
+ sock.sQpush8(ver);
3387
+ sock.sQpush8(op);
3388
+
3389
+ sock.flush();
3390
+ }
3391
+ };
3392
+
3393
+ RFB.cursors = {
3394
+ none: {
3395
+ rgbaPixels: new Uint8Array(),
3396
+ w: 0, h: 0,
3397
+ hotx: 0, hoty: 0,
3398
+ },
3399
+
3400
+ dot: {
3401
+ /* eslint-disable indent */
3402
+ rgbaPixels: new Uint8Array([
3403
+ 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255,
3404
+ 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 255,
3405
+ 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255,
3406
+ ]),
3407
+ /* eslint-enable indent */
3408
+ w: 3, h: 3,
3409
+ hotx: 1, hoty: 1,
3410
+ }
3411
+ };