]> git.proxmox.com Git - mirror_novnc.git/blame - core/rfb.js
Ensure warning status timeouts are honored
[mirror_novnc.git] / core / rfb.js
CommitLineData
a7a89626
JM
1/*
2 * noVNC: HTML5 VNC client
412d9306 3 * Copyright (C) 2019 The noVNC Authors
1d728ace 4 * Licensed under MPL 2.0 (see LICENSE.txt)
a7a89626
JM
5 *
6 * See README.md for usage and integration instructions.
d38db74a 7 *
a7a89626
JM
8 */
9
6d6f0db0 10import * as Log from './util/logging.js';
6d6f0db0 11import { decodeUTF8 } from './util/strings.js';
3b7c4741 12import { dragThreshold } from './util/browser.js';
e89eef94 13import EventTargetMixin from './util/eventtarget.js';
3ae0bb09 14import Display from "./display.js";
c1e2785f
SM
15import Keyboard from "./input/keyboard.js";
16import Mouse from "./input/mouse.js";
b475eed5 17import Cursor from "./util/cursor.js";
3ae0bb09 18import Websock from "./websock.js";
3ae0bb09
SR
19import DES from "./des.js";
20import KeyTable from "./input/keysym.js";
21import XtScancode from "./input/xtscancodes.js";
e17cae8f 22import { encodings } from "./encodings.js";
e89eef94 23import "./util/polyfill.js";
3ae0bb09 24
923cd220
PO
25import RawDecoder from "./decoders/raw.js";
26import CopyRectDecoder from "./decoders/copyrect.js";
27import RREDecoder from "./decoders/rre.js";
28import HextileDecoder from "./decoders/hextile.js";
29import TightDecoder from "./decoders/tight.js";
30import TightPNGDecoder from "./decoders/tightpng.js";
31
68e09edc 32// How many seconds to wait for a disconnect to finish
2b5f94fa 33const DISCONNECT_TIMEOUT = 3;
d7791ebb 34const DEFAULT_BACKGROUND = 'rgb(40, 40, 40)';
68e09edc 35
0e4808bf
JD
36export default class RFB extends EventTargetMixin {
37 constructor(target, url, options) {
38 if (!target) {
d3ed883a 39 throw new Error("Must specify target");
0e4808bf
JD
40 }
41 if (!url) {
d3ed883a 42 throw new Error("Must specify URL");
0e4808bf
JD
43 }
44
45 super();
46
47 this._target = target;
48 this._url = url;
49
50 // Connection details
51 options = options || {};
52 this._rfb_credentials = options.credentials || {};
53 this._shared = 'shared' in options ? !!options.shared : true;
54 this._repeaterID = options.repeaterID || '';
c9122303 55 this._wsProtocols = options.wsProtocols || [];
0e4808bf
JD
56
57 // Internal state
58 this._rfb_connection_state = '';
59 this._rfb_init_state = '';
c02b18f0 60 this._rfb_auth_scheme = -1;
0e4808bf
JD
61 this._rfb_clean_disconnect = true;
62
63 // Server capabilities
64 this._rfb_version = 0;
65 this._rfb_max_version = 3.8;
66 this._rfb_tightvnc = false;
67 this._rfb_xvp_ver = 0;
68
69 this._fb_width = 0;
70 this._fb_height = 0;
71
72 this._fb_name = "";
73
74 this._capabilities = { power: false };
75
76 this._supportsFence = false;
77
78 this._supportsContinuousUpdates = false;
79 this._enabledContinuousUpdates = false;
80
81 this._supportsSetDesktopSize = false;
82 this._screen_id = 0;
83 this._screen_flags = 0;
84
85 this._qemuExtKeyEventSupported = false;
86
87 // Internal objects
88 this._sock = null; // Websock object
89 this._display = null; // Display object
90 this._flushing = false; // Display flushing state
91 this._keyboard = null; // Keyboard input handler object
92 this._mouse = null; // Mouse input handler object
93
94 // Timers
95 this._disconnTimer = null; // disconnection timer
96 this._resizeTimeout = null; // resize rate limiting
97
e17cae8f 98 // Decoder states
923cd220 99 this._decoders = {};
0e4808bf
JD
100
101 this._FBU = {
102 rects: 0,
0e4808bf
JD
103 x: 0,
104 y: 0,
105 width: 0,
106 height: 0,
923cd220 107 encoding: null,
0e4808bf
JD
108 };
109
110 // Mouse state
111 this._mouse_buttonMask = 0;
112 this._mouse_arr = [];
113 this._viewportDragging = false;
114 this._viewportDragPos = {};
115 this._viewportHasMoved = false;
116
117 // Bound event handlers
118 this._eventHandlers = {
119 focusCanvas: this._focusCanvas.bind(this),
120 windowResize: this._windowResize.bind(this),
121 };
122
123 // main setup
124 Log.Debug(">> RFB.constructor");
125
126 // Create DOM elements
127 this._screen = document.createElement('div');
128 this._screen.style.display = 'flex';
129 this._screen.style.width = '100%';
130 this._screen.style.height = '100%';
131 this._screen.style.overflow = 'auto';
d7791ebb 132 this._screen.style.background = DEFAULT_BACKGROUND;
0e4808bf
JD
133 this._canvas = document.createElement('canvas');
134 this._canvas.style.margin = 'auto';
135 // Some browsers add an outline on focus
136 this._canvas.style.outline = 'none';
137 // IE miscalculates width without this :(
138 this._canvas.style.flexShrink = '0';
139 this._canvas.width = 0;
140 this._canvas.height = 0;
141 this._canvas.tabIndex = -1;
142 this._screen.appendChild(this._canvas);
45808617 143
d1314d4b
AP
144 // Cursor
145 this._cursor = new Cursor();
4c38179d
AP
146
147 // XXX: TightVNC 2.8.11 sends no cursor at all until Windows changes
148 // it. Result: no cursor at all until a window border or an edit field
149 // is hit blindly. But there are also VNC servers that draw the cursor
150 // in the framebuffer and don't send the empty local cursor. There is
151 // no way to satisfy both sides.
152 //
153 // The spec is unclear on this "initial cursor" issue. Many other
154 // viewers (TigerVNC, RealVNC, Remmina) display an arrow as the
155 // initial cursor instead.
156 this._cursorImage = RFB.cursors.none;
b475eed5 157
923cd220
PO
158 // populate decoder array with objects
159 this._decoders[encodings.encodingRaw] = new RawDecoder();
160 this._decoders[encodings.encodingCopyRect] = new CopyRectDecoder();
161 this._decoders[encodings.encodingRRE] = new RREDecoder();
162 this._decoders[encodings.encodingHextile] = new HextileDecoder();
163 this._decoders[encodings.encodingTight] = new TightDecoder();
164 this._decoders[encodings.encodingTightPNG] = new TightPNGDecoder();
0e4808bf
JD
165
166 // NB: nothing that needs explicit teardown should be done
167 // before this point, since this can throw an exception
168 try {
169 this._display = new Display(this._canvas);
170 } catch (exc) {
171 Log.Error("Display exception: " + exc);
172 throw exc;
173 }
174 this._display.onflush = this._onFlush.bind(this);
0e4808bf
JD
175
176 this._keyboard = new Keyboard(this._canvas);
177 this._keyboard.onkeyevent = this._handleKeyEvent.bind(this);
178
179 this._mouse = new Mouse(this._canvas);
180 this._mouse.onmousebutton = this._handleMouseButton.bind(this);
181 this._mouse.onmousemove = this._handleMouseMove.bind(this);
182
183 this._sock = new Websock();
b8ff5d1b
PO
184 this._sock.on('message', () => {
185 this._handle_message();
186 });
651c23ec 187 this._sock.on('open', () => {
0e4808bf
JD
188 if ((this._rfb_connection_state === 'connecting') &&
189 (this._rfb_init_state === '')) {
190 this._rfb_init_state = 'ProtocolVersion';
191 Log.Debug("Starting VNC handshake");
192 } else {
193 this._fail("Unexpected server connection while " +
651c23ec 194 this._rfb_connection_state);
b1dee947 195 }
651c23ec
JD
196 });
197 this._sock.on('close', (e) => {
0e4808bf
JD
198 Log.Debug("WebSocket on-close event");
199 let msg = "";
200 if (e.code) {
201 msg = "(code: " + e.code;
202 if (e.reason) {
203 msg += ", reason: " + e.reason;
204 }
205 msg += ")";
206 }
207 switch (this._rfb_connection_state) {
208 case 'connecting':
209 this._fail("Connection closed " + msg);
210 break;
211 case 'connected':
212 // Handle disconnects that were initiated server-side
213 this._updateConnectionState('disconnecting');
214 this._updateConnectionState('disconnected');
215 break;
216 case 'disconnecting':
217 // Normal disconnection path
218 this._updateConnectionState('disconnected');
219 break;
220 case 'disconnected':
221 this._fail("Unexpected server disconnect " +
651c23ec 222 "when already disconnected " + msg);
0e4808bf
JD
223 break;
224 default:
225 this._fail("Unexpected server disconnect before connecting " +
651c23ec 226 msg);
0e4808bf
JD
227 break;
228 }
229 this._sock.off('close');
0e4808bf 230 });
651c23ec 231 this._sock.on('error', e => Log.Warn("WebSocket on-error event"));
8db09746 232
0e4808bf
JD
233 // Slight delay of the actual connection so that the caller has
234 // time to set up callbacks
235 setTimeout(this._updateConnectionState.bind(this, 'connecting'));
ae510306 236
0e4808bf 237 Log.Debug("<< RFB.constructor");
a7a89626 238
0e4808bf 239 // ===== PROPERTIES =====
6d6f0db0 240
0e4808bf
JD
241 this.dragViewport = false;
242 this.focusOnClick = true;
a7a89626 243
0e4808bf
JD
244 this._viewOnly = false;
245 this._clipViewport = false;
246 this._scaleViewport = false;
247 this._resizeSession = false;
6aed0b4d
PO
248
249 this._showDotCursor = false;
250 if (options.showDotCursor !== undefined) {
251 Log.Warn("Specifying showDotCursor as a RFB constructor argument is deprecated");
252 this._showDotCursor = options.showDotCursor;
253 }
0e4808bf
JD
254 }
255
256 // ===== PROPERTIES =====
257
258 get viewOnly() { return this._viewOnly; }
747b4623
PO
259 set viewOnly(viewOnly) {
260 this._viewOnly = viewOnly;
261
262 if (this._rfb_connection_state === "connecting" ||
263 this._rfb_connection_state === "connected") {
264 if (viewOnly) {
265 this._keyboard.ungrab();
266 this._mouse.ungrab();
267 } else {
268 this._keyboard.grab();
269 this._mouse.grab();
270 }
271 }
0e4808bf 272 }
6d6f0db0 273
0e4808bf 274 get capabilities() { return this._capabilities; }
747b4623 275
0e4808bf
JD
276 get touchButton() { return this._mouse.touchButton; }
277 set touchButton(button) { this._mouse.touchButton = button; }
747b4623 278
0e4808bf 279 get clipViewport() { return this._clipViewport; }
9b84f516
PO
280 set clipViewport(viewport) {
281 this._clipViewport = viewport;
282 this._updateClip();
0e4808bf 283 }
747b4623 284
0e4808bf 285 get scaleViewport() { return this._scaleViewport; }
9b84f516
PO
286 set scaleViewport(scale) {
287 this._scaleViewport = scale;
288 // Scaling trumps clipping, so we may need to adjust
289 // clipping when enabling or disabling scaling
290 if (scale && this._clipViewport) {
291 this._updateClip();
292 }
293 this._updateScale();
294 if (!scale && this._clipViewport) {
295 this._updateClip();
296 }
0e4808bf 297 }
747b4623 298
0e4808bf 299 get resizeSession() { return this._resizeSession; }
9b84f516
PO
300 set resizeSession(resize) {
301 this._resizeSession = resize;
302 if (resize) {
303 this._requestRemoteResize();
304 }
0e4808bf 305 }
a80aa416 306
4c38179d
AP
307 get showDotCursor() { return this._showDotCursor; }
308 set showDotCursor(show) {
309 this._showDotCursor = show;
310 this._refreshCursor();
311 }
312
d7791ebb
MM
313 get background() { return this._screen.style.background; }
314 set background(cssValue) { this._screen.style.background = cssValue; }
315
747b4623
PO
316 // ===== PUBLIC METHODS =====
317
0e4808bf 318 disconnect() {
6d6f0db0
SR
319 this._updateConnectionState('disconnecting');
320 this._sock.off('error');
321 this._sock.off('message');
322 this._sock.off('open');
0e4808bf 323 }
6d6f0db0 324
0e4808bf 325 sendCredentials(creds) {
430f00d6 326 this._rfb_credentials = creds;
6d6f0db0 327 setTimeout(this._init_msg.bind(this), 0);
0e4808bf 328 }
6d6f0db0 329
0e4808bf 330 sendCtrlAltDel() {
15a62695 331 if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; }
6d6f0db0
SR
332 Log.Info("Sending Ctrl-Alt-Del");
333
94f5cf05
PO
334 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true);
335 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true);
336 this.sendKey(KeyTable.XK_Delete, "Delete", true);
337 this.sendKey(KeyTable.XK_Delete, "Delete", false);
338 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false);
339 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false);
0e4808bf 340 }
6d6f0db0 341
0e4808bf 342 machineShutdown() {
cd523e8f 343 this._xvpOp(1, 2);
0e4808bf 344 }
6d6f0db0 345
0e4808bf 346 machineReboot() {
cd523e8f 347 this._xvpOp(1, 3);
0e4808bf 348 }
6d6f0db0 349
0e4808bf 350 machineReset() {
cd523e8f 351 this._xvpOp(1, 4);
0e4808bf 352 }
6d6f0db0
SR
353
354 // Send a key press. If 'down' is not specified then send a down key
355 // followed by an up key.
0e4808bf 356 sendKey(keysym, code, down) {
15a62695 357 if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; }
94f5cf05
PO
358
359 if (down === undefined) {
360 this.sendKey(keysym, code, true);
361 this.sendKey(keysym, code, false);
15a62695 362 return;
94f5cf05
PO
363 }
364
2b5f94fa 365 const scancode = XtScancode[code];
94f5cf05 366
be70fe0a 367 if (this._qemuExtKeyEventSupported && scancode) {
459ed008
PO
368 // 0 is NoSymbol
369 keysym = keysym || 0;
370
94f5cf05
PO
371 Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode);
372
373 RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode);
374 } else {
459ed008 375 if (!keysym) {
15a62695 376 return;
459ed008 377 }
6d6f0db0
SR
378 Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym);
379 RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0);
6d6f0db0 380 }
0e4808bf 381 }
6d6f0db0 382
0e4808bf 383 focus() {
9b84f516 384 this._canvas.focus();
0e4808bf 385 }
b9854a5c 386
0e4808bf 387 blur() {
9b84f516 388 this._canvas.blur();
0e4808bf 389 }
b9854a5c 390
0e4808bf 391 clipboardPasteFrom(text) {
9b84f516
PO
392 if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; }
393 RFB.messages.clientCutText(this._sock, text);
0e4808bf 394 }
b1dee947 395
747b4623 396 // ===== PRIVATE METHODS =====
b0ec6509 397
0e4808bf 398 _connect() {
6d6f0db0 399 Log.Debug(">> RFB.connect");
b0ec6509 400
5b4e5d01 401 Log.Info("connecting to " + this._url);
b1dee947 402
6d6f0db0
SR
403 try {
404 // WebSocket.onopen transitions to the RFB init states
25b3d49d 405 this._sock.open(this._url, this._wsProtocols);
6d6f0db0
SR
406 } catch (e) {
407 if (e.name === 'SyntaxError') {
d472f3f1 408 this._fail("Invalid host or port (" + e + ")");
b1dee947 409 } else {
d472f3f1 410 this._fail("Error when opening socket (" + e + ")");
159ad55d 411 }
6d6f0db0 412 }
e3efeb32 413
9b84f516
PO
414 // Make our elements part of the page
415 this._target.appendChild(this._screen);
416
b475eed5 417 this._cursor.attach(this._canvas);
4c38179d 418 this._refreshCursor();
b475eed5 419
9b84f516
PO
420 // Monitor size changes of the screen
421 // FIXME: Use ResizeObserver, or hidden overflow
422 window.addEventListener('resize', this._eventHandlers.windowResize);
423
2afda544 424 // Always grab focus on some kind of click event
9b84f516
PO
425 this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas);
426 this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas);
2afda544 427
6d6f0db0 428 Log.Debug("<< RFB.connect");
0e4808bf 429 }
6d6f0db0 430
0e4808bf 431 _disconnect() {
6d6f0db0 432 Log.Debug(">> RFB.disconnect");
b475eed5 433 this._cursor.detach();
9b84f516
PO
434 this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas);
435 this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas);
436 window.removeEventListener('resize', this._eventHandlers.windowResize);
437 this._keyboard.ungrab();
438 this._mouse.ungrab();
6d6f0db0 439 this._sock.close();
b245ec70
SM
440 try {
441 this._target.removeChild(this._screen);
442 } catch (e) {
443 if (e.name === 'NotFoundError') {
444 // Some cases where the initial connection fails
445 // can disconnect before the _screen is created
446 } else {
447 throw e;
448 }
449 }
9b84f516 450 clearTimeout(this._resizeTimeout);
6d6f0db0 451 Log.Debug("<< RFB.disconnect");
0e4808bf 452 }
6d6f0db0 453
0e4808bf 454 _focusCanvas(event) {
2afda544 455 // Respect earlier handlers' request to not do side-effects
1d6ff4a3
PO
456 if (event.defaultPrevented) {
457 return;
458 }
459
b8dfb983 460 if (!this.focusOnClick) {
1d6ff4a3
PO
461 return;
462 }
463
9b84f516 464 this.focus();
0e4808bf 465 }
9b84f516 466
ce66b469
NL
467 _setDesktopName(name) {
468 this._fb_name = name;
469 this.dispatchEvent(new CustomEvent(
470 "desktopname",
471 { detail: { name: this._fb_name } }));
472 }
473
0e4808bf 474 _windowResize(event) {
9b84f516
PO
475 // If the window resized then our screen element might have
476 // as well. Update the viewport dimensions.
651c23ec 477 window.requestAnimationFrame(() => {
9b84f516
PO
478 this._updateClip();
479 this._updateScale();
651c23ec 480 });
9b84f516
PO
481
482 if (this._resizeSession) {
483 // Request changing the resolution of the remote display to
484 // the size of the local browser viewport.
485
486 // In order to not send multiple requests before the browser-resize
487 // is finished we wait 0.5 seconds before sending the request.
488 clearTimeout(this._resizeTimeout);
489 this._resizeTimeout = setTimeout(this._requestRemoteResize.bind(this), 500);
490 }
0e4808bf 491 }
9b84f516
PO
492
493 // Update state of clipping in Display object, and make sure the
494 // configured viewport matches the current screen size
0e4808bf 495 _updateClip() {
2b5f94fa
JD
496 const cur_clip = this._display.clipViewport;
497 let new_clip = this._clipViewport;
9b84f516
PO
498
499 if (this._scaleViewport) {
500 // Disable viewport clipping if we are scaling
501 new_clip = false;
502 }
503
504 if (cur_clip !== new_clip) {
505 this._display.clipViewport = new_clip;
506 }
507
508 if (new_clip) {
509 // When clipping is enabled, the screen is limited to
510 // the size of the container.
2b5f94fa 511 const size = this._screenSize();
9b84f516
PO
512 this._display.viewportChangeSize(size.w, size.h);
513 this._fixScrollbars();
514 }
0e4808bf 515 }
9b84f516 516
0e4808bf 517 _updateScale() {
9b84f516
PO
518 if (!this._scaleViewport) {
519 this._display.scale = 1.0;
520 } else {
2b5f94fa 521 const size = this._screenSize();
9b84f516
PO
522 this._display.autoscale(size.w, size.h);
523 }
524 this._fixScrollbars();
0e4808bf 525 }
9b84f516
PO
526
527 // Requests a change of remote desktop size. This message is an extension
528 // and may only be sent if we have received an ExtendedDesktopSize message
0e4808bf 529 _requestRemoteResize() {
9b84f516
PO
530 clearTimeout(this._resizeTimeout);
531 this._resizeTimeout = null;
532
533 if (!this._resizeSession || this._viewOnly ||
534 !this._supportsSetDesktopSize) {
535 return;
536 }
537
2b5f94fa 538 const size = this._screenSize();
ab1ace38
PO
539 RFB.messages.setDesktopSize(this._sock,
540 Math.floor(size.w), Math.floor(size.h),
9b84f516
PO
541 this._screen_id, this._screen_flags);
542
543 Log.Debug('Requested new desktop size: ' +
544 size.w + 'x' + size.h);
0e4808bf 545 }
9b84f516
PO
546
547 // Gets the the size of the available screen
0e4808bf 548 _screenSize() {
ab1ace38
PO
549 let r = this._screen.getBoundingClientRect();
550 return { w: r.width, h: r.height };
0e4808bf 551 }
9b84f516 552
0e4808bf 553 _fixScrollbars() {
9b84f516
PO
554 // This is a hack because Chrome screws up the calculation
555 // for when scrollbars are needed. So to fix it we temporarily
556 // toggle them off and on.
2b5f94fa 557 const orig = this._screen.style.overflow;
9b84f516
PO
558 this._screen.style.overflow = 'hidden';
559 // Force Chrome to recalculate the layout by asking for
560 // an element's dimensions
561 this._screen.getBoundingClientRect();
562 this._screen.style.overflow = orig;
0e4808bf 563 }
2afda544 564
6d6f0db0
SR
565 /*
566 * Connection states:
567 * connecting
568 * connected
569 * disconnecting
570 * disconnected - permanent state
571 */
0e4808bf 572 _updateConnectionState(state) {
2b5f94fa 573 const oldstate = this._rfb_connection_state;
6d6f0db0
SR
574
575 if (state === oldstate) {
576 Log.Debug("Already in state '" + state + "', ignoring");
577 return;
578 }
579
580 // The 'disconnected' state is permanent for each RFB object
581 if (oldstate === 'disconnected') {
582 Log.Error("Tried changing state of a disconnected RFB object");
583 return;
584 }
585
586 // Ensure proper transitions before doing anything
587 switch (state) {
588 case 'connected':
589 if (oldstate !== 'connecting') {
590 Log.Error("Bad transition to connected state, " +
591 "previous connection state: " + oldstate);
592 return;
b1dee947 593 }
6d6f0db0 594 break;
a7a89626 595
6d6f0db0
SR
596 case 'disconnected':
597 if (oldstate !== 'disconnecting') {
598 Log.Error("Bad transition to disconnected state, " +
599 "previous connection state: " + oldstate);
600 return;
601 }
602 break;
a7a89626 603
6d6f0db0
SR
604 case 'connecting':
605 if (oldstate !== '') {
606 Log.Error("Bad transition to connecting state, " +
607 "previous connection state: " + oldstate);
608 return;
609 }
610 break;
b1dee947 611
6d6f0db0
SR
612 case 'disconnecting':
613 if (oldstate !== 'connected' && oldstate !== 'connecting') {
614 Log.Error("Bad transition to disconnecting state, " +
615 "previous connection state: " + oldstate);
616 return;
617 }
618 break;
a679a97d 619
6d6f0db0
SR
620 default:
621 Log.Error("Unknown connection state: " + state);
3bb12056 622 return;
6d6f0db0 623 }
b1dee947 624
6d6f0db0 625 // State change actions
3bb12056 626
6d6f0db0 627 this._rfb_connection_state = state;
b2e961d4 628
651c23ec 629 Log.Debug("New state '" + state + "', was '" + oldstate + "'.");
b2e961d4 630
6d6f0db0
SR
631 if (this._disconnTimer && state !== 'disconnecting') {
632 Log.Debug("Clearing disconnect timer");
633 clearTimeout(this._disconnTimer);
634 this._disconnTimer = null;
3bb12056 635
6d6f0db0
SR
636 // make sure we don't get a double event
637 this._sock.off('close');
638 }
b2e961d4 639
6d6f0db0 640 switch (state) {
6d6f0db0
SR
641 case 'connecting':
642 this._connect();
643 break;
b2e961d4 644
ee5cae9f 645 case 'connected':
2b5f94fa 646 this.dispatchEvent(new CustomEvent("connect", { detail: {} }));
ee5cae9f
SM
647 break;
648
6d6f0db0
SR
649 case 'disconnecting':
650 this._disconnect();
b2e961d4 651
651c23ec 652 this._disconnTimer = setTimeout(() => {
d472f3f1 653 Log.Error("Disconnection timed out.");
6d6f0db0 654 this._updateConnectionState('disconnected');
651c23ec 655 }, DISCONNECT_TIMEOUT * 1000);
6d6f0db0 656 break;
ee5cae9f
SM
657
658 case 'disconnected':
2b5f94fa 659 this.dispatchEvent(new CustomEvent(
d472f3f1 660 "disconnect", { detail:
2b5f94fa 661 { clean: this._rfb_clean_disconnect } }));
ee5cae9f 662 break;
6d6f0db0 663 }
0e4808bf 664 }
6d6f0db0
SR
665
666 /* Print errors and disconnect
667 *
d472f3f1 668 * The parameter 'details' is used for information that
6d6f0db0
SR
669 * should be logged but not sent to the user interface.
670 */
0e4808bf 671 _fail(details) {
6d6f0db0
SR
672 switch (this._rfb_connection_state) {
673 case 'disconnecting':
d472f3f1 674 Log.Error("Failed when disconnecting: " + details);
6d6f0db0
SR
675 break;
676 case 'connected':
d472f3f1 677 Log.Error("Failed while connected: " + details);
6d6f0db0
SR
678 break;
679 case 'connecting':
d472f3f1 680 Log.Error("Failed when connecting: " + details);
6d6f0db0
SR
681 break;
682 default:
d472f3f1 683 Log.Error("RFB failure: " + details);
6d6f0db0
SR
684 break;
685 }
d472f3f1 686 this._rfb_clean_disconnect = false; //This is sent to the UI
6d6f0db0
SR
687
688 // Transition to disconnected without waiting for socket to close
689 this._updateConnectionState('disconnecting');
690 this._updateConnectionState('disconnected');
691
692 return false;
0e4808bf 693 }
6d6f0db0 694
0e4808bf 695 _setCapability(cap, val) {
832be262 696 this._capabilities[cap] = val;
2b5f94fa 697 this.dispatchEvent(new CustomEvent("capabilities",
0e4808bf
JD
698 { detail: { capabilities: this._capabilities } }));
699 }
b1dee947 700
0e4808bf 701 _handle_message() {
8a189a62 702 if (this._sock.rQlen === 0) {
6d6f0db0
SR
703 Log.Warn("handle_message called on an empty receive queue");
704 return;
705 }
b1dee947 706
6d6f0db0
SR
707 switch (this._rfb_connection_state) {
708 case 'disconnected':
709 Log.Error("Got data while disconnected");
710 break;
711 case 'connected':
712 while (true) {
713 if (this._flushing) {
714 break;
715 }
716 if (!this._normal_msg()) {
717 break;
718 }
8a189a62 719 if (this._sock.rQlen === 0) {
6d6f0db0
SR
720 break;
721 }
722 }
723 break;
724 default:
725 this._init_msg();
726 break;
727 }
0e4808bf 728 }
3bb12056 729
0e4808bf 730 _handleKeyEvent(keysym, code, down) {
d0703d1b 731 this.sendKey(keysym, code, down);
0e4808bf 732 }
06a9ef0c 733
0e4808bf 734 _handleMouseButton(x, y, down, bmask) {
6d6f0db0
SR
735 if (down) {
736 this._mouse_buttonMask |= bmask;
737 } else {
270bdbd7 738 this._mouse_buttonMask &= ~bmask;
6d6f0db0 739 }
a7127fee 740
0460e5fd 741 if (this.dragViewport) {
6d6f0db0
SR
742 if (down && !this._viewportDragging) {
743 this._viewportDragging = true;
744 this._viewportDragPos = {'x': x, 'y': y};
898cd32c 745 this._viewportHasMoved = false;
a7127fee 746
6d6f0db0 747 // Skip sending mouse events
b1dee947 748 return;
6d6f0db0
SR
749 } else {
750 this._viewportDragging = false;
8db09746 751
898cd32c
PO
752 // If we actually performed a drag then we are done
753 // here and should not send any mouse events
754 if (this._viewportHasMoved) {
755 return;
6d6f0db0 756 }
898cd32c
PO
757
758 // Otherwise we treat this as a mouse click event.
759 // Send the button down event here, as the button up
760 // event is sent at the end of this function.
761 RFB.messages.pointerEvent(this._sock,
762 this._display.absX(x),
763 this._display.absY(y),
764 bmask);
b1dee947 765 }
6d6f0db0 766 }
8db09746 767
747b4623 768 if (this._viewOnly) { return; } // View only, skip mouse events
8f06673a 769
6d6f0db0
SR
770 if (this._rfb_connection_state !== 'connected') { return; }
771 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
0e4808bf 772 }
8db09746 773
0e4808bf 774 _handleMouseMove(x, y) {
6d6f0db0 775 if (this._viewportDragging) {
2b5f94fa
JD
776 const deltaX = this._viewportDragPos.x - x;
777 const deltaY = this._viewportDragPos.y - y;
8db09746 778
6d6f0db0
SR
779 if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
780 Math.abs(deltaY) > dragThreshold)) {
781 this._viewportHasMoved = true;
27e77d46 782
6d6f0db0
SR
783 this._viewportDragPos = {'x': x, 'y': y};
784 this._display.viewportChangePos(deltaX, deltaY);
b50f3406 785 }
8db09746 786
6d6f0db0
SR
787 // Skip sending mouse events
788 return;
789 }
b1dee947 790
747b4623 791 if (this._viewOnly) { return; } // View only, skip mouse events
b1dee947 792
6d6f0db0
SR
793 if (this._rfb_connection_state !== 'connected') { return; }
794 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
0e4808bf 795 }
b1dee947 796
6d6f0db0 797 // Message Handlers
27e77d46 798
0e4808bf 799 _negotiate_protocol_version() {
c13df5ae
PO
800 if (this._sock.rQwait("version", 12)) {
801 return false;
6d6f0db0 802 }
32df3fdb 803
2b5f94fa 804 const sversion = this._sock.rQshiftStr(12).substr(4, 7);
6d6f0db0 805 Log.Info("Server ProtocolVersion: " + sversion);
2b5f94fa 806 let is_repeater = 0;
6d6f0db0
SR
807 switch (sversion) {
808 case "000.000": // UltraVNC repeater
809 is_repeater = 1;
810 break;
811 case "003.003":
812 case "003.006": // UltraVNC
813 case "003.889": // Apple Remote Desktop
814 this._rfb_version = 3.3;
815 break;
816 case "003.007":
817 this._rfb_version = 3.7;
818 break;
819 case "003.008":
820 case "004.000": // Intel AMT KVM
821 case "004.001": // RealVNC 4.6
822 case "005.000": // RealVNC 5.3
823 this._rfb_version = 3.8;
824 break;
825 default:
d472f3f1 826 return this._fail("Invalid server version " + sversion);
6d6f0db0 827 }
8db09746 828
6d6f0db0 829 if (is_repeater) {
2b5f94fa 830 let repeaterID = "ID:" + this._repeaterID;
6d6f0db0
SR
831 while (repeaterID.length < 250) {
832 repeaterID += "\0";
b1dee947 833 }
6d6f0db0
SR
834 this._sock.send_string(repeaterID);
835 return true;
836 }
b1dee947 837
6d6f0db0
SR
838 if (this._rfb_version > this._rfb_max_version) {
839 this._rfb_version = this._rfb_max_version;
840 }
b1dee947 841
2b5f94fa 842 const cversion = "00" + parseInt(this._rfb_version, 10) +
6d6f0db0
SR
843 ".00" + ((this._rfb_version * 10) % 10);
844 this._sock.send_string("RFB " + cversion + "\n");
845 Log.Debug('Sent ProtocolVersion: ' + cversion);
b1dee947 846
6d6f0db0 847 this._rfb_init_state = 'Security';
0e4808bf 848 }
b1dee947 849
0e4808bf 850 _negotiate_security() {
6d6f0db0
SR
851 // Polyfill since IE and PhantomJS doesn't have
852 // TypedArray.includes()
853 function includes(item, array) {
2b5f94fa 854 for (let i = 0; i < array.length; i++) {
6d6f0db0
SR
855 if (array[i] === item) {
856 return true;
857 }
b1dee947 858 }
6d6f0db0
SR
859 return false;
860 }
b1dee947 861
6d6f0db0
SR
862 if (this._rfb_version >= 3.7) {
863 // Server sends supported list, client decides
2b5f94fa 864 const num_types = this._sock.rQshift8();
6d6f0db0 865 if (this._sock.rQwait("security type", num_types, 1)) { return false; }
b1dee947 866
6d6f0db0 867 if (num_types === 0) {
3bb15d4a
PO
868 this._rfb_init_state = "SecurityReason";
869 this._security_context = "no security types";
870 this._security_status = 1;
871 return this._init_msg();
6d6f0db0
SR
872 }
873
2b5f94fa 874 const types = this._sock.rQshiftBytes(num_types);
6d6f0db0
SR
875 Log.Debug("Server security types: " + types);
876
877 // Look for each auth in preferred order
6d6f0db0
SR
878 if (includes(1, types)) {
879 this._rfb_auth_scheme = 1; // None
880 } else if (includes(22, types)) {
881 this._rfb_auth_scheme = 22; // XVP
882 } else if (includes(16, types)) {
883 this._rfb_auth_scheme = 16; // Tight
884 } else if (includes(2, types)) {
885 this._rfb_auth_scheme = 2; // VNC Auth
886 } else {
d472f3f1 887 return this._fail("Unsupported security types (types: " + types + ")");
8db09746 888 }
b1dee947 889
6d6f0db0
SR
890 this._sock.send([this._rfb_auth_scheme]);
891 } else {
892 // Server decides
893 if (this._sock.rQwait("security scheme", 4)) { return false; }
894 this._rfb_auth_scheme = this._sock.rQshift32();
3bb15d4a
PO
895
896 if (this._rfb_auth_scheme == 0) {
897 this._rfb_init_state = "SecurityReason";
898 this._security_context = "authentication scheme";
899 this._security_status = 1;
900 return this._init_msg();
901 }
6d6f0db0 902 }
b1dee947 903
6d6f0db0
SR
904 this._rfb_init_state = 'Authentication';
905 Log.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme);
b1dee947 906
6d6f0db0 907 return this._init_msg(); // jump to authentication
0e4808bf 908 }
b1dee947 909
3bb15d4a 910 _handle_security_reason() {
d472f3f1
SM
911 if (this._sock.rQwait("reason length", 4)) {
912 return false;
913 }
2b5f94fa 914 const strlen = this._sock.rQshift32();
d472f3f1
SM
915 let reason = "";
916
917 if (strlen > 0) {
3bb15d4a 918 if (this._sock.rQwait("reason", strlen, 4)) { return false; }
d472f3f1
SM
919 reason = this._sock.rQshiftStr(strlen);
920 }
921
922 if (reason !== "") {
2b5f94fa 923 this.dispatchEvent(new CustomEvent(
d472f3f1 924 "securityfailure",
3bb15d4a
PO
925 { detail: { status: this._security_status,
926 reason: reason } }));
d472f3f1 927
3bb15d4a
PO
928 return this._fail("Security negotiation failed on " +
929 this._security_context +
d472f3f1
SM
930 " (reason: " + reason + ")");
931 } else {
2b5f94fa 932 this.dispatchEvent(new CustomEvent(
d472f3f1 933 "securityfailure",
3bb15d4a 934 { detail: { status: this._security_status } }));
d472f3f1 935
3bb15d4a
PO
936 return this._fail("Security negotiation failed on " +
937 this._security_context);
d472f3f1 938 }
0e4808bf 939 }
d472f3f1 940
6d6f0db0 941 // authentication
0e4808bf 942 _negotiate_xvp_auth() {
430f00d6
PO
943 if (!this._rfb_credentials.username ||
944 !this._rfb_credentials.password ||
945 !this._rfb_credentials.target) {
2b5f94fa
JD
946 this.dispatchEvent(new CustomEvent(
947 "credentialsrequired",
948 { detail: { types: ["username", "password", "target"] } }));
7b536961 949 return false;
6d6f0db0 950 }
0ee5ca6e 951
2b5f94fa 952 const xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) +
430f00d6
PO
953 String.fromCharCode(this._rfb_credentials.target.length) +
954 this._rfb_credentials.username +
955 this._rfb_credentials.target;
6d6f0db0 956 this._sock.send_string(xvp_auth_str);
6d6f0db0
SR
957 this._rfb_auth_scheme = 2;
958 return this._negotiate_authentication();
0e4808bf 959 }
6d6f0db0 960
0e4808bf 961 _negotiate_std_vnc_auth() {
abfe5b7a
SM
962 if (this._sock.rQwait("auth challenge", 16)) { return false; }
963
430f00d6 964 if (!this._rfb_credentials.password) {
2b5f94fa
JD
965 this.dispatchEvent(new CustomEvent(
966 "credentialsrequired",
967 { detail: { types: ["password"] } }));
6d6f0db0
SR
968 return false;
969 }
b1dee947 970
6d6f0db0 971 // TODO(directxman12): make genDES not require an Array
2b5f94fa
JD
972 const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
973 const response = RFB.genDES(this._rfb_credentials.password, challenge);
6d6f0db0
SR
974 this._sock.send(response);
975 this._rfb_init_state = "SecurityResult";
976 return true;
0e4808bf 977 }
6d6f0db0 978
0e4808bf 979 _negotiate_tight_tunnels(numTunnels) {
2b5f94fa 980 const clientSupportedTunnelTypes = {
6d6f0db0
SR
981 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
982 };
2b5f94fa 983 const serverSupportedTunnelTypes = {};
6d6f0db0 984 // receive tunnel capabilities
2b5f94fa
JD
985 for (let i = 0; i < numTunnels; i++) {
986 const cap_code = this._sock.rQshift32();
987 const cap_vendor = this._sock.rQshiftStr(4);
988 const cap_signature = this._sock.rQshiftStr(8);
6d6f0db0
SR
989 serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature };
990 }
991
e6bad200
PO
992 Log.Debug("Server Tight tunnel types: " + serverSupportedTunnelTypes);
993
8f47bd29
PO
994 // Siemens touch panels have a VNC server that supports NOTUNNEL,
995 // but forgets to advertise it. Try to detect such servers by
996 // looking for their custom tunnel type.
997 if (serverSupportedTunnelTypes[1] &&
998 (serverSupportedTunnelTypes[1].vendor === "SICR") &&
999 (serverSupportedTunnelTypes[1].signature === "SCHANNEL")) {
1000 Log.Debug("Detected Siemens server. Assuming NOTUNNEL support.");
1001 serverSupportedTunnelTypes[0] = { vendor: 'TGHT', signature: 'NOTUNNEL' };
1002 }
1003
6d6f0db0
SR
1004 // choose the notunnel type
1005 if (serverSupportedTunnelTypes[0]) {
1006 if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
1007 serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
d472f3f1 1008 return this._fail("Client's tunnel type had the incorrect " +
6d6f0db0 1009 "vendor or signature");
b1dee947 1010 }
e6bad200 1011 Log.Debug("Selected tunnel type: " + clientSupportedTunnelTypes[0]);
6d6f0db0
SR
1012 this._sock.send([0, 0, 0, 0]); // use NOTUNNEL
1013 return false; // wait until we receive the sub auth count to continue
1014 } else {
d472f3f1 1015 return this._fail("Server wanted tunnels, but doesn't support " +
6d6f0db0
SR
1016 "the notunnel type");
1017 }
0e4808bf 1018 }
b1dee947 1019
0e4808bf 1020 _negotiate_tight_auth() {
6d6f0db0
SR
1021 if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation
1022 if (this._sock.rQwait("num tunnels", 4)) { return false; }
2b5f94fa 1023 const numTunnels = this._sock.rQshift32();
6d6f0db0 1024 if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
c00ee156 1025
6d6f0db0 1026 this._rfb_tightvnc = true;
b1dee947 1027
6d6f0db0
SR
1028 if (numTunnels > 0) {
1029 this._negotiate_tight_tunnels(numTunnels);
1030 return false; // wait until we receive the sub auth to continue
b1dee947 1031 }
6d6f0db0 1032 }
b1dee947 1033
6d6f0db0
SR
1034 // second pass, do the sub-auth negotiation
1035 if (this._sock.rQwait("sub auth count", 4)) { return false; }
2b5f94fa 1036 const subAuthCount = this._sock.rQshift32();
6d6f0db0
SR
1037 if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
1038 this._rfb_init_state = 'SecurityResult';
1039 return true;
1040 }
b1dee947 1041
6d6f0db0 1042 if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
b1dee947 1043
2b5f94fa 1044 const clientSupportedTypes = {
6d6f0db0
SR
1045 'STDVNOAUTH__': 1,
1046 'STDVVNCAUTH_': 2
1047 };
b1dee947 1048
2b5f94fa 1049 const serverSupportedTypes = [];
95eb681b 1050
2b5f94fa 1051 for (let i = 0; i < subAuthCount; i++) {
8727f598 1052 this._sock.rQshift32(); // capNum
2b5f94fa 1053 const capabilities = this._sock.rQshiftStr(12);
6d6f0db0
SR
1054 serverSupportedTypes.push(capabilities);
1055 }
d86cc2d9 1056
e6bad200
PO
1057 Log.Debug("Server Tight authentication types: " + serverSupportedTypes);
1058
2b5f94fa 1059 for (let authType in clientSupportedTypes) {
6d6f0db0
SR
1060 if (serverSupportedTypes.indexOf(authType) != -1) {
1061 this._sock.send([0, 0, 0, clientSupportedTypes[authType]]);
e6bad200 1062 Log.Debug("Selected authentication type: " + authType);
d86cc2d9 1063
6d6f0db0
SR
1064 switch (authType) {
1065 case 'STDVNOAUTH__': // no auth
1066 this._rfb_init_state = 'SecurityResult';
1067 return true;
1068 case 'STDVVNCAUTH_': // VNC auth
1069 this._rfb_auth_scheme = 2;
1070 return this._init_msg();
1071 default:
d472f3f1
SM
1072 return this._fail("Unsupported tiny auth scheme " +
1073 "(scheme: " + authType + ")");
b1dee947
SR
1074 }
1075 }
6d6f0db0 1076 }
b1dee947 1077
d472f3f1 1078 return this._fail("No supported sub-auth types!");
0e4808bf 1079 }
6d6f0db0 1080
0e4808bf 1081 _negotiate_authentication() {
6d6f0db0 1082 switch (this._rfb_auth_scheme) {
6d6f0db0
SR
1083 case 1: // no auth
1084 if (this._rfb_version >= 3.8) {
1085 this._rfb_init_state = 'SecurityResult';
1086 return true;
1087 }
1088 this._rfb_init_state = 'ClientInitialisation';
1089 return this._init_msg();
95eb681b 1090
6d6f0db0
SR
1091 case 22: // XVP auth
1092 return this._negotiate_xvp_auth();
d86cc2d9 1093
6d6f0db0
SR
1094 case 2: // VNC authentication
1095 return this._negotiate_std_vnc_auth();
d86cc2d9 1096
6d6f0db0
SR
1097 case 16: // TightVNC Security Type
1098 return this._negotiate_tight_auth();
d86cc2d9 1099
6d6f0db0 1100 default:
d472f3f1
SM
1101 return this._fail("Unsupported auth scheme (scheme: " +
1102 this._rfb_auth_scheme + ")");
6d6f0db0 1103 }
0e4808bf 1104 }
6d6f0db0 1105
0e4808bf 1106 _handle_security_result() {
6d6f0db0 1107 if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
d472f3f1 1108
2b5f94fa 1109 const status = this._sock.rQshift32();
d472f3f1
SM
1110
1111 if (status === 0) { // OK
1112 this._rfb_init_state = 'ClientInitialisation';
1113 Log.Debug('Authentication OK');
1114 return this._init_msg();
1115 } else {
1116 if (this._rfb_version >= 3.8) {
3bb15d4a
PO
1117 this._rfb_init_state = "SecurityReason";
1118 this._security_context = "security result";
1119 this._security_status = status;
1120 return this._init_msg();
d472f3f1 1121 } else {
2b5f94fa
JD
1122 this.dispatchEvent(new CustomEvent(
1123 "securityfailure",
1124 { detail: { status: status } }));
d472f3f1
SM
1125
1126 return this._fail("Security handshake failed");
1127 }
6d6f0db0 1128 }
0e4808bf 1129 }
6d6f0db0 1130
0e4808bf 1131 _negotiate_server_init() {
6d6f0db0
SR
1132 if (this._sock.rQwait("server initialization", 24)) { return false; }
1133
1134 /* Screen size */
2b5f94fa
JD
1135 const width = this._sock.rQshift16();
1136 const height = this._sock.rQshift16();
6d6f0db0
SR
1137
1138 /* PIXEL_FORMAT */
2b5f94fa
JD
1139 const bpp = this._sock.rQshift8();
1140 const depth = this._sock.rQshift8();
1141 const big_endian = this._sock.rQshift8();
1142 const true_color = this._sock.rQshift8();
1143
1144 const red_max = this._sock.rQshift16();
1145 const green_max = this._sock.rQshift16();
1146 const blue_max = this._sock.rQshift16();
1147 const red_shift = this._sock.rQshift8();
1148 const green_shift = this._sock.rQshift8();
1149 const blue_shift = this._sock.rQshift8();
6d6f0db0
SR
1150 this._sock.rQskipBytes(3); // padding
1151
1152 // NB(directxman12): we don't want to call any callbacks or print messages until
1153 // *after* we're past the point where we could backtrack
1154
1155 /* Connection name/title */
2b5f94fa 1156 const name_length = this._sock.rQshift32();
6d6f0db0 1157 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
ce66b469 1158 let name = decodeUTF8(this._sock.rQshiftStr(name_length));
6d6f0db0
SR
1159
1160 if (this._rfb_tightvnc) {
1161 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1162 // In TightVNC mode, ServerInit message is extended
2b5f94fa
JD
1163 const numServerMessages = this._sock.rQshift16();
1164 const numClientMessages = this._sock.rQshift16();
1165 const numEncodings = this._sock.rQshift16();
6d6f0db0
SR
1166 this._sock.rQskipBytes(2); // padding
1167
2b5f94fa 1168 const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
6d6f0db0
SR
1169 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1170
1171 // we don't actually do anything with the capability information that TIGHT sends,
1172 // so we just skip the all of this.
1173
1174 // TIGHT server message capabilities
1175 this._sock.rQskipBytes(16 * numServerMessages);
1176
1177 // TIGHT client message capabilities
1178 this._sock.rQskipBytes(16 * numClientMessages);
1179
1180 // TIGHT encoding capabilities
1181 this._sock.rQskipBytes(16 * numEncodings);
1182 }
d86cc2d9 1183
6d6f0db0
SR
1184 // NB(directxman12): these are down here so that we don't run them multiple times
1185 // if we backtrack
91d5c625 1186 Log.Info("Screen: " + width + "x" + height +
6d6f0db0
SR
1187 ", bpp: " + bpp + ", depth: " + depth +
1188 ", big_endian: " + big_endian +
1189 ", true_color: " + true_color +
1190 ", red_max: " + red_max +
1191 ", green_max: " + green_max +
1192 ", blue_max: " + blue_max +
1193 ", red_shift: " + red_shift +
1194 ", green_shift: " + green_shift +
1195 ", blue_shift: " + blue_shift);
1196
6d6f0db0 1197 // we're past the point where we could backtrack, so it's safe to call this
ce66b469 1198 this._setDesktopName(name);
91d5c625 1199 this._resize(width, height);
b1dee947 1200
747b4623
PO
1201 if (!this._viewOnly) { this._keyboard.grab(); }
1202 if (!this._viewOnly) { this._mouse.grab(); }
b1dee947 1203
5a5f5ada
PO
1204 this._fb_depth = 24;
1205
1206 if (this._fb_name === "Intel(r) AMT KVM") {
1207 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1208 this._fb_depth = 8;
1209 }
1210
1211 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
49a81837 1212 this._sendEncodings();
6d6f0db0
SR
1213 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1214
6d6f0db0
SR
1215 this._updateConnectionState('connected');
1216 return true;
0e4808bf 1217 }
6d6f0db0 1218
0e4808bf 1219 _sendEncodings() {
2b5f94fa 1220 const encs = [];
49a81837
PO
1221
1222 // In preference order
1223 encs.push(encodings.encodingCopyRect);
5a5f5ada
PO
1224 // Only supported with full depth support
1225 if (this._fb_depth == 24) {
1226 encs.push(encodings.encodingTight);
2c813a33 1227 encs.push(encodings.encodingTightPNG);
5a5f5ada
PO
1228 encs.push(encodings.encodingHextile);
1229 encs.push(encodings.encodingRRE);
1230 }
49a81837
PO
1231 encs.push(encodings.encodingRaw);
1232
1233 // Psuedo-encoding settings
49a81837
PO
1234 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1235 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1236
1237 encs.push(encodings.pseudoEncodingDesktopSize);
1238 encs.push(encodings.pseudoEncodingLastRect);
1239 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1240 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1241 encs.push(encodings.pseudoEncodingXvp);
1242 encs.push(encodings.pseudoEncodingFence);
1243 encs.push(encodings.pseudoEncodingContinuousUpdates);
ce66b469 1244 encs.push(encodings.pseudoEncodingDesktopName);
49a81837 1245
baa4f23e 1246 if (this._fb_depth == 24) {
296ba51f 1247 encs.push(encodings.pseudoEncodingVMwareCursor);
49a81837
PO
1248 encs.push(encodings.pseudoEncodingCursor);
1249 }
1250
1251 RFB.messages.clientEncodings(this._sock, encs);
0e4808bf 1252 }
49a81837 1253
6d6f0db0
SR
1254 /* RFB protocol initialization states:
1255 * ProtocolVersion
1256 * Security
1257 * Authentication
1258 * SecurityResult
1259 * ClientInitialization - not triggered by server message
1260 * ServerInitialization
1261 */
0e4808bf 1262 _init_msg() {
6d6f0db0
SR
1263 switch (this._rfb_init_state) {
1264 case 'ProtocolVersion':
1265 return this._negotiate_protocol_version();
1266
1267 case 'Security':
1268 return this._negotiate_security();
1269
1270 case 'Authentication':
1271 return this._negotiate_authentication();
1272
1273 case 'SecurityResult':
1274 return this._handle_security_result();
1275
3bb15d4a
PO
1276 case 'SecurityReason':
1277 return this._handle_security_reason();
1278
6d6f0db0
SR
1279 case 'ClientInitialisation':
1280 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1281 this._rfb_init_state = 'ServerInitialisation';
1282 return true;
b1dee947 1283
6d6f0db0
SR
1284 case 'ServerInitialisation':
1285 return this._negotiate_server_init();
b1dee947 1286
6d6f0db0 1287 default:
d472f3f1
SM
1288 return this._fail("Unknown init state (state: " +
1289 this._rfb_init_state + ")");
6d6f0db0 1290 }
0e4808bf 1291 }
b1dee947 1292
0e4808bf 1293 _handle_set_colour_map_msg() {
6d6f0db0 1294 Log.Debug("SetColorMapEntries");
b1dee947 1295
d472f3f1 1296 return this._fail("Unexpected SetColorMapEntries message");
0e4808bf 1297 }
b1dee947 1298
0e4808bf 1299 _handle_server_cut_text() {
6d6f0db0 1300 Log.Debug("ServerCutText");
b1dee947 1301
6d6f0db0
SR
1302 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1303 this._sock.rQskipBytes(3); // Padding
2b5f94fa 1304 const length = this._sock.rQshift32();
6d6f0db0 1305 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
b1dee947 1306
2b5f94fa 1307 const text = this._sock.rQshiftStr(length);
b4ff032e 1308
747b4623 1309 if (this._viewOnly) { return true; }
b4ff032e 1310
2b5f94fa
JD
1311 this.dispatchEvent(new CustomEvent(
1312 "clipboard",
1313 { detail: { text: text } }));
b1dee947 1314
6d6f0db0 1315 return true;
0e4808bf 1316 }
b1dee947 1317
0e4808bf 1318 _handle_server_fence_msg() {
6d6f0db0
SR
1319 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1320 this._sock.rQskipBytes(3); // Padding
2b5f94fa
JD
1321 let flags = this._sock.rQshift32();
1322 let length = this._sock.rQshift8();
b1dee947 1323
6d6f0db0 1324 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
b1dee947 1325
6d6f0db0
SR
1326 if (length > 64) {
1327 Log.Warn("Bad payload length (" + length + ") in fence response");
1328 length = 64;
1329 }
4e0c36dd 1330
2b5f94fa 1331 const payload = this._sock.rQshiftStr(length);
b1dee947 1332
6d6f0db0 1333 this._supportsFence = true;
b1dee947 1334
6d6f0db0
SR
1335 /*
1336 * Fence flags
1337 *
1338 * (1<<0) - BlockBefore
1339 * (1<<1) - BlockAfter
1340 * (1<<2) - SyncNext
1341 * (1<<31) - Request
1342 */
b1dee947 1343
6d6f0db0 1344 if (!(flags & (1<<31))) {
d472f3f1 1345 return this._fail("Unexpected fence response");
6d6f0db0 1346 }
b1dee947 1347
6d6f0db0
SR
1348 // Filter out unsupported flags
1349 // FIXME: support syncNext
1350 flags &= (1<<0) | (1<<1);
b1dee947 1351
6d6f0db0
SR
1352 // BlockBefore and BlockAfter are automatically handled by
1353 // the fact that we process each incoming message
1354 // synchronuosly.
1355 RFB.messages.clientFence(this._sock, flags, payload);
f78a652e 1356
6d6f0db0 1357 return true;
0e4808bf 1358 }
b1dee947 1359
0e4808bf 1360 _handle_xvp_msg() {
6d6f0db0 1361 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
8a189a62 1362 this._sock.rQskipBytes(1); // Padding
2b5f94fa
JD
1363 const xvp_ver = this._sock.rQshift8();
1364 const xvp_msg = this._sock.rQshift8();
b1dee947 1365
6d6f0db0
SR
1366 switch (xvp_msg) {
1367 case 0: // XVP_FAIL
5b20d338 1368 Log.Error("XVP Operation Failed");
6d6f0db0
SR
1369 break;
1370 case 1: // XVP_INIT
1371 this._rfb_xvp_ver = xvp_ver;
1372 Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
832be262 1373 this._setCapability("power", true);
6d6f0db0
SR
1374 break;
1375 default:
d472f3f1 1376 this._fail("Illegal server XVP message (msg: " + xvp_msg + ")");
6d6f0db0
SR
1377 break;
1378 }
b1dee947 1379
6d6f0db0 1380 return true;
0e4808bf 1381 }
3df13262 1382
0e4808bf 1383 _normal_msg() {
2b5f94fa 1384 let msg_type;
6d6f0db0
SR
1385 if (this._FBU.rects > 0) {
1386 msg_type = 0;
1387 } else {
1388 msg_type = this._sock.rQshift8();
1389 }
76a86ff5 1390
2b5f94fa 1391 let first, ret;
6d6f0db0
SR
1392 switch (msg_type) {
1393 case 0: // FramebufferUpdate
2b5f94fa 1394 ret = this._framebufferUpdate();
6d6f0db0
SR
1395 if (ret && !this._enabledContinuousUpdates) {
1396 RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
1397 this._fb_width, this._fb_height);
1398 }
1399 return ret;
3df13262 1400
6d6f0db0
SR
1401 case 1: // SetColorMapEntries
1402 return this._handle_set_colour_map_msg();
1403
1404 case 2: // Bell
1405 Log.Debug("Bell");
2b5f94fa 1406 this.dispatchEvent(new CustomEvent(
4a16dc51 1407 "bell",
2b5f94fa 1408 { detail: {} }));
6d6f0db0
SR
1409 return true;
1410
1411 case 3: // ServerCutText
1412 return this._handle_server_cut_text();
1413
1414 case 150: // EndOfContinuousUpdates
2b5f94fa 1415 first = !this._supportsContinuousUpdates;
6d6f0db0
SR
1416 this._supportsContinuousUpdates = true;
1417 this._enabledContinuousUpdates = false;
1418 if (first) {
1419 this._enabledContinuousUpdates = true;
1420 this._updateContinuousUpdates();
1421 Log.Info("Enabling continuous updates.");
1422 } else {
1423 // FIXME: We need to send a framebufferupdaterequest here
1424 // if we add support for turning off continuous updates
1425 }
1426 return true;
3df13262 1427
6d6f0db0
SR
1428 case 248: // ServerFence
1429 return this._handle_server_fence_msg();
3df13262 1430
6d6f0db0
SR
1431 case 250: // XVP
1432 return this._handle_xvp_msg();
3df13262 1433
6d6f0db0 1434 default:
d472f3f1 1435 this._fail("Unexpected server message (type " + msg_type + ")");
6d6f0db0
SR
1436 Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1437 return true;
1438 }
0e4808bf 1439 }
3df13262 1440
0e4808bf 1441 _onFlush() {
6d6f0db0
SR
1442 this._flushing = false;
1443 // Resume processing
8a189a62 1444 if (this._sock.rQlen > 0) {
6d6f0db0
SR
1445 this._handle_message();
1446 }
0e4808bf 1447 }
3df13262 1448
0e4808bf 1449 _framebufferUpdate() {
6d6f0db0
SR
1450 if (this._FBU.rects === 0) {
1451 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
8a189a62 1452 this._sock.rQskipBytes(1); // Padding
6d6f0db0 1453 this._FBU.rects = this._sock.rQshift16();
b1dee947 1454
6d6f0db0
SR
1455 // Make sure the previous frame is fully rendered first
1456 // to avoid building up an excessive queue
1457 if (this._display.pending()) {
1458 this._flushing = true;
1459 this._display.flush();
1460 return false;
1461 }
1462 }
b1dee947 1463
6d6f0db0 1464 while (this._FBU.rects > 0) {
923cd220 1465 if (this._FBU.encoding === null) {
6d6f0db0
SR
1466 if (this._sock.rQwait("rect header", 12)) { return false; }
1467 /* New FramebufferUpdate */
b1dee947 1468
2b5f94fa 1469 const hdr = this._sock.rQshiftBytes(12);
6d6f0db0
SR
1470 this._FBU.x = (hdr[0] << 8) + hdr[1];
1471 this._FBU.y = (hdr[2] << 8) + hdr[3];
1472 this._FBU.width = (hdr[4] << 8) + hdr[5];
1473 this._FBU.height = (hdr[6] << 8) + hdr[7];
1474 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1475 (hdr[10] << 8) + hdr[11], 10);
6d6f0db0 1476 }
b1dee947 1477
11309f32
PO
1478 if (!this._handleRect()) {
1479 return false;
6d6f0db0 1480 }
b1dee947 1481
11309f32 1482 this._FBU.rects--;
923cd220 1483 this._FBU.encoding = null;
6d6f0db0 1484 }
76a86ff5 1485
6d6f0db0 1486 this._display.flip();
3df13262 1487
6d6f0db0 1488 return true; // We finished this FBU
0e4808bf 1489 }
b1dee947 1490
11309f32
PO
1491 _handleRect() {
1492 switch (this._FBU.encoding) {
1493 case encodings.pseudoEncodingLastRect:
1494 this._FBU.rects = 1; // Will be decreased when we return
1495 return true;
b1dee947 1496
296ba51f
NL
1497 case encodings.pseudoEncodingVMwareCursor:
1498 return this._handleVMwareCursor();
1499
11309f32
PO
1500 case encodings.pseudoEncodingCursor:
1501 return this._handleCursor();
d9ca5e5b 1502
11309f32
PO
1503 case encodings.pseudoEncodingQEMUExtendedKeyEvent:
1504 // Old Safari doesn't support creating keyboard events
1505 try {
1506 const keyboardEvent = document.createEvent("keyboardEvent");
1507 if (keyboardEvent.code !== undefined) {
1508 this._qemuExtKeyEventSupported = true;
1509 }
1510 } catch (err) {
1511 // Do nothing
d9ca5e5b 1512 }
11309f32
PO
1513 return true;
1514
ce66b469
NL
1515 case encodings.pseudoEncodingDesktopName:
1516 return this._handleDesktopName();
1517
11309f32
PO
1518 case encodings.pseudoEncodingDesktopSize:
1519 this._resize(this._FBU.width, this._FBU.height);
1520 return true;
1521
1522 case encodings.pseudoEncodingExtendedDesktopSize:
1523 return this._handleExtendedDesktopSize();
1524
1525 default:
1526 return this._handleDataRect();
1527 }
1528 }
1529
296ba51f
NL
1530 _handleVMwareCursor() {
1531 const hotx = this._FBU.x; // hotspot-x
1532 const hoty = this._FBU.y; // hotspot-y
1533 const w = this._FBU.width;
1534 const h = this._FBU.height;
1535 if (this._sock.rQwait("VMware cursor encoding", 1)) {
1536 return false;
1537 }
1538
1539 const cursor_type = this._sock.rQshift8();
1540
1541 this._sock.rQshift8(); //Padding
1542
1543 let rgba;
1544 const bytesPerPixel = 4;
1545
1546 //Classic cursor
1547 if (cursor_type == 0) {
1548 //Used to filter away unimportant bits.
1549 //OR is used for correct conversion in js.
1550 const PIXEL_MASK = 0xffffff00 | 0;
1551 rgba = new Array(w * h * bytesPerPixel);
1552
1553 if (this._sock.rQwait("VMware cursor classic encoding",
1554 (w * h * bytesPerPixel) * 2, 2)) {
1555 return false;
1556 }
1557
1558 let and_mask = new Array(w * h);
1559 for (let pixel = 0; pixel < (w * h); pixel++) {
1560 and_mask[pixel] = this._sock.rQshift32();
1561 }
1562
1563 let xor_mask = new Array(w * h);
1564 for (let pixel = 0; pixel < (w * h); pixel++) {
1565 xor_mask[pixel] = this._sock.rQshift32();
1566 }
1567
1568 for (let pixel = 0; pixel < (w * h); pixel++) {
1569 if (and_mask[pixel] == 0) {
1570 //Fully opaque pixel
1571 let bgr = xor_mask[pixel];
1572 let r = bgr >> 8 & 0xff;
1573 let g = bgr >> 16 & 0xff;
1574 let b = bgr >> 24 & 0xff;
1575
1576 rgba[(pixel * bytesPerPixel) ] = r; //r
1577 rgba[(pixel * bytesPerPixel) + 1 ] = g; //g
1578 rgba[(pixel * bytesPerPixel) + 2 ] = b; //b
1579 rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; //a
1580
1581 } else if ((and_mask[pixel] & PIXEL_MASK) ==
1582 PIXEL_MASK) {
1583 //Only screen value matters, no mouse colouring
1584 if (xor_mask[pixel] == 0) {
1585 //Transparent pixel
1586 rgba[(pixel * bytesPerPixel) ] = 0x00;
1587 rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
1588 rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
1589 rgba[(pixel * bytesPerPixel) + 3 ] = 0x00;
1590
1591 } else if ((xor_mask[pixel] & PIXEL_MASK) ==
1592 PIXEL_MASK) {
1593 //Inverted pixel, not supported in browsers.
1594 //Fully opaque instead.
1595 rgba[(pixel * bytesPerPixel) ] = 0x00;
1596 rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
1597 rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
1598 rgba[(pixel * bytesPerPixel) + 3 ] = 0xff;
1599
1600 } else {
1601 //Unhandled xor_mask
1602 rgba[(pixel * bytesPerPixel) ] = 0x00;
1603 rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
1604 rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
1605 rgba[(pixel * bytesPerPixel) + 3 ] = 0xff;
1606 }
1607
1608 } else {
1609 //Unhandled and_mask
1610 rgba[(pixel * bytesPerPixel) ] = 0x00;
1611 rgba[(pixel * bytesPerPixel) + 1 ] = 0x00;
1612 rgba[(pixel * bytesPerPixel) + 2 ] = 0x00;
1613 rgba[(pixel * bytesPerPixel) + 3 ] = 0xff;
1614 }
1615 }
1616
1617 //Alpha cursor.
1618 } else if (cursor_type == 1) {
1619 if (this._sock.rQwait("VMware cursor alpha encoding",
1620 (w * h * 4), 2)) {
1621 return false;
1622 }
1623
1624 rgba = new Array(w * h * bytesPerPixel);
1625
1626 for (let pixel = 0; pixel < (w * h); pixel++) {
1627 let data = this._sock.rQshift32();
1628
1629 rgba[(pixel * 4) ] = data >> 8 & 0xff; //r
1630 rgba[(pixel * 4) + 1 ] = data >> 16 & 0xff; //g
1631 rgba[(pixel * 4) + 2 ] = data >> 24 & 0xff; //b
1632 rgba[(pixel * 4) + 3 ] = data & 0xff; //a
1633 }
1634
1635 } else {
1636 Log.Warn("The given cursor type is not supported: "
1637 + cursor_type + " given.");
1638 return false;
1639 }
1640
1641 this._updateCursor(rgba, hotx, hoty, w, h);
1642
1643 return true;
1644 }
1645
11309f32 1646 _handleCursor() {
679535ec
PO
1647 const hotx = this._FBU.x; // hotspot-x
1648 const hoty = this._FBU.y; // hotspot-y
11309f32
PO
1649 const w = this._FBU.width;
1650 const h = this._FBU.height;
1651
1652 const pixelslength = w * h * 4;
679535ec 1653 const masklength = Math.ceil(w / 8) * h;
11309f32 1654
923cd220
PO
1655 let bytes = pixelslength + masklength;
1656 if (this._sock.rQwait("cursor encoding", bytes)) {
11309f32
PO
1657 return false;
1658 }
1659
679535ec
PO
1660 // Decode from BGRX pixels + bit mask to RGBA
1661 const pixels = this._sock.rQshiftBytes(pixelslength);
1662 const mask = this._sock.rQshiftBytes(masklength);
1663 let rgba = new Uint8Array(w * h * 4);
1664
1665 let pix_idx = 0;
1666 for (let y = 0; y < h; y++) {
1667 for (let x = 0; x < w; x++) {
1668 let mask_idx = y * Math.ceil(w / 8) + Math.floor(x / 8);
1669 let alpha = (mask[mask_idx] << (x % 8)) & 0x80 ? 255 : 0;
1670 rgba[pix_idx ] = pixels[pix_idx + 2];
1671 rgba[pix_idx + 1] = pixels[pix_idx + 1];
1672 rgba[pix_idx + 2] = pixels[pix_idx];
1673 rgba[pix_idx + 3] = alpha;
1674 pix_idx += 4;
1675 }
1676 }
1677
1678 this._updateCursor(rgba, hotx, hoty, w, h);
11309f32 1679
11309f32
PO
1680 return true;
1681 }
1682
ce66b469
NL
1683 _handleDesktopName() {
1684 if (this._sock.rQwait("DesktopName", 4)) {
1685 return false;
1686 }
1687
1688 let length = this._sock.rQshift32();
1689
1690 if (this._sock.rQwait("DesktopName", length, 4)) {
1691 return false;
1692 }
1693
1694 let name = this._sock.rQshiftStr(length);
1695 name = decodeUTF8(name);
1696
1697 this._setDesktopName(name);
1698
1699 return true;
1700 }
1701
11309f32 1702 _handleExtendedDesktopSize() {
923cd220 1703 if (this._sock.rQwait("ExtendedDesktopSize", 4)) {
11309f32
PO
1704 return false;
1705 }
1706
1707 const number_of_screens = this._sock.rQpeek8();
1708
923cd220
PO
1709 let bytes = 4 + (number_of_screens * 16);
1710 if (this._sock.rQwait("ExtendedDesktopSize", bytes)) {
11309f32
PO
1711 return false;
1712 }
1713
1714 const firstUpdate = !this._supportsSetDesktopSize;
1715 this._supportsSetDesktopSize = true;
1716
1717 // Normally we only apply the current resize mode after a
1718 // window resize event. However there is no such trigger on the
1719 // initial connect. And we don't know if the server supports
1720 // resizing until we've gotten here.
1721 if (firstUpdate) {
1722 this._requestRemoteResize();
1723 }
1724
1725 this._sock.rQskipBytes(1); // number-of-screens
1726 this._sock.rQskipBytes(3); // padding
1727
1728 for (let i = 0; i < number_of_screens; i += 1) {
1729 // Save the id and flags of the first screen
1730 if (i === 0) {
1731 this._screen_id = this._sock.rQshiftBytes(4); // id
1732 this._sock.rQskipBytes(2); // x-position
1733 this._sock.rQskipBytes(2); // y-position
1734 this._sock.rQskipBytes(2); // width
1735 this._sock.rQskipBytes(2); // height
1736 this._screen_flags = this._sock.rQshiftBytes(4); // flags
1737 } else {
1738 this._sock.rQskipBytes(16);
b1dee947 1739 }
11309f32 1740 }
b1dee947 1741
11309f32
PO
1742 /*
1743 * The x-position indicates the reason for the change:
1744 *
1745 * 0 - server resized on its own
1746 * 1 - this client requested the resize
1747 * 2 - another client requested the resize
1748 */
1749
1750 // We need to handle errors when we requested the resize.
1751 if (this._FBU.x === 1 && this._FBU.y !== 0) {
1752 let msg = "";
1753 // The y-position indicates the status code from the server
1754 switch (this._FBU.y) {
9881899e
PO
1755 case 1:
1756 msg = "Resize is administratively prohibited";
1757 break;
1758 case 2:
1759 msg = "Out of resources";
1760 break;
1761 case 3:
1762 msg = "Invalid screen layout";
1763 break;
1764 default:
1765 msg = "Unknown reason";
1766 break;
11309f32
PO
1767 }
1768 Log.Warn("Server did not accept the resize request: "
1769 + msg);
1770 } else {
1771 this._resize(this._FBU.width, this._FBU.height);
6d6f0db0 1772 }
b1dee947 1773
11309f32
PO
1774 return true;
1775 }
b1dee947 1776
11309f32 1777 _handleDataRect() {
923cd220
PO
1778 let decoder = this._decoders[this._FBU.encoding];
1779 if (!decoder) {
11309f32
PO
1780 this._fail("Unsupported encoding (encoding: " +
1781 this._FBU.encoding + ")");
1782 return false;
1783 }
1784
923cd220
PO
1785 try {
1786 return decoder.decodeRect(this._FBU.x, this._FBU.y,
1787 this._FBU.width, this._FBU.height,
1788 this._sock, this._display,
1789 this._fb_depth);
1790 } catch (err) {
1791 this._fail("Error decoding rect: " + err);
1792 return false;
1793 }
0e4808bf 1794 }
b1dee947 1795
0e4808bf 1796 _updateContinuousUpdates() {
6d6f0db0 1797 if (!this._enabledContinuousUpdates) { return; }
b1dee947 1798
6d6f0db0
SR
1799 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1800 this._fb_width, this._fb_height);
0e4808bf 1801 }
91d5c625 1802
0e4808bf 1803 _resize(width, height) {
91d5c625
PO
1804 this._fb_width = width;
1805 this._fb_height = height;
1806
91d5c625 1807 this._display.resize(this._fb_width, this._fb_height);
e89eef94 1808
9b84f516
PO
1809 // Adjust the visible viewport based on the new dimensions
1810 this._updateClip();
1811 this._updateScale();
91d5c625 1812
91d5c625 1813 this._updateContinuousUpdates();
0e4808bf 1814 }
8db09746 1815
0e4808bf 1816 _xvpOp(ver, op) {
cd523e8f
PO
1817 if (this._rfb_xvp_ver < ver) { return; }
1818 Log.Info("Sending XVP operation " + op + " (version " + ver + ")");
1819 RFB.messages.xvpOp(this._sock, ver, op);
0e4808bf 1820 }
76a86ff5 1821
d1314d4b
AP
1822 _updateCursor(rgba, hotx, hoty, w, h) {
1823 this._cursorImage = {
1824 rgbaPixels: rgba,
1825 hotx: hotx, hoty: hoty, w: w, h: h,
1826 };
1827 this._refreshCursor();
1828 }
1829
4c38179d
AP
1830 _shouldShowDotCursor() {
1831 // Called when this._cursorImage is updated
1832 if (!this._showDotCursor) {
1833 // User does not want to see the dot, so...
1834 return false;
1835 }
1836
1837 // The dot should not be shown if the cursor is already visible,
1838 // i.e. contains at least one not-fully-transparent pixel.
1839 // So iterate through all alpha bytes in rgba and stop at the
1840 // first non-zero.
1841 for (let i = 3; i < this._cursorImage.rgbaPixels.length; i += 4) {
1842 if (this._cursorImage.rgbaPixels[i]) {
1843 return false;
1844 }
1845 }
1846
1847 // At this point, we know that the cursor is fully transparent, and
1848 // the user wants to see the dot instead of this.
1849 return true;
1850 }
1851
d1314d4b 1852 _refreshCursor() {
1f2bb528 1853 if (this._rfb_connection_state !== 'connected') { return; }
4c38179d
AP
1854 const image = this._shouldShowDotCursor() ? RFB.cursors.dot : this._cursorImage;
1855 this._cursor.change(image.rgbaPixels,
1856 image.hotx, image.hoty,
1857 image.w, image.h
d1314d4b
AP
1858 );
1859 }
1860
0e4808bf 1861 static genDES(password, challenge) {
0505214c
JD
1862 const passwordChars = password.split('').map(c => c.charCodeAt(0));
1863 return (new DES(passwordChars)).encrypt(challenge);
0e4808bf
JD
1864 }
1865}
76a86ff5 1866
6d6f0db0
SR
1867// Class Methods
1868RFB.messages = {
0e4808bf 1869 keyEvent(sock, keysym, down) {
2b5f94fa
JD
1870 const buff = sock._sQ;
1871 const offset = sock._sQlen;
8db09746 1872
6d6f0db0
SR
1873 buff[offset] = 4; // msg-type
1874 buff[offset + 1] = down;
b1dee947 1875
6d6f0db0
SR
1876 buff[offset + 2] = 0;
1877 buff[offset + 3] = 0;
fb49f91b 1878
6d6f0db0
SR
1879 buff[offset + 4] = (keysym >> 24);
1880 buff[offset + 5] = (keysym >> 16);
1881 buff[offset + 6] = (keysym >> 8);
1882 buff[offset + 7] = keysym;
b1dee947 1883
6d6f0db0
SR
1884 sock._sQlen += 8;
1885 sock.flush();
1886 },
ef1e8bab 1887
0e4808bf 1888 QEMUExtendedKeyEvent(sock, keysym, down, keycode) {
6d6f0db0 1889 function getRFBkeycode(xt_scancode) {
2b5f94fa
JD
1890 const upperByte = (keycode >> 8);
1891 const lowerByte = (keycode & 0x00ff);
6d6f0db0 1892 if (upperByte === 0xe0 && lowerByte < 0x7f) {
2b5f94fa 1893 return lowerByte | 0x80;
ef1e8bab 1894 }
6d6f0db0 1895 return xt_scancode;
ef1e8bab 1896 }
b1dee947 1897
2b5f94fa
JD
1898 const buff = sock._sQ;
1899 const offset = sock._sQlen;
8f06673a 1900
6d6f0db0
SR
1901 buff[offset] = 255; // msg-type
1902 buff[offset + 1] = 0; // sub msg-type
8f06673a 1903
6d6f0db0
SR
1904 buff[offset + 2] = (down >> 8);
1905 buff[offset + 3] = down;
8f06673a 1906
6d6f0db0
SR
1907 buff[offset + 4] = (keysym >> 24);
1908 buff[offset + 5] = (keysym >> 16);
1909 buff[offset + 6] = (keysym >> 8);
1910 buff[offset + 7] = keysym;
8f06673a 1911
2b5f94fa 1912 const RFBkeycode = getRFBkeycode(keycode);
8f06673a 1913
6d6f0db0
SR
1914 buff[offset + 8] = (RFBkeycode >> 24);
1915 buff[offset + 9] = (RFBkeycode >> 16);
1916 buff[offset + 10] = (RFBkeycode >> 8);
1917 buff[offset + 11] = RFBkeycode;
8f06673a 1918
6d6f0db0
SR
1919 sock._sQlen += 12;
1920 sock.flush();
1921 },
8f06673a 1922
0e4808bf 1923 pointerEvent(sock, x, y, mask) {
2b5f94fa
JD
1924 const buff = sock._sQ;
1925 const offset = sock._sQlen;
8f06673a 1926
6d6f0db0 1927 buff[offset] = 5; // msg-type
9ff86fb7 1928
6d6f0db0 1929 buff[offset + 1] = mask;
9ff86fb7 1930
6d6f0db0
SR
1931 buff[offset + 2] = x >> 8;
1932 buff[offset + 3] = x;
9ff86fb7 1933
6d6f0db0
SR
1934 buff[offset + 4] = y >> 8;
1935 buff[offset + 5] = y;
9ff86fb7 1936
6d6f0db0
SR
1937 sock._sQlen += 6;
1938 sock.flush();
1939 },
9ff86fb7 1940
6d6f0db0 1941 // TODO(directxman12): make this unicode compatible?
0e4808bf 1942 clientCutText(sock, text) {
2b5f94fa
JD
1943 const buff = sock._sQ;
1944 const offset = sock._sQlen;
b1dee947 1945
6d6f0db0 1946 buff[offset] = 6; // msg-type
9ff86fb7 1947
6d6f0db0
SR
1948 buff[offset + 1] = 0; // padding
1949 buff[offset + 2] = 0; // padding
1950 buff[offset + 3] = 0; // padding
9ff86fb7 1951
0e4808bf 1952 let length = text.length;
9ff86fb7 1953
2bb8b28d
SM
1954 buff[offset + 4] = length >> 24;
1955 buff[offset + 5] = length >> 16;
1956 buff[offset + 6] = length >> 8;
1957 buff[offset + 7] = length;
9ff86fb7 1958
2bb8b28d 1959 sock._sQlen += 8;
9ff86fb7 1960
2bb8b28d
SM
1961 // We have to keep track of from where in the text we begin creating the
1962 // buffer for the flush in the next iteration.
1963 let textOffset = 0;
1964
1965 let remaining = length;
1966 while (remaining > 0) {
1967
0e4808bf 1968 let flushSize = Math.min(remaining, (sock._sQbufferSize - sock._sQlen));
2bb8b28d 1969 for (let i = 0; i < flushSize; i++) {
2b5f94fa 1970 buff[sock._sQlen + i] = text.charCodeAt(textOffset + i);
2bb8b28d
SM
1971 }
1972
1973 sock._sQlen += flushSize;
1974 sock.flush();
1975
1976 remaining -= flushSize;
1977 textOffset += flushSize;
1978 }
6d6f0db0
SR
1979 },
1980
0e4808bf 1981 setDesktopSize(sock, width, height, id, flags) {
2b5f94fa
JD
1982 const buff = sock._sQ;
1983 const offset = sock._sQlen;
6d6f0db0
SR
1984
1985 buff[offset] = 251; // msg-type
1986 buff[offset + 1] = 0; // padding
1987 buff[offset + 2] = width >> 8; // width
1988 buff[offset + 3] = width;
1989 buff[offset + 4] = height >> 8; // height
1990 buff[offset + 5] = height;
1991
1992 buff[offset + 6] = 1; // number-of-screens
1993 buff[offset + 7] = 0; // padding
1994
1995 // screen array
1996 buff[offset + 8] = id >> 24; // id
1997 buff[offset + 9] = id >> 16;
1998 buff[offset + 10] = id >> 8;
1999 buff[offset + 11] = id;
2000 buff[offset + 12] = 0; // x-position
2001 buff[offset + 13] = 0;
2002 buff[offset + 14] = 0; // y-position
2003 buff[offset + 15] = 0;
2004 buff[offset + 16] = width >> 8; // width
2005 buff[offset + 17] = width;
2006 buff[offset + 18] = height >> 8; // height
2007 buff[offset + 19] = height;
2008 buff[offset + 20] = flags >> 24; // flags
2009 buff[offset + 21] = flags >> 16;
2010 buff[offset + 22] = flags >> 8;
2011 buff[offset + 23] = flags;
2012
2013 sock._sQlen += 24;
2014 sock.flush();
2015 },
2016
0e4808bf 2017 clientFence(sock, flags, payload) {
2b5f94fa
JD
2018 const buff = sock._sQ;
2019 const offset = sock._sQlen;
6d6f0db0
SR
2020
2021 buff[offset] = 248; // msg-type
2022
2023 buff[offset + 1] = 0; // padding
2024 buff[offset + 2] = 0; // padding
2025 buff[offset + 3] = 0; // padding
2026
2027 buff[offset + 4] = flags >> 24; // flags
2028 buff[offset + 5] = flags >> 16;
2029 buff[offset + 6] = flags >> 8;
2030 buff[offset + 7] = flags;
2031
2b5f94fa 2032 const n = payload.length;
6d6f0db0
SR
2033
2034 buff[offset + 8] = n; // length
2035
2b5f94fa 2036 for (let i = 0; i < n; i++) {
6d6f0db0
SR
2037 buff[offset + 9 + i] = payload.charCodeAt(i);
2038 }
a7a89626 2039
6d6f0db0
SR
2040 sock._sQlen += 9 + n;
2041 sock.flush();
2042 },
3df13262 2043
0e4808bf 2044 enableContinuousUpdates(sock, enable, x, y, width, height) {
2b5f94fa
JD
2045 const buff = sock._sQ;
2046 const offset = sock._sQlen;
3df13262 2047
6d6f0db0
SR
2048 buff[offset] = 150; // msg-type
2049 buff[offset + 1] = enable; // enable-flag
76a86ff5 2050
6d6f0db0
SR
2051 buff[offset + 2] = x >> 8; // x
2052 buff[offset + 3] = x;
2053 buff[offset + 4] = y >> 8; // y
2054 buff[offset + 5] = y;
2055 buff[offset + 6] = width >> 8; // width
2056 buff[offset + 7] = width;
2057 buff[offset + 8] = height >> 8; // height
2058 buff[offset + 9] = height;
76a86ff5 2059
6d6f0db0
SR
2060 sock._sQlen += 10;
2061 sock.flush();
2062 },
76a86ff5 2063
0e4808bf 2064 pixelFormat(sock, depth, true_color) {
2b5f94fa
JD
2065 const buff = sock._sQ;
2066 const offset = sock._sQlen;
ae116051 2067
2b5f94fa 2068 let bpp;
5a5f5ada
PO
2069
2070 if (depth > 16) {
2071 bpp = 32;
2072 } else if (depth > 8) {
2073 bpp = 16;
2074 } else {
2075 bpp = 8;
2076 }
2077
2b5f94fa 2078 const bits = Math.floor(depth/3);
5a5f5ada 2079
6d6f0db0 2080 buff[offset] = 0; // msg-type
9ff86fb7 2081
6d6f0db0
SR
2082 buff[offset + 1] = 0; // padding
2083 buff[offset + 2] = 0; // padding
2084 buff[offset + 3] = 0; // padding
9ff86fb7 2085
5a5f5ada
PO
2086 buff[offset + 4] = bpp; // bits-per-pixel
2087 buff[offset + 5] = depth; // depth
6d6f0db0
SR
2088 buff[offset + 6] = 0; // little-endian
2089 buff[offset + 7] = true_color ? 1 : 0; // true-color
9ff86fb7 2090
6d6f0db0 2091 buff[offset + 8] = 0; // red-max
5a5f5ada 2092 buff[offset + 9] = (1 << bits) - 1; // red-max
9ff86fb7 2093
6d6f0db0 2094 buff[offset + 10] = 0; // green-max
5a5f5ada 2095 buff[offset + 11] = (1 << bits) - 1; // green-max
9ff86fb7 2096
6d6f0db0 2097 buff[offset + 12] = 0; // blue-max
5a5f5ada 2098 buff[offset + 13] = (1 << bits) - 1; // blue-max
9ff86fb7 2099
5a5f5ada
PO
2100 buff[offset + 14] = bits * 2; // red-shift
2101 buff[offset + 15] = bits * 1; // green-shift
2102 buff[offset + 16] = bits * 0; // blue-shift
9ff86fb7 2103
6d6f0db0
SR
2104 buff[offset + 17] = 0; // padding
2105 buff[offset + 18] = 0; // padding
2106 buff[offset + 19] = 0; // padding
9ff86fb7 2107
6d6f0db0
SR
2108 sock._sQlen += 20;
2109 sock.flush();
2110 },
9ff86fb7 2111
0e4808bf 2112 clientEncodings(sock, encodings) {
2b5f94fa
JD
2113 const buff = sock._sQ;
2114 const offset = sock._sQlen;
b1dee947 2115
6d6f0db0
SR
2116 buff[offset] = 2; // msg-type
2117 buff[offset + 1] = 0; // padding
b1dee947 2118
49a81837
PO
2119 buff[offset + 2] = encodings.length >> 8;
2120 buff[offset + 3] = encodings.length;
9ff86fb7 2121
2b5f94fa
JD
2122 let j = offset + 4;
2123 for (let i = 0; i < encodings.length; i++) {
2124 const enc = encodings[i];
49a81837
PO
2125 buff[j] = enc >> 24;
2126 buff[j + 1] = enc >> 16;
2127 buff[j + 2] = enc >> 8;
2128 buff[j + 3] = enc;
a7a89626 2129
49a81837
PO
2130 j += 4;
2131 }
a7a89626 2132
6d6f0db0
SR
2133 sock._sQlen += j - offset;
2134 sock.flush();
2135 },
a679a97d 2136
0e4808bf 2137 fbUpdateRequest(sock, incremental, x, y, w, h) {
2b5f94fa
JD
2138 const buff = sock._sQ;
2139 const offset = sock._sQlen;
9ff86fb7 2140
6d6f0db0
SR
2141 if (typeof(x) === "undefined") { x = 0; }
2142 if (typeof(y) === "undefined") { y = 0; }
b1dee947 2143
6d6f0db0
SR
2144 buff[offset] = 3; // msg-type
2145 buff[offset + 1] = incremental ? 1 : 0;
9ff86fb7 2146
6d6f0db0
SR
2147 buff[offset + 2] = (x >> 8) & 0xFF;
2148 buff[offset + 3] = x & 0xFF;
9ff86fb7 2149
6d6f0db0
SR
2150 buff[offset + 4] = (y >> 8) & 0xFF;
2151 buff[offset + 5] = y & 0xFF;
9ff86fb7 2152
6d6f0db0
SR
2153 buff[offset + 6] = (w >> 8) & 0xFF;
2154 buff[offset + 7] = w & 0xFF;
9ff86fb7 2155
6d6f0db0
SR
2156 buff[offset + 8] = (h >> 8) & 0xFF;
2157 buff[offset + 9] = h & 0xFF;
b1dee947 2158
6d6f0db0
SR
2159 sock._sQlen += 10;
2160 sock.flush();
85b35fc0
PO
2161 },
2162
0e4808bf 2163 xvpOp(sock, ver, op) {
2b5f94fa
JD
2164 const buff = sock._sQ;
2165 const offset = sock._sQlen;
85b35fc0
PO
2166
2167 buff[offset] = 250; // msg-type
2168 buff[offset + 1] = 0; // padding
2169
2170 buff[offset + 2] = ver;
2171 buff[offset + 3] = op;
2172
2173 sock._sQlen += 4;
2174 sock.flush();
6d6f0db0 2175 }
6d6f0db0 2176};
b1dee947 2177
4c38179d
AP
2178RFB.cursors = {
2179 none: {
2180 rgbaPixels: new Uint8Array(),
2181 w: 0, h: 0,
2182 hotx: 0, hoty: 0,
2183 },
2184
2185 dot: {
9881899e 2186 /* eslint-disable indent */
4c38179d
AP
2187 rgbaPixels: new Uint8Array([
2188 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255,
2189 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 255,
2190 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255,
2191 ]),
9881899e 2192 /* eslint-enable indent */
4c38179d
AP
2193 w: 3, h: 3,
2194 hotx: 1, hoty: 1,
2195 }
2196};