@andy.ian/dsh-homing 2.1.4 → 2.1.5

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