]> git.proxmox.com Git - mirror_novnc.git/blame - core/rfb.js
Work around Siemens touch panel authentication bug
[mirror_novnc.git] / core / rfb.js
CommitLineData
a7a89626
JM
1/*
2 * noVNC: HTML5 VNC client
d58f8b51 3 * Copyright (C) 2012 Joel Martin
2bb8b28d 4 * Copyright (C) 2018 Samuel Mannehed for Cendio AB
1d728ace 5 * Licensed under MPL 2.0 (see LICENSE.txt)
a7a89626
JM
6 *
7 * See README.md for usage and integration instructions.
d38db74a
MT
8 *
9 * TIGHT decoder portion:
10 * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
a7a89626
JM
11 */
12
6d6f0db0 13import * as Log from './util/logging.js';
6d6f0db0 14import { decodeUTF8 } from './util/strings.js';
59ef2916 15import { supportsCursorURIs, isTouchDevice } from './util/browser.js';
e89eef94 16import EventTargetMixin from './util/eventtarget.js';
3ae0bb09 17import Display from "./display.js";
c1e2785f
SM
18import Keyboard from "./input/keyboard.js";
19import Mouse from "./input/mouse.js";
3ae0bb09 20import Websock from "./websock.js";
3ae0bb09
SR
21import DES from "./des.js";
22import KeyTable from "./input/keysym.js";
23import XtScancode from "./input/xtscancodes.js";
fba220c6 24import Inflator from "./inflator.js";
f8ec2df2 25import { encodings, encodingName } from "./encodings.js";
e89eef94 26import "./util/polyfill.js";
3ae0bb09 27
68e09edc 28// How many seconds to wait for a disconnect to finish
2b5f94fa 29const DISCONNECT_TIMEOUT = 3;
68e09edc 30
2f4516f2
PO
31export default function RFB(target, url, options) {
32 if (!target) {
33 throw Error("Must specify target");
34 }
35 if (!url) {
36 throw Error("Must specify URL");
ae510306
SR
37 }
38
3d7bb020 39 this._target = target;
2f4516f2 40 this._url = url;
ae510306 41
c7d08d72 42 // Connection details
4e1c5435 43 options = options || {};
2f4516f2
PO
44 this._rfb_credentials = options.credentials || {};
45 this._shared = 'shared' in options ? !!options.shared : true;
46 this._repeaterID = options.repeaterID || '';
ae510306 47
c7d08d72 48 // Internal state
3bb12056 49 this._rfb_connection_state = '';
c00ee156 50 this._rfb_init_state = '';
ae510306 51 this._rfb_auth_scheme = '';
d472f3f1 52 this._rfb_clean_disconnect = true;
ae510306 53
c7d08d72
PO
54 // Server capabilities
55 this._rfb_version = 0;
56 this._rfb_max_version = 3.8;
ae510306
SR
57 this._rfb_tightvnc = false;
58 this._rfb_xvp_ver = 0;
59
c7d08d72
PO
60 this._fb_width = 0;
61 this._fb_height = 0;
62
63 this._fb_name = "";
ae510306 64
9b84f516 65 this._capabilities = { power: false };
cd523e8f 66
c7d08d72 67 this._supportsFence = false;
ae510306 68
c7d08d72
PO
69 this._supportsContinuousUpdates = false;
70 this._enabledContinuousUpdates = false;
71
72 this._supportsSetDesktopSize = false;
73 this._screen_id = 0;
74 this._screen_flags = 0;
75
76 this._qemuExtKeyEventSupported = false;
77
78 // Internal objects
ae510306
SR
79 this._sock = null; // Websock object
80 this._display = null; // Display object
d9ca5e5b 81 this._flushing = false; // Display flushing state
ae510306
SR
82 this._keyboard = null; // Keyboard input handler object
83 this._mouse = null; // Mouse input handler object
ae510306 84
c7d08d72
PO
85 // Timers
86 this._disconnTimer = null; // disconnection timer
9b84f516 87 this._resizeTimeout = null; // resize rate limiting
ae510306 88
c7d08d72
PO
89 // Decoder states and stats
90 this._encHandlers = {};
91 this._encStats = {};
ae510306 92
ae510306
SR
93 this._FBU = {
94 rects: 0,
c7d08d72 95 subrects: 0, // RRE and HEXTILE
ae510306
SR
96 lines: 0, // RAW
97 tiles: 0, // HEXTILE
98 bytes: 0,
99 x: 0,
100 y: 0,
101 width: 0,
102 height: 0,
103 encoding: 0,
104 subencoding: -1,
105 background: null,
c7d08d72 106 zlibs: [] // TIGHT zlib streams
ae510306 107 };
2b5f94fa 108 for (let i = 0; i < 4; i++) {
c7d08d72
PO
109 this._FBU.zlibs[i] = new Inflator();
110 }
b1dee947 111
ae510306
SR
112 this._destBuff = null;
113 this._paletteBuff = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
b1dee947 114
ae510306 115 this._rre_chunk_sz = 100;
b1dee947 116
ae510306
SR
117 this._timing = {
118 last_fbu: 0,
119 fbu_total: 0,
120 fbu_total_cnt: 0,
121 full_fbu_total: 0,
122 full_fbu_cnt: 0,
b1dee947 123
ae510306
SR
124 fbu_rt_start: 0,
125 fbu_rt_total: 0,
126 fbu_rt_cnt: 0,
127 pixels: 0
128 };
129
ae510306
SR
130 // Mouse state
131 this._mouse_buttonMask = 0;
132 this._mouse_arr = [];
133 this._viewportDragging = false;
134 this._viewportDragPos = {};
135 this._viewportHasMoved = false;
136
1d6ff4a3
PO
137 // Bound event handlers
138 this._eventHandlers = {
139 focusCanvas: this._focusCanvas.bind(this),
9b84f516 140 windowResize: this._windowResize.bind(this),
1d6ff4a3
PO
141 };
142
ae510306 143 // main setup
6d6f0db0 144 Log.Debug(">> RFB.constructor");
ae510306 145
9b84f516
PO
146 // Create DOM elements
147 this._screen = document.createElement('div');
148 this._screen.style.display = 'flex';
149 this._screen.style.width = '100%';
150 this._screen.style.height = '100%';
151 this._screen.style.overflow = 'auto';
152 this._screen.style.backgroundColor = 'rgb(40, 40, 40)';
153 this._canvas = document.createElement('canvas');
154 this._canvas.style.margin = 'auto';
155 // Some browsers add an outline on focus
156 this._canvas.style.outline = 'none';
157 // IE miscalculates width without this :(
158 this._canvas.style.flexShrink = '0';
159 this._canvas.width = 0;
160 this._canvas.height = 0;
161 this._canvas.tabIndex = -1;
162 this._screen.appendChild(this._canvas);
45808617 163
ae510306 164 // populate encHandlers with bound versions
cd230363
SM
165 this._encHandlers[encodings.encodingRaw] = RFB.encodingHandlers.RAW.bind(this);
166 this._encHandlers[encodings.encodingCopyRect] = RFB.encodingHandlers.COPYRECT.bind(this);
167 this._encHandlers[encodings.encodingRRE] = RFB.encodingHandlers.RRE.bind(this);
168 this._encHandlers[encodings.encodingHextile] = RFB.encodingHandlers.HEXTILE.bind(this);
5bdcf5d3
PO
169 this._encHandlers[encodings.encodingTight] = RFB.encodingHandlers.TIGHT.bind(this, false);
170 this._encHandlers[encodings.encodingTightPNG] = RFB.encodingHandlers.TIGHT.bind(this, true);
cd230363
SM
171
172 this._encHandlers[encodings.pseudoEncodingDesktopSize] = RFB.encodingHandlers.DesktopSize.bind(this);
173 this._encHandlers[encodings.pseudoEncodingLastRect] = RFB.encodingHandlers.last_rect.bind(this);
174 this._encHandlers[encodings.pseudoEncodingCursor] = RFB.encodingHandlers.Cursor.bind(this);
175 this._encHandlers[encodings.pseudoEncodingQEMUExtendedKeyEvent] = RFB.encodingHandlers.QEMUExtendedKeyEvent.bind(this);
176 this._encHandlers[encodings.pseudoEncodingExtendedDesktopSize] = RFB.encodingHandlers.ExtendedDesktopSize.bind(this);
ae510306
SR
177
178 // NB: nothing that needs explicit teardown should be done
179 // before this point, since this can throw an exception
180 try {
9b84f516 181 this._display = new Display(this._canvas);
ae510306 182 } catch (exc) {
6d6f0db0 183 Log.Error("Display exception: " + exc);
ae510306
SR
184 throw exc;
185 }
747b4623 186 this._display.onflush = this._onFlush.bind(this);
c7d08d72 187 this._display.clear();
ae510306 188
9b84f516 189 this._keyboard = new Keyboard(this._canvas);
747b4623 190 this._keyboard.onkeyevent = this._handleKeyEvent.bind(this);
ae510306 191
9b84f516 192 this._mouse = new Mouse(this._canvas);
747b4623
PO
193 this._mouse.onmousebutton = this._handleMouseButton.bind(this);
194 this._mouse.onmousemove = this._handleMouseMove.bind(this);
ae510306
SR
195
196 this._sock = new Websock();
197 this._sock.on('message', this._handle_message.bind(this));
198 this._sock.on('open', function () {
c2a4d3ef 199 if ((this._rfb_connection_state === 'connecting') &&
c00ee156
SM
200 (this._rfb_init_state === '')) {
201 this._rfb_init_state = 'ProtocolVersion';
6d6f0db0 202 Log.Debug("Starting VNC handshake");
ae510306 203 } else {
d472f3f1
SM
204 this._fail("Unexpected server connection while " +
205 this._rfb_connection_state);
ae510306
SR
206 }
207 }.bind(this));
208 this._sock.on('close', function (e) {
ddcb60c3 209 Log.Debug("WebSocket on-close event");
2b5f94fa 210 let msg = "";
ae510306 211 if (e.code) {
d472f3f1 212 msg = "(code: " + e.code;
ae510306
SR
213 if (e.reason) {
214 msg += ", reason: " + e.reason;
b1dee947 215 }
ae510306
SR
216 msg += ")";
217 }
c00ee156 218 switch (this._rfb_connection_state) {
c2a4d3ef 219 case 'connecting':
d472f3f1 220 this._fail("Connection closed " + msg);
c00ee156 221 break;
b45905ab
SM
222 case 'connected':
223 // Handle disconnects that were initiated server-side
224 this._updateConnectionState('disconnecting');
225 this._updateConnectionState('disconnected');
226 break;
d472f3f1
SM
227 case 'disconnecting':
228 // Normal disconnection path
229 this._updateConnectionState('disconnected');
230 break;
c00ee156 231 case 'disconnected':
d472f3f1
SM
232 this._fail("Unexpected server disconnect " +
233 "when already disconnected " + msg);
c00ee156
SM
234 break;
235 default:
d472f3f1
SM
236 this._fail("Unexpected server disconnect before connecting " +
237 msg);
c00ee156 238 break;
a679a97d 239 }
ae510306
SR
240 this._sock.off('close');
241 }.bind(this));
242 this._sock.on('error', function (e) {
6d6f0db0 243 Log.Warn("WebSocket on-error event");
ae510306 244 });
8db09746 245
2f4516f2
PO
246 // Slight delay of the actual connection so that the caller has
247 // time to set up callbacks
248 setTimeout(this._updateConnectionState.bind(this, 'connecting'));
ae510306 249
6d6f0db0 250 Log.Debug("<< RFB.constructor");
8727f598 251}
a7a89626 252
6d6f0db0 253RFB.prototype = {
747b4623 254 // ===== PROPERTIES =====
6d6f0db0 255
0460e5fd 256 dragViewport: false,
a201bfc5 257 focusOnClick: true,
a7a89626 258
747b4623
PO
259 _viewOnly: false,
260 get viewOnly() { return this._viewOnly; },
261 set viewOnly(viewOnly) {
262 this._viewOnly = viewOnly;
263
264 if (this._rfb_connection_state === "connecting" ||
265 this._rfb_connection_state === "connected") {
266 if (viewOnly) {
267 this._keyboard.ungrab();
268 this._mouse.ungrab();
269 } else {
270 this._keyboard.grab();
271 this._mouse.grab();
272 }
273 }
6d6f0db0
SR
274 },
275
747b4623
PO
276 get capabilities() { return this._capabilities; },
277
278 get touchButton() { return this._mouse.touchButton; },
279 set touchButton(button) { this._mouse.touchButton = button; },
280
9b84f516
PO
281 _clipViewport: false,
282 get clipViewport() { return this._clipViewport; },
283 set clipViewport(viewport) {
284 this._clipViewport = viewport;
285 this._updateClip();
286 },
747b4623 287
9b84f516
PO
288 _scaleViewport: false,
289 get scaleViewport() { return this._scaleViewport; },
290 set scaleViewport(scale) {
291 this._scaleViewport = scale;
292 // Scaling trumps clipping, so we may need to adjust
293 // clipping when enabling or disabling scaling
294 if (scale && this._clipViewport) {
295 this._updateClip();
296 }
297 this._updateScale();
298 if (!scale && this._clipViewport) {
299 this._updateClip();
300 }
301 },
747b4623 302
9b84f516
PO
303 _resizeSession: false,
304 get resizeSession() { return this._resizeSession; },
305 set resizeSession(resize) {
306 this._resizeSession = resize;
307 if (resize) {
308 this._requestRemoteResize();
309 }
310 },
a80aa416 311
747b4623
PO
312 // ===== PUBLIC METHODS =====
313
6d6f0db0
SR
314 disconnect: function () {
315 this._updateConnectionState('disconnecting');
316 this._sock.off('error');
317 this._sock.off('message');
318 this._sock.off('open');
319 },
320
430f00d6
PO
321 sendCredentials: function (creds) {
322 this._rfb_credentials = creds;
6d6f0db0
SR
323 setTimeout(this._init_msg.bind(this), 0);
324 },
325
326 sendCtrlAltDel: function () {
15a62695 327 if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; }
6d6f0db0
SR
328 Log.Info("Sending Ctrl-Alt-Del");
329
94f5cf05
PO
330 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true);
331 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true);
332 this.sendKey(KeyTable.XK_Delete, "Delete", true);
333 this.sendKey(KeyTable.XK_Delete, "Delete", false);
334 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false);
335 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false);
6d6f0db0
SR
336 },
337
cd523e8f
PO
338 machineShutdown: function () {
339 this._xvpOp(1, 2);
6d6f0db0
SR
340 },
341
cd523e8f
PO
342 machineReboot: function () {
343 this._xvpOp(1, 3);
6d6f0db0
SR
344 },
345
cd523e8f
PO
346 machineReset: function () {
347 this._xvpOp(1, 4);
6d6f0db0
SR
348 },
349
350 // Send a key press. If 'down' is not specified then send a down key
351 // followed by an up key.
94f5cf05 352 sendKey: function (keysym, code, down) {
15a62695 353 if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; }
94f5cf05
PO
354
355 if (down === undefined) {
356 this.sendKey(keysym, code, true);
357 this.sendKey(keysym, code, false);
15a62695 358 return;
94f5cf05
PO
359 }
360
2b5f94fa 361 const scancode = XtScancode[code];
94f5cf05 362
be70fe0a 363 if (this._qemuExtKeyEventSupported && scancode) {
459ed008
PO
364 // 0 is NoSymbol
365 keysym = keysym || 0;
366
94f5cf05
PO
367 Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode);
368
369 RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode);
370 } else {
459ed008 371 if (!keysym) {
15a62695 372 return;
459ed008 373 }
6d6f0db0
SR
374 Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym);
375 RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0);
6d6f0db0 376 }
6d6f0db0
SR
377 },
378
9b84f516
PO
379 focus: function () {
380 this._canvas.focus();
b9854a5c
PO
381 },
382
9b84f516
PO
383 blur: function () {
384 this._canvas.blur();
b9854a5c
PO
385 },
386
9b84f516
PO
387 clipboardPasteFrom: function (text) {
388 if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; }
389 RFB.messages.clientCutText(this._sock, text);
6d6f0db0 390 },
b1dee947 391
747b4623 392 // ===== PRIVATE METHODS =====
b0ec6509 393
6d6f0db0
SR
394 _connect: function () {
395 Log.Debug(">> RFB.connect");
b0ec6509 396
5b4e5d01 397 Log.Info("connecting to " + this._url);
b1dee947 398
6d6f0db0
SR
399 try {
400 // WebSocket.onopen transitions to the RFB init states
f8318361 401 this._sock.open(this._url, ['binary']);
6d6f0db0
SR
402 } catch (e) {
403 if (e.name === 'SyntaxError') {
d472f3f1 404 this._fail("Invalid host or port (" + e + ")");
b1dee947 405 } else {
d472f3f1 406 this._fail("Error when opening socket (" + e + ")");
159ad55d 407 }
6d6f0db0 408 }
e3efeb32 409
9b84f516
PO
410 // Make our elements part of the page
411 this._target.appendChild(this._screen);
412
413 // Monitor size changes of the screen
414 // FIXME: Use ResizeObserver, or hidden overflow
415 window.addEventListener('resize', this._eventHandlers.windowResize);
416
2afda544 417 // Always grab focus on some kind of click event
9b84f516
PO
418 this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas);
419 this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas);
2afda544 420
6d6f0db0
SR
421 Log.Debug("<< RFB.connect");
422 },
423
424 _disconnect: function () {
425 Log.Debug(">> RFB.disconnect");
9b84f516
PO
426 this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas);
427 this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas);
428 window.removeEventListener('resize', this._eventHandlers.windowResize);
429 this._keyboard.ungrab();
430 this._mouse.ungrab();
6d6f0db0
SR
431 this._sock.close();
432 this._print_stats();
b245ec70
SM
433 try {
434 this._target.removeChild(this._screen);
435 } catch (e) {
436 if (e.name === 'NotFoundError') {
437 // Some cases where the initial connection fails
438 // can disconnect before the _screen is created
439 } else {
440 throw e;
441 }
442 }
9b84f516 443 clearTimeout(this._resizeTimeout);
6d6f0db0
SR
444 Log.Debug("<< RFB.disconnect");
445 },
446
6d6f0db0 447 _print_stats: function () {
2b5f94fa 448 const stats = this._encStats;
c3386227 449
6d6f0db0 450 Log.Info("Encoding stats for this connection:");
c3386227 451 Object.keys(stats).forEach(function (key) {
2b5f94fa 452 const s = stats[key];
6d6f0db0 453 if (s[0] + s[1] > 0) {
c3386227 454 Log.Info(" " + encodingName(key) + ": " + s[0] + " rects");
b1dee947 455 }
c3386227 456 });
a7a89626 457
6d6f0db0 458 Log.Info("Encoding stats since page load:");
c3386227 459 Object.keys(stats).forEach(function (key) {
2b5f94fa 460 const s = stats[key];
c3386227
PO
461 Log.Info(" " + encodingName(key) + ": " + s[1] + " rects");
462 });
6d6f0db0
SR
463 },
464
2afda544
PO
465 _focusCanvas: function(event) {
466 // Respect earlier handlers' request to not do side-effects
1d6ff4a3
PO
467 if (event.defaultPrevented) {
468 return;
469 }
470
b8dfb983 471 if (!this.focusOnClick) {
1d6ff4a3
PO
472 return;
473 }
474
9b84f516
PO
475 this.focus();
476 },
477
478 _windowResize: function (event) {
479 // If the window resized then our screen element might have
480 // as well. Update the viewport dimensions.
481 window.requestAnimationFrame(function () {
482 this._updateClip();
483 this._updateScale();
484 }.bind(this));
485
486 if (this._resizeSession) {
487 // Request changing the resolution of the remote display to
488 // the size of the local browser viewport.
489
490 // In order to not send multiple requests before the browser-resize
491 // is finished we wait 0.5 seconds before sending the request.
492 clearTimeout(this._resizeTimeout);
493 this._resizeTimeout = setTimeout(this._requestRemoteResize.bind(this), 500);
494 }
495 },
496
497 // Update state of clipping in Display object, and make sure the
498 // configured viewport matches the current screen size
499 _updateClip: function () {
2b5f94fa
JD
500 const cur_clip = this._display.clipViewport;
501 let new_clip = this._clipViewport;
9b84f516
PO
502
503 if (this._scaleViewport) {
504 // Disable viewport clipping if we are scaling
505 new_clip = false;
506 }
507
508 if (cur_clip !== new_clip) {
509 this._display.clipViewport = new_clip;
510 }
511
512 if (new_clip) {
513 // When clipping is enabled, the screen is limited to
514 // the size of the container.
2b5f94fa 515 const size = this._screenSize();
9b84f516
PO
516 this._display.viewportChangeSize(size.w, size.h);
517 this._fixScrollbars();
518 }
519 },
520
521 _updateScale: function () {
522 if (!this._scaleViewport) {
523 this._display.scale = 1.0;
524 } else {
2b5f94fa 525 const size = this._screenSize();
9b84f516
PO
526 this._display.autoscale(size.w, size.h);
527 }
528 this._fixScrollbars();
529 },
530
531 // Requests a change of remote desktop size. This message is an extension
532 // and may only be sent if we have received an ExtendedDesktopSize message
533 _requestRemoteResize: function () {
534 clearTimeout(this._resizeTimeout);
535 this._resizeTimeout = null;
536
537 if (!this._resizeSession || this._viewOnly ||
538 !this._supportsSetDesktopSize) {
539 return;
540 }
541
2b5f94fa 542 const size = this._screenSize();
9b84f516
PO
543 RFB.messages.setDesktopSize(this._sock, size.w, size.h,
544 this._screen_id, this._screen_flags);
545
546 Log.Debug('Requested new desktop size: ' +
547 size.w + 'x' + size.h);
548 },
549
550 // Gets the the size of the available screen
551 _screenSize: function () {
552 return { w: this._screen.offsetWidth,
553 h: this._screen.offsetHeight };
554 },
555
556 _fixScrollbars: function () {
557 // This is a hack because Chrome screws up the calculation
558 // for when scrollbars are needed. So to fix it we temporarily
559 // toggle them off and on.
2b5f94fa 560 const orig = this._screen.style.overflow;
9b84f516
PO
561 this._screen.style.overflow = 'hidden';
562 // Force Chrome to recalculate the layout by asking for
563 // an element's dimensions
564 this._screen.getBoundingClientRect();
565 this._screen.style.overflow = orig;
2afda544
PO
566 },
567
6d6f0db0
SR
568 /*
569 * Connection states:
570 * connecting
571 * connected
572 * disconnecting
573 * disconnected - permanent state
574 */
575 _updateConnectionState: function (state) {
2b5f94fa 576 const oldstate = this._rfb_connection_state;
6d6f0db0
SR
577
578 if (state === oldstate) {
579 Log.Debug("Already in state '" + state + "', ignoring");
580 return;
581 }
582
583 // The 'disconnected' state is permanent for each RFB object
584 if (oldstate === 'disconnected') {
585 Log.Error("Tried changing state of a disconnected RFB object");
586 return;
587 }
588
589 // Ensure proper transitions before doing anything
590 switch (state) {
591 case 'connected':
592 if (oldstate !== 'connecting') {
593 Log.Error("Bad transition to connected state, " +
594 "previous connection state: " + oldstate);
595 return;
b1dee947 596 }
6d6f0db0 597 break;
a7a89626 598
6d6f0db0
SR
599 case 'disconnected':
600 if (oldstate !== 'disconnecting') {
601 Log.Error("Bad transition to disconnected state, " +
602 "previous connection state: " + oldstate);
603 return;
604 }
605 break;
a7a89626 606
6d6f0db0
SR
607 case 'connecting':
608 if (oldstate !== '') {
609 Log.Error("Bad transition to connecting state, " +
610 "previous connection state: " + oldstate);
611 return;
612 }
613 break;
b1dee947 614
6d6f0db0
SR
615 case 'disconnecting':
616 if (oldstate !== 'connected' && oldstate !== 'connecting') {
617 Log.Error("Bad transition to disconnecting state, " +
618 "previous connection state: " + oldstate);
619 return;
620 }
621 break;
a679a97d 622
6d6f0db0
SR
623 default:
624 Log.Error("Unknown connection state: " + state);
3bb12056 625 return;
6d6f0db0 626 }
b1dee947 627
6d6f0db0 628 // State change actions
3bb12056 629
6d6f0db0 630 this._rfb_connection_state = state;
b2e961d4 631
2b5f94fa 632 const smsg = "New state '" + state + "', was '" + oldstate + "'.";
6d6f0db0 633 Log.Debug(smsg);
b2e961d4 634
6d6f0db0
SR
635 if (this._disconnTimer && state !== 'disconnecting') {
636 Log.Debug("Clearing disconnect timer");
637 clearTimeout(this._disconnTimer);
638 this._disconnTimer = null;
3bb12056 639
6d6f0db0
SR
640 // make sure we don't get a double event
641 this._sock.off('close');
642 }
b2e961d4 643
6d6f0db0 644 switch (state) {
6d6f0db0
SR
645 case 'connecting':
646 this._connect();
647 break;
b2e961d4 648
ee5cae9f 649 case 'connected':
2b5f94fa 650 this.dispatchEvent(new CustomEvent("connect", { detail: {} }));
ee5cae9f
SM
651 break;
652
6d6f0db0
SR
653 case 'disconnecting':
654 this._disconnect();
b2e961d4 655
6d6f0db0 656 this._disconnTimer = setTimeout(function () {
d472f3f1 657 Log.Error("Disconnection timed out.");
6d6f0db0 658 this._updateConnectionState('disconnected');
68e09edc 659 }.bind(this), DISCONNECT_TIMEOUT * 1000);
6d6f0db0 660 break;
ee5cae9f
SM
661
662 case 'disconnected':
2b5f94fa 663 this.dispatchEvent(new CustomEvent(
d472f3f1 664 "disconnect", { detail:
2b5f94fa 665 { clean: this._rfb_clean_disconnect } }));
ee5cae9f 666 break;
6d6f0db0
SR
667 }
668 },
669
670 /* Print errors and disconnect
671 *
d472f3f1 672 * The parameter 'details' is used for information that
6d6f0db0
SR
673 * should be logged but not sent to the user interface.
674 */
d472f3f1 675 _fail: function (details) {
6d6f0db0
SR
676 switch (this._rfb_connection_state) {
677 case 'disconnecting':
d472f3f1 678 Log.Error("Failed when disconnecting: " + details);
6d6f0db0
SR
679 break;
680 case 'connected':
d472f3f1 681 Log.Error("Failed while connected: " + details);
6d6f0db0
SR
682 break;
683 case 'connecting':
d472f3f1 684 Log.Error("Failed when connecting: " + details);
6d6f0db0
SR
685 break;
686 default:
d472f3f1 687 Log.Error("RFB failure: " + details);
6d6f0db0
SR
688 break;
689 }
d472f3f1 690 this._rfb_clean_disconnect = false; //This is sent to the UI
6d6f0db0
SR
691
692 // Transition to disconnected without waiting for socket to close
693 this._updateConnectionState('disconnecting');
694 this._updateConnectionState('disconnected');
695
696 return false;
697 },
698
832be262
PO
699 _setCapability: function (cap, val) {
700 this._capabilities[cap] = val;
2b5f94fa
JD
701 this.dispatchEvent(new CustomEvent("capabilities",
702 { detail: { capabilities: this._capabilities } }));
6d6f0db0 703 },
b1dee947 704
6d6f0db0
SR
705 _handle_message: function () {
706 if (this._sock.rQlen() === 0) {
707 Log.Warn("handle_message called on an empty receive queue");
708 return;
709 }
b1dee947 710
6d6f0db0
SR
711 switch (this._rfb_connection_state) {
712 case 'disconnected':
713 Log.Error("Got data while disconnected");
714 break;
715 case 'connected':
716 while (true) {
717 if (this._flushing) {
718 break;
719 }
720 if (!this._normal_msg()) {
721 break;
722 }
723 if (this._sock.rQlen() === 0) {
724 break;
725 }
726 }
727 break;
728 default:
729 this._init_msg();
730 break;
731 }
732 },
3bb12056 733
d0703d1b
PO
734 _handleKeyEvent: function (keysym, code, down) {
735 this.sendKey(keysym, code, down);
6d6f0db0 736 },
06a9ef0c 737
6d6f0db0
SR
738 _handleMouseButton: function (x, y, down, bmask) {
739 if (down) {
740 this._mouse_buttonMask |= bmask;
741 } else {
270bdbd7 742 this._mouse_buttonMask &= ~bmask;
6d6f0db0 743 }
a7127fee 744
0460e5fd 745 if (this.dragViewport) {
6d6f0db0
SR
746 if (down && !this._viewportDragging) {
747 this._viewportDragging = true;
748 this._viewportDragPos = {'x': x, 'y': y};
898cd32c 749 this._viewportHasMoved = false;
a7127fee 750
6d6f0db0 751 // Skip sending mouse events
b1dee947 752 return;
6d6f0db0
SR
753 } else {
754 this._viewportDragging = false;
8db09746 755
898cd32c
PO
756 // If we actually performed a drag then we are done
757 // here and should not send any mouse events
758 if (this._viewportHasMoved) {
759 return;
6d6f0db0 760 }
898cd32c
PO
761
762 // Otherwise we treat this as a mouse click event.
763 // Send the button down event here, as the button up
764 // event is sent at the end of this function.
765 RFB.messages.pointerEvent(this._sock,
766 this._display.absX(x),
767 this._display.absY(y),
768 bmask);
b1dee947 769 }
6d6f0db0 770 }
8db09746 771
747b4623 772 if (this._viewOnly) { return; } // View only, skip mouse events
8f06673a 773
6d6f0db0
SR
774 if (this._rfb_connection_state !== 'connected') { return; }
775 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
776 },
8db09746 777
6d6f0db0
SR
778 _handleMouseMove: function (x, y) {
779 if (this._viewportDragging) {
2b5f94fa
JD
780 const deltaX = this._viewportDragPos.x - x;
781 const deltaY = this._viewportDragPos.y - y;
8db09746 782
6d6f0db0
SR
783 // The goal is to trigger on a certain physical width, the
784 // devicePixelRatio brings us a bit closer but is not optimal.
2b5f94fa 785 const dragThreshold = 10 * (window.devicePixelRatio || 1);
8db09746 786
6d6f0db0
SR
787 if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
788 Math.abs(deltaY) > dragThreshold)) {
789 this._viewportHasMoved = true;
27e77d46 790
6d6f0db0
SR
791 this._viewportDragPos = {'x': x, 'y': y};
792 this._display.viewportChangePos(deltaX, deltaY);
b50f3406 793 }
8db09746 794
6d6f0db0
SR
795 // Skip sending mouse events
796 return;
797 }
b1dee947 798
747b4623 799 if (this._viewOnly) { return; } // View only, skip mouse events
b1dee947 800
6d6f0db0
SR
801 if (this._rfb_connection_state !== 'connected') { return; }
802 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
803 },
b1dee947 804
6d6f0db0 805 // Message Handlers
27e77d46 806
6d6f0db0
SR
807 _negotiate_protocol_version: function () {
808 if (this._sock.rQlen() < 12) {
d472f3f1 809 return this._fail("Received incomplete protocol version.");
6d6f0db0 810 }
32df3fdb 811
2b5f94fa 812 const sversion = this._sock.rQshiftStr(12).substr(4, 7);
6d6f0db0 813 Log.Info("Server ProtocolVersion: " + sversion);
2b5f94fa 814 let is_repeater = 0;
6d6f0db0
SR
815 switch (sversion) {
816 case "000.000": // UltraVNC repeater
817 is_repeater = 1;
818 break;
819 case "003.003":
820 case "003.006": // UltraVNC
821 case "003.889": // Apple Remote Desktop
822 this._rfb_version = 3.3;
823 break;
824 case "003.007":
825 this._rfb_version = 3.7;
826 break;
827 case "003.008":
828 case "004.000": // Intel AMT KVM
829 case "004.001": // RealVNC 4.6
830 case "005.000": // RealVNC 5.3
831 this._rfb_version = 3.8;
832 break;
833 default:
d472f3f1 834 return this._fail("Invalid server version " + sversion);
6d6f0db0 835 }
8db09746 836
6d6f0db0 837 if (is_repeater) {
2b5f94fa 838 let repeaterID = "ID:" + this._repeaterID;
6d6f0db0
SR
839 while (repeaterID.length < 250) {
840 repeaterID += "\0";
b1dee947 841 }
6d6f0db0
SR
842 this._sock.send_string(repeaterID);
843 return true;
844 }
b1dee947 845
6d6f0db0
SR
846 if (this._rfb_version > this._rfb_max_version) {
847 this._rfb_version = this._rfb_max_version;
848 }
b1dee947 849
2b5f94fa 850 const cversion = "00" + parseInt(this._rfb_version, 10) +
6d6f0db0
SR
851 ".00" + ((this._rfb_version * 10) % 10);
852 this._sock.send_string("RFB " + cversion + "\n");
853 Log.Debug('Sent ProtocolVersion: ' + cversion);
b1dee947 854
6d6f0db0
SR
855 this._rfb_init_state = 'Security';
856 },
b1dee947 857
6d6f0db0
SR
858 _negotiate_security: function () {
859 // Polyfill since IE and PhantomJS doesn't have
860 // TypedArray.includes()
861 function includes(item, array) {
2b5f94fa 862 for (let i = 0; i < array.length; i++) {
6d6f0db0
SR
863 if (array[i] === item) {
864 return true;
865 }
b1dee947 866 }
6d6f0db0
SR
867 return false;
868 }
b1dee947 869
6d6f0db0
SR
870 if (this._rfb_version >= 3.7) {
871 // Server sends supported list, client decides
2b5f94fa 872 const num_types = this._sock.rQshift8();
6d6f0db0 873 if (this._sock.rQwait("security type", num_types, 1)) { return false; }
b1dee947 874
6d6f0db0 875 if (num_types === 0) {
d472f3f1 876 return this._handle_security_failure("no security types");
6d6f0db0
SR
877 }
878
2b5f94fa 879 const types = this._sock.rQshiftBytes(num_types);
6d6f0db0
SR
880 Log.Debug("Server security types: " + types);
881
882 // Look for each auth in preferred order
883 this._rfb_auth_scheme = 0;
884 if (includes(1, types)) {
885 this._rfb_auth_scheme = 1; // None
886 } else if (includes(22, types)) {
887 this._rfb_auth_scheme = 22; // XVP
888 } else if (includes(16, types)) {
889 this._rfb_auth_scheme = 16; // Tight
890 } else if (includes(2, types)) {
891 this._rfb_auth_scheme = 2; // VNC Auth
892 } else {
d472f3f1 893 return this._fail("Unsupported security types (types: " + types + ")");
8db09746 894 }
b1dee947 895
6d6f0db0
SR
896 this._sock.send([this._rfb_auth_scheme]);
897 } else {
898 // Server decides
899 if (this._sock.rQwait("security scheme", 4)) { return false; }
900 this._rfb_auth_scheme = this._sock.rQshift32();
901 }
b1dee947 902
6d6f0db0
SR
903 this._rfb_init_state = 'Authentication';
904 Log.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme);
b1dee947 905
6d6f0db0
SR
906 return this._init_msg(); // jump to authentication
907 },
b1dee947 908
d472f3f1
SM
909 /*
910 * Get the security failure reason if sent from the server and
911 * send the 'securityfailure' event.
912 *
913 * - The optional parameter context can be used to add some extra
914 * context to the log output.
915 *
916 * - The optional parameter security_result_status can be used to
917 * add a custom status code to the event.
918 */
919 _handle_security_failure: function (context, security_result_status) {
920
921 if (typeof context === 'undefined') {
922 context = "";
923 } else {
924 context = " on " + context;
925 }
926
927 if (typeof security_result_status === 'undefined') {
928 security_result_status = 1; // fail
929 }
930
931 if (this._sock.rQwait("reason length", 4)) {
932 return false;
933 }
2b5f94fa 934 const strlen = this._sock.rQshift32();
d472f3f1
SM
935 let reason = "";
936
937 if (strlen > 0) {
938 if (this._sock.rQwait("reason", strlen, 8)) { return false; }
939 reason = this._sock.rQshiftStr(strlen);
940 }
941
942 if (reason !== "") {
2b5f94fa 943 this.dispatchEvent(new CustomEvent(
d472f3f1 944 "securityfailure",
2b5f94fa 945 { detail: { status: security_result_status, reason: reason } }));
d472f3f1
SM
946
947 return this._fail("Security negotiation failed" + context +
948 " (reason: " + reason + ")");
949 } else {
2b5f94fa 950 this.dispatchEvent(new CustomEvent(
d472f3f1 951 "securityfailure",
2b5f94fa 952 { detail: { status: security_result_status } }));
d472f3f1
SM
953
954 return this._fail("Security negotiation failed" + context);
955 }
956 },
957
6d6f0db0
SR
958 // authentication
959 _negotiate_xvp_auth: function () {
430f00d6
PO
960 if (!this._rfb_credentials.username ||
961 !this._rfb_credentials.password ||
962 !this._rfb_credentials.target) {
2b5f94fa
JD
963 this.dispatchEvent(new CustomEvent(
964 "credentialsrequired",
965 { detail: { types: ["username", "password", "target"] } }));
6d6f0db0
SR
966 return false;
967 }
0ee5ca6e 968
2b5f94fa 969 const xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) +
430f00d6
PO
970 String.fromCharCode(this._rfb_credentials.target.length) +
971 this._rfb_credentials.username +
972 this._rfb_credentials.target;
6d6f0db0 973 this._sock.send_string(xvp_auth_str);
6d6f0db0
SR
974 this._rfb_auth_scheme = 2;
975 return this._negotiate_authentication();
976 },
977
978 _negotiate_std_vnc_auth: function () {
abfe5b7a
SM
979 if (this._sock.rQwait("auth challenge", 16)) { return false; }
980
430f00d6 981 if (!this._rfb_credentials.password) {
2b5f94fa
JD
982 this.dispatchEvent(new CustomEvent(
983 "credentialsrequired",
984 { detail: { types: ["password"] } }));
6d6f0db0
SR
985 return false;
986 }
b1dee947 987
6d6f0db0 988 // TODO(directxman12): make genDES not require an Array
2b5f94fa
JD
989 const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
990 const response = RFB.genDES(this._rfb_credentials.password, challenge);
6d6f0db0
SR
991 this._sock.send(response);
992 this._rfb_init_state = "SecurityResult";
993 return true;
994 },
995
996 _negotiate_tight_tunnels: function (numTunnels) {
2b5f94fa 997 const clientSupportedTunnelTypes = {
6d6f0db0
SR
998 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
999 };
2b5f94fa 1000 const serverSupportedTunnelTypes = {};
6d6f0db0 1001 // receive tunnel capabilities
2b5f94fa
JD
1002 for (let i = 0; i < numTunnels; i++) {
1003 const cap_code = this._sock.rQshift32();
1004 const cap_vendor = this._sock.rQshiftStr(4);
1005 const cap_signature = this._sock.rQshiftStr(8);
6d6f0db0
SR
1006 serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature };
1007 }
1008
e6bad200
PO
1009 Log.Debug("Server Tight tunnel types: " + serverSupportedTunnelTypes);
1010
8f47bd29
PO
1011 // Siemens touch panels have a VNC server that supports NOTUNNEL,
1012 // but forgets to advertise it. Try to detect such servers by
1013 // looking for their custom tunnel type.
1014 if (serverSupportedTunnelTypes[1] &&
1015 (serverSupportedTunnelTypes[1].vendor === "SICR") &&
1016 (serverSupportedTunnelTypes[1].signature === "SCHANNEL")) {
1017 Log.Debug("Detected Siemens server. Assuming NOTUNNEL support.");
1018 serverSupportedTunnelTypes[0] = { vendor: 'TGHT', signature: 'NOTUNNEL' };
1019 }
1020
6d6f0db0
SR
1021 // choose the notunnel type
1022 if (serverSupportedTunnelTypes[0]) {
1023 if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
1024 serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
d472f3f1 1025 return this._fail("Client's tunnel type had the incorrect " +
6d6f0db0 1026 "vendor or signature");
b1dee947 1027 }
e6bad200 1028 Log.Debug("Selected tunnel type: " + clientSupportedTunnelTypes[0]);
6d6f0db0
SR
1029 this._sock.send([0, 0, 0, 0]); // use NOTUNNEL
1030 return false; // wait until we receive the sub auth count to continue
1031 } else {
d472f3f1 1032 return this._fail("Server wanted tunnels, but doesn't support " +
6d6f0db0
SR
1033 "the notunnel type");
1034 }
1035 },
b1dee947 1036
6d6f0db0
SR
1037 _negotiate_tight_auth: function () {
1038 if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation
1039 if (this._sock.rQwait("num tunnels", 4)) { return false; }
2b5f94fa 1040 const numTunnels = this._sock.rQshift32();
6d6f0db0 1041 if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
c00ee156 1042
6d6f0db0 1043 this._rfb_tightvnc = true;
b1dee947 1044
6d6f0db0
SR
1045 if (numTunnels > 0) {
1046 this._negotiate_tight_tunnels(numTunnels);
1047 return false; // wait until we receive the sub auth to continue
b1dee947 1048 }
6d6f0db0 1049 }
b1dee947 1050
6d6f0db0
SR
1051 // second pass, do the sub-auth negotiation
1052 if (this._sock.rQwait("sub auth count", 4)) { return false; }
2b5f94fa 1053 const subAuthCount = this._sock.rQshift32();
6d6f0db0
SR
1054 if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
1055 this._rfb_init_state = 'SecurityResult';
1056 return true;
1057 }
b1dee947 1058
6d6f0db0 1059 if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
b1dee947 1060
2b5f94fa 1061 const clientSupportedTypes = {
6d6f0db0
SR
1062 'STDVNOAUTH__': 1,
1063 'STDVVNCAUTH_': 2
1064 };
b1dee947 1065
2b5f94fa 1066 const serverSupportedTypes = [];
95eb681b 1067
2b5f94fa 1068 for (let i = 0; i < subAuthCount; i++) {
8727f598 1069 this._sock.rQshift32(); // capNum
2b5f94fa 1070 const capabilities = this._sock.rQshiftStr(12);
6d6f0db0
SR
1071 serverSupportedTypes.push(capabilities);
1072 }
d86cc2d9 1073
e6bad200
PO
1074 Log.Debug("Server Tight authentication types: " + serverSupportedTypes);
1075
2b5f94fa 1076 for (let authType in clientSupportedTypes) {
6d6f0db0
SR
1077 if (serverSupportedTypes.indexOf(authType) != -1) {
1078 this._sock.send([0, 0, 0, clientSupportedTypes[authType]]);
e6bad200 1079 Log.Debug("Selected authentication type: " + authType);
d86cc2d9 1080
6d6f0db0
SR
1081 switch (authType) {
1082 case 'STDVNOAUTH__': // no auth
1083 this._rfb_init_state = 'SecurityResult';
1084 return true;
1085 case 'STDVVNCAUTH_': // VNC auth
1086 this._rfb_auth_scheme = 2;
1087 return this._init_msg();
1088 default:
d472f3f1
SM
1089 return this._fail("Unsupported tiny auth scheme " +
1090 "(scheme: " + authType + ")");
b1dee947
SR
1091 }
1092 }
6d6f0db0 1093 }
b1dee947 1094
d472f3f1 1095 return this._fail("No supported sub-auth types!");
6d6f0db0
SR
1096 },
1097
1098 _negotiate_authentication: function () {
1099 switch (this._rfb_auth_scheme) {
1100 case 0: // connection failed
d472f3f1 1101 return this._handle_security_failure("authentication scheme");
6d6f0db0
SR
1102
1103 case 1: // no auth
1104 if (this._rfb_version >= 3.8) {
1105 this._rfb_init_state = 'SecurityResult';
1106 return true;
1107 }
1108 this._rfb_init_state = 'ClientInitialisation';
1109 return this._init_msg();
95eb681b 1110
6d6f0db0
SR
1111 case 22: // XVP auth
1112 return this._negotiate_xvp_auth();
d86cc2d9 1113
6d6f0db0
SR
1114 case 2: // VNC authentication
1115 return this._negotiate_std_vnc_auth();
d86cc2d9 1116
6d6f0db0
SR
1117 case 16: // TightVNC Security Type
1118 return this._negotiate_tight_auth();
d86cc2d9 1119
6d6f0db0 1120 default:
d472f3f1
SM
1121 return this._fail("Unsupported auth scheme (scheme: " +
1122 this._rfb_auth_scheme + ")");
6d6f0db0
SR
1123 }
1124 },
1125
1126 _handle_security_result: function () {
1127 if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
d472f3f1 1128
2b5f94fa 1129 const status = this._sock.rQshift32();
d472f3f1
SM
1130
1131 if (status === 0) { // OK
1132 this._rfb_init_state = 'ClientInitialisation';
1133 Log.Debug('Authentication OK');
1134 return this._init_msg();
1135 } else {
1136 if (this._rfb_version >= 3.8) {
1137 return this._handle_security_failure("security result", status);
1138 } else {
2b5f94fa
JD
1139 this.dispatchEvent(new CustomEvent(
1140 "securityfailure",
1141 { detail: { status: status } }));
d472f3f1
SM
1142
1143 return this._fail("Security handshake failed");
1144 }
6d6f0db0
SR
1145 }
1146 },
1147
1148 _negotiate_server_init: function () {
1149 if (this._sock.rQwait("server initialization", 24)) { return false; }
1150
1151 /* Screen size */
2b5f94fa
JD
1152 const width = this._sock.rQshift16();
1153 const height = this._sock.rQshift16();
6d6f0db0
SR
1154
1155 /* PIXEL_FORMAT */
2b5f94fa
JD
1156 const bpp = this._sock.rQshift8();
1157 const depth = this._sock.rQshift8();
1158 const big_endian = this._sock.rQshift8();
1159 const true_color = this._sock.rQshift8();
1160
1161 const red_max = this._sock.rQshift16();
1162 const green_max = this._sock.rQshift16();
1163 const blue_max = this._sock.rQshift16();
1164 const red_shift = this._sock.rQshift8();
1165 const green_shift = this._sock.rQshift8();
1166 const blue_shift = this._sock.rQshift8();
6d6f0db0
SR
1167 this._sock.rQskipBytes(3); // padding
1168
1169 // NB(directxman12): we don't want to call any callbacks or print messages until
1170 // *after* we're past the point where we could backtrack
1171
1172 /* Connection name/title */
2b5f94fa 1173 const name_length = this._sock.rQshift32();
6d6f0db0
SR
1174 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1175 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1176
1177 if (this._rfb_tightvnc) {
1178 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1179 // In TightVNC mode, ServerInit message is extended
2b5f94fa
JD
1180 const numServerMessages = this._sock.rQshift16();
1181 const numClientMessages = this._sock.rQshift16();
1182 const numEncodings = this._sock.rQshift16();
6d6f0db0
SR
1183 this._sock.rQskipBytes(2); // padding
1184
2b5f94fa 1185 const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
6d6f0db0
SR
1186 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1187
1188 // we don't actually do anything with the capability information that TIGHT sends,
1189 // so we just skip the all of this.
1190
1191 // TIGHT server message capabilities
1192 this._sock.rQskipBytes(16 * numServerMessages);
1193
1194 // TIGHT client message capabilities
1195 this._sock.rQskipBytes(16 * numClientMessages);
1196
1197 // TIGHT encoding capabilities
1198 this._sock.rQskipBytes(16 * numEncodings);
1199 }
d86cc2d9 1200
6d6f0db0
SR
1201 // NB(directxman12): these are down here so that we don't run them multiple times
1202 // if we backtrack
91d5c625 1203 Log.Info("Screen: " + width + "x" + height +
6d6f0db0
SR
1204 ", bpp: " + bpp + ", depth: " + depth +
1205 ", big_endian: " + big_endian +
1206 ", true_color: " + true_color +
1207 ", red_max: " + red_max +
1208 ", green_max: " + green_max +
1209 ", blue_max: " + blue_max +
1210 ", red_shift: " + red_shift +
1211 ", green_shift: " + green_shift +
1212 ", blue_shift: " + blue_shift);
1213
1214 if (big_endian !== 0) {
1215 Log.Warn("Server native endian is not little endian");
1216 }
b1dee947 1217
6d6f0db0
SR
1218 if (red_shift !== 16) {
1219 Log.Warn("Server native red-shift is not 16");
1220 }
b1dee947 1221
6d6f0db0
SR
1222 if (blue_shift !== 0) {
1223 Log.Warn("Server native blue-shift is not 0");
1224 }
b1dee947 1225
6d6f0db0 1226 // we're past the point where we could backtrack, so it's safe to call this
2b5f94fa
JD
1227 this.dispatchEvent(new CustomEvent(
1228 "desktopname",
1229 { detail: { name: this._fb_name } }));
b1dee947 1230
91d5c625 1231 this._resize(width, height);
b1dee947 1232
747b4623
PO
1233 if (!this._viewOnly) { this._keyboard.grab(); }
1234 if (!this._viewOnly) { this._mouse.grab(); }
b1dee947 1235
5a5f5ada
PO
1236 this._fb_depth = 24;
1237
1238 if (this._fb_name === "Intel(r) AMT KVM") {
1239 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1240 this._fb_depth = 8;
1241 }
1242
1243 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
49a81837 1244 this._sendEncodings();
6d6f0db0
SR
1245 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1246
1247 this._timing.fbu_rt_start = (new Date()).getTime();
1248 this._timing.pixels = 0;
1249
cd74793b
PO
1250 // Cursor will be server side until the server decides to honor
1251 // our request and send over the cursor image
1252 this._display.disableLocalCursor();
1253
6d6f0db0
SR
1254 this._updateConnectionState('connected');
1255 return true;
1256 },
1257
49a81837 1258 _sendEncodings: function () {
2b5f94fa 1259 const encs = [];
49a81837
PO
1260
1261 // In preference order
1262 encs.push(encodings.encodingCopyRect);
5a5f5ada
PO
1263 // Only supported with full depth support
1264 if (this._fb_depth == 24) {
1265 encs.push(encodings.encodingTight);
2c813a33 1266 encs.push(encodings.encodingTightPNG);
5a5f5ada
PO
1267 encs.push(encodings.encodingHextile);
1268 encs.push(encodings.encodingRRE);
1269 }
49a81837
PO
1270 encs.push(encodings.encodingRaw);
1271
1272 // Psuedo-encoding settings
49a81837
PO
1273 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1274 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1275
1276 encs.push(encodings.pseudoEncodingDesktopSize);
1277 encs.push(encodings.pseudoEncodingLastRect);
1278 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1279 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1280 encs.push(encodings.pseudoEncodingXvp);
1281 encs.push(encodings.pseudoEncodingFence);
1282 encs.push(encodings.pseudoEncodingContinuousUpdates);
1283
59ef2916 1284 if (supportsCursorURIs() &&
8d1f0a3d 1285 !isTouchDevice && this._fb_depth == 24) {
49a81837
PO
1286 encs.push(encodings.pseudoEncodingCursor);
1287 }
1288
1289 RFB.messages.clientEncodings(this._sock, encs);
1290 },
1291
6d6f0db0
SR
1292 /* RFB protocol initialization states:
1293 * ProtocolVersion
1294 * Security
1295 * Authentication
1296 * SecurityResult
1297 * ClientInitialization - not triggered by server message
1298 * ServerInitialization
1299 */
1300 _init_msg: function () {
1301 switch (this._rfb_init_state) {
1302 case 'ProtocolVersion':
1303 return this._negotiate_protocol_version();
1304
1305 case 'Security':
1306 return this._negotiate_security();
1307
1308 case 'Authentication':
1309 return this._negotiate_authentication();
1310
1311 case 'SecurityResult':
1312 return this._handle_security_result();
1313
1314 case 'ClientInitialisation':
1315 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1316 this._rfb_init_state = 'ServerInitialisation';
1317 return true;
b1dee947 1318
6d6f0db0
SR
1319 case 'ServerInitialisation':
1320 return this._negotiate_server_init();
b1dee947 1321
6d6f0db0 1322 default:
d472f3f1
SM
1323 return this._fail("Unknown init state (state: " +
1324 this._rfb_init_state + ")");
6d6f0db0
SR
1325 }
1326 },
b1dee947 1327
6d6f0db0
SR
1328 _handle_set_colour_map_msg: function () {
1329 Log.Debug("SetColorMapEntries");
b1dee947 1330
d472f3f1 1331 return this._fail("Unexpected SetColorMapEntries message");
6d6f0db0 1332 },
b1dee947 1333
6d6f0db0
SR
1334 _handle_server_cut_text: function () {
1335 Log.Debug("ServerCutText");
b1dee947 1336
6d6f0db0
SR
1337 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1338 this._sock.rQskipBytes(3); // Padding
2b5f94fa 1339 const length = this._sock.rQshift32();
6d6f0db0 1340 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
b1dee947 1341
2b5f94fa 1342 const text = this._sock.rQshiftStr(length);
b4ff032e 1343
747b4623 1344 if (this._viewOnly) { return true; }
b4ff032e 1345
2b5f94fa
JD
1346 this.dispatchEvent(new CustomEvent(
1347 "clipboard",
1348 { detail: { text: text } }));
b1dee947 1349
6d6f0db0
SR
1350 return true;
1351 },
b1dee947 1352
6d6f0db0
SR
1353 _handle_server_fence_msg: function() {
1354 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1355 this._sock.rQskipBytes(3); // Padding
2b5f94fa
JD
1356 let flags = this._sock.rQshift32();
1357 let length = this._sock.rQshift8();
b1dee947 1358
6d6f0db0 1359 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
b1dee947 1360
6d6f0db0
SR
1361 if (length > 64) {
1362 Log.Warn("Bad payload length (" + length + ") in fence response");
1363 length = 64;
1364 }
4e0c36dd 1365
2b5f94fa 1366 const payload = this._sock.rQshiftStr(length);
b1dee947 1367
6d6f0db0 1368 this._supportsFence = true;
b1dee947 1369
6d6f0db0
SR
1370 /*
1371 * Fence flags
1372 *
1373 * (1<<0) - BlockBefore
1374 * (1<<1) - BlockAfter
1375 * (1<<2) - SyncNext
1376 * (1<<31) - Request
1377 */
b1dee947 1378
6d6f0db0 1379 if (!(flags & (1<<31))) {
d472f3f1 1380 return this._fail("Unexpected fence response");
6d6f0db0 1381 }
b1dee947 1382
6d6f0db0
SR
1383 // Filter out unsupported flags
1384 // FIXME: support syncNext
1385 flags &= (1<<0) | (1<<1);
b1dee947 1386
6d6f0db0
SR
1387 // BlockBefore and BlockAfter are automatically handled by
1388 // the fact that we process each incoming message
1389 // synchronuosly.
1390 RFB.messages.clientFence(this._sock, flags, payload);
f78a652e 1391
6d6f0db0
SR
1392 return true;
1393 },
b1dee947 1394
6d6f0db0
SR
1395 _handle_xvp_msg: function () {
1396 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
1397 this._sock.rQskip8(); // Padding
2b5f94fa
JD
1398 const xvp_ver = this._sock.rQshift8();
1399 const xvp_msg = this._sock.rQshift8();
b1dee947 1400
6d6f0db0
SR
1401 switch (xvp_msg) {
1402 case 0: // XVP_FAIL
5b20d338 1403 Log.Error("XVP Operation Failed");
6d6f0db0
SR
1404 break;
1405 case 1: // XVP_INIT
1406 this._rfb_xvp_ver = xvp_ver;
1407 Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
832be262 1408 this._setCapability("power", true);
6d6f0db0
SR
1409 break;
1410 default:
d472f3f1 1411 this._fail("Illegal server XVP message (msg: " + xvp_msg + ")");
6d6f0db0
SR
1412 break;
1413 }
b1dee947 1414
6d6f0db0
SR
1415 return true;
1416 },
3df13262 1417
6d6f0db0 1418 _normal_msg: function () {
2b5f94fa 1419 let msg_type;
6d6f0db0
SR
1420 if (this._FBU.rects > 0) {
1421 msg_type = 0;
1422 } else {
1423 msg_type = this._sock.rQshift8();
1424 }
76a86ff5 1425
2b5f94fa 1426 let first, ret;
6d6f0db0
SR
1427 switch (msg_type) {
1428 case 0: // FramebufferUpdate
2b5f94fa 1429 ret = this._framebufferUpdate();
6d6f0db0
SR
1430 if (ret && !this._enabledContinuousUpdates) {
1431 RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
1432 this._fb_width, this._fb_height);
1433 }
1434 return ret;
3df13262 1435
6d6f0db0
SR
1436 case 1: // SetColorMapEntries
1437 return this._handle_set_colour_map_msg();
1438
1439 case 2: // Bell
1440 Log.Debug("Bell");
2b5f94fa
JD
1441 this.dispatchEvent(new CustomEvent(
1442 "bell",
1443 { detail: {} }));
6d6f0db0
SR
1444 return true;
1445
1446 case 3: // ServerCutText
1447 return this._handle_server_cut_text();
1448
1449 case 150: // EndOfContinuousUpdates
2b5f94fa 1450 first = !this._supportsContinuousUpdates;
6d6f0db0
SR
1451 this._supportsContinuousUpdates = true;
1452 this._enabledContinuousUpdates = false;
1453 if (first) {
1454 this._enabledContinuousUpdates = true;
1455 this._updateContinuousUpdates();
1456 Log.Info("Enabling continuous updates.");
1457 } else {
1458 // FIXME: We need to send a framebufferupdaterequest here
1459 // if we add support for turning off continuous updates
1460 }
1461 return true;
3df13262 1462
6d6f0db0
SR
1463 case 248: // ServerFence
1464 return this._handle_server_fence_msg();
3df13262 1465
6d6f0db0
SR
1466 case 250: // XVP
1467 return this._handle_xvp_msg();
3df13262 1468
6d6f0db0 1469 default:
d472f3f1 1470 this._fail("Unexpected server message (type " + msg_type + ")");
6d6f0db0
SR
1471 Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1472 return true;
1473 }
1474 },
3df13262 1475
6d6f0db0
SR
1476 _onFlush: function() {
1477 this._flushing = false;
1478 // Resume processing
1479 if (this._sock.rQlen() > 0) {
1480 this._handle_message();
1481 }
1482 },
3df13262 1483
6d6f0db0 1484 _framebufferUpdate: function () {
6d6f0db0
SR
1485 if (this._FBU.rects === 0) {
1486 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
b1dee947 1487 this._sock.rQskip8(); // Padding
6d6f0db0
SR
1488 this._FBU.rects = this._sock.rQshift16();
1489 this._FBU.bytes = 0;
1490 this._timing.cur_fbu = 0;
1491 if (this._timing.fbu_rt_start > 0) {
2b5f94fa 1492 const now = (new Date()).getTime();
6d6f0db0 1493 Log.Info("First FBU latency: " + (now - this._timing.fbu_rt_start));
b1dee947
SR
1494 }
1495
6d6f0db0
SR
1496 // Make sure the previous frame is fully rendered first
1497 // to avoid building up an excessive queue
1498 if (this._display.pending()) {
1499 this._flushing = true;
1500 this._display.flush();
1501 return false;
1502 }
1503 }
b1dee947 1504
6d6f0db0
SR
1505 while (this._FBU.rects > 0) {
1506 if (this._rfb_connection_state !== 'connected') { return false; }
b1dee947 1507
6d6f0db0
SR
1508 if (this._sock.rQwait("FBU", this._FBU.bytes)) { return false; }
1509 if (this._FBU.bytes === 0) {
1510 if (this._sock.rQwait("rect header", 12)) { return false; }
1511 /* New FramebufferUpdate */
b1dee947 1512
2b5f94fa 1513 const hdr = this._sock.rQshiftBytes(12);
6d6f0db0
SR
1514 this._FBU.x = (hdr[0] << 8) + hdr[1];
1515 this._FBU.y = (hdr[2] << 8) + hdr[3];
1516 this._FBU.width = (hdr[4] << 8) + hdr[5];
1517 this._FBU.height = (hdr[6] << 8) + hdr[7];
1518 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1519 (hdr[10] << 8) + hdr[11], 10);
b1dee947 1520
49a81837 1521 if (!this._encHandlers[this._FBU.encoding]) {
d472f3f1
SM
1522 this._fail("Unsupported encoding (encoding: " +
1523 this._FBU.encoding + ")");
6d6f0db0
SR
1524 return false;
1525 }
1526 }
b1dee947 1527
6d6f0db0 1528 this._timing.last_fbu = (new Date()).getTime();
76a86ff5 1529
2b5f94fa 1530 const ret = this._encHandlers[this._FBU.encoding]();
3df13262 1531
2b5f94fa 1532 const now = (new Date()).getTime();
6d6f0db0 1533 this._timing.cur_fbu += (now - this._timing.last_fbu);
b1dee947 1534
6d6f0db0 1535 if (ret) {
c3386227
PO
1536 if (!(this._FBU.encoding in this._encStats)) {
1537 this._encStats[this._FBU.encoding] = [0, 0];
1538 }
6d6f0db0
SR
1539 this._encStats[this._FBU.encoding][0]++;
1540 this._encStats[this._FBU.encoding][1]++;
1541 this._timing.pixels += this._FBU.width * this._FBU.height;
b1dee947 1542 }
b1dee947 1543
6d6f0db0
SR
1544 if (this._timing.pixels >= (this._fb_width * this._fb_height)) {
1545 if ((this._FBU.width === this._fb_width && this._FBU.height === this._fb_height) ||
1546 this._timing.fbu_rt_start > 0) {
1547 this._timing.full_fbu_total += this._timing.cur_fbu;
1548 this._timing.full_fbu_cnt++;
1549 Log.Info("Timing of full FBU, curr: " +
1550 this._timing.cur_fbu + ", total: " +
1551 this._timing.full_fbu_total + ", cnt: " +
1552 this._timing.full_fbu_cnt + ", avg: " +
1553 (this._timing.full_fbu_total / this._timing.full_fbu_cnt));
b1dee947 1554 }
d9ca5e5b 1555
6d6f0db0 1556 if (this._timing.fbu_rt_start > 0) {
2b5f94fa 1557 const fbu_rt_diff = now - this._timing.fbu_rt_start;
6d6f0db0
SR
1558 this._timing.fbu_rt_total += fbu_rt_diff;
1559 this._timing.fbu_rt_cnt++;
1560 Log.Info("full FBU round-trip, cur: " +
1561 fbu_rt_diff + ", total: " +
1562 this._timing.fbu_rt_total + ", cnt: " +
1563 this._timing.fbu_rt_cnt + ", avg: " +
1564 (this._timing.fbu_rt_total / this._timing.fbu_rt_cnt));
1565 this._timing.fbu_rt_start = 0;
d9ca5e5b 1566 }
b1dee947
SR
1567 }
1568
6d6f0db0
SR
1569 if (!ret) { return ret; } // need more data
1570 }
b1dee947 1571
6d6f0db0 1572 this._display.flip();
b1dee947 1573
6d6f0db0
SR
1574 return true; // We finished this FBU
1575 },
b1dee947 1576
6d6f0db0
SR
1577 _updateContinuousUpdates: function() {
1578 if (!this._enabledContinuousUpdates) { return; }
b1dee947 1579
6d6f0db0
SR
1580 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1581 this._fb_width, this._fb_height);
91d5c625
PO
1582 },
1583
1584 _resize: function(width, height) {
1585 this._fb_width = width;
1586 this._fb_height = height;
1587
1588 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
1589
1590 this._display.resize(this._fb_width, this._fb_height);
e89eef94 1591
9b84f516
PO
1592 // Adjust the visible viewport based on the new dimensions
1593 this._updateClip();
1594 this._updateScale();
91d5c625
PO
1595
1596 this._timing.fbu_rt_start = (new Date()).getTime();
1597 this._updateContinuousUpdates();
cd523e8f 1598 },
8db09746 1599
cd523e8f
PO
1600 _xvpOp: function (ver, op) {
1601 if (this._rfb_xvp_ver < ver) { return; }
1602 Log.Info("Sending XVP operation " + op + " (version " + ver + ")");
1603 RFB.messages.xvpOp(this._sock, ver, op);
1604 },
6d6f0db0 1605};
76a86ff5 1606
e89eef94 1607Object.assign(RFB.prototype, EventTargetMixin);
76a86ff5 1608
6d6f0db0
SR
1609// Class Methods
1610RFB.messages = {
1611 keyEvent: function (sock, keysym, down) {
2b5f94fa
JD
1612 const buff = sock._sQ;
1613 const offset = sock._sQlen;
8db09746 1614
6d6f0db0
SR
1615 buff[offset] = 4; // msg-type
1616 buff[offset + 1] = down;
b1dee947 1617
6d6f0db0
SR
1618 buff[offset + 2] = 0;
1619 buff[offset + 3] = 0;
fb49f91b 1620
6d6f0db0
SR
1621 buff[offset + 4] = (keysym >> 24);
1622 buff[offset + 5] = (keysym >> 16);
1623 buff[offset + 6] = (keysym >> 8);
1624 buff[offset + 7] = keysym;
b1dee947 1625
6d6f0db0
SR
1626 sock._sQlen += 8;
1627 sock.flush();
1628 },
ef1e8bab 1629
6d6f0db0
SR
1630 QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) {
1631 function getRFBkeycode(xt_scancode) {
2b5f94fa
JD
1632 const upperByte = (keycode >> 8);
1633 const lowerByte = (keycode & 0x00ff);
6d6f0db0 1634 if (upperByte === 0xe0 && lowerByte < 0x7f) {
2b5f94fa 1635 return lowerByte | 0x80;
ef1e8bab 1636 }
6d6f0db0 1637 return xt_scancode;
ef1e8bab 1638 }
b1dee947 1639
2b5f94fa
JD
1640 const buff = sock._sQ;
1641 const offset = sock._sQlen;
8f06673a 1642
6d6f0db0
SR
1643 buff[offset] = 255; // msg-type
1644 buff[offset + 1] = 0; // sub msg-type
8f06673a 1645
6d6f0db0
SR
1646 buff[offset + 2] = (down >> 8);
1647 buff[offset + 3] = down;
8f06673a 1648
6d6f0db0
SR
1649 buff[offset + 4] = (keysym >> 24);
1650 buff[offset + 5] = (keysym >> 16);
1651 buff[offset + 6] = (keysym >> 8);
1652 buff[offset + 7] = keysym;
8f06673a 1653
2b5f94fa 1654 const RFBkeycode = getRFBkeycode(keycode);
8f06673a 1655
6d6f0db0
SR
1656 buff[offset + 8] = (RFBkeycode >> 24);
1657 buff[offset + 9] = (RFBkeycode >> 16);
1658 buff[offset + 10] = (RFBkeycode >> 8);
1659 buff[offset + 11] = RFBkeycode;
8f06673a 1660
6d6f0db0
SR
1661 sock._sQlen += 12;
1662 sock.flush();
1663 },
8f06673a 1664
6d6f0db0 1665 pointerEvent: function (sock, x, y, mask) {
2b5f94fa
JD
1666 const buff = sock._sQ;
1667 const offset = sock._sQlen;
8f06673a 1668
6d6f0db0 1669 buff[offset] = 5; // msg-type
9ff86fb7 1670
6d6f0db0 1671 buff[offset + 1] = mask;
9ff86fb7 1672
6d6f0db0
SR
1673 buff[offset + 2] = x >> 8;
1674 buff[offset + 3] = x;
9ff86fb7 1675
6d6f0db0
SR
1676 buff[offset + 4] = y >> 8;
1677 buff[offset + 5] = y;
9ff86fb7 1678
6d6f0db0
SR
1679 sock._sQlen += 6;
1680 sock.flush();
1681 },
9ff86fb7 1682
6d6f0db0
SR
1683 // TODO(directxman12): make this unicode compatible?
1684 clientCutText: function (sock, text) {
2b5f94fa
JD
1685 const buff = sock._sQ;
1686 const offset = sock._sQlen;
b1dee947 1687
6d6f0db0 1688 buff[offset] = 6; // msg-type
9ff86fb7 1689
6d6f0db0
SR
1690 buff[offset + 1] = 0; // padding
1691 buff[offset + 2] = 0; // padding
1692 buff[offset + 3] = 0; // padding
9ff86fb7 1693
2b5f94fa 1694 const length = text.length;
9ff86fb7 1695
2bb8b28d
SM
1696 buff[offset + 4] = length >> 24;
1697 buff[offset + 5] = length >> 16;
1698 buff[offset + 6] = length >> 8;
1699 buff[offset + 7] = length;
9ff86fb7 1700
2bb8b28d 1701 sock._sQlen += 8;
9ff86fb7 1702
2bb8b28d
SM
1703 // We have to keep track of from where in the text we begin creating the
1704 // buffer for the flush in the next iteration.
1705 let textOffset = 0;
1706
1707 let remaining = length;
1708 while (remaining > 0) {
1709
2b5f94fa 1710 const flushSize = Math.min(remaining, (sock._sQbufferSize - sock._sQlen));
2bb8b28d
SM
1711 if (flushSize <= 0) {
1712 this._fail("Clipboard contents could not be sent");
1713 break;
1714 }
1715
2bb8b28d 1716 for (let i = 0; i < flushSize; i++) {
2b5f94fa 1717 buff[sock._sQlen + i] = text.charCodeAt(textOffset + i);
2bb8b28d
SM
1718 }
1719
1720 sock._sQlen += flushSize;
1721 sock.flush();
1722
1723 remaining -= flushSize;
1724 textOffset += flushSize;
1725 }
6d6f0db0
SR
1726 },
1727
1728 setDesktopSize: function (sock, width, height, id, flags) {
2b5f94fa
JD
1729 const buff = sock._sQ;
1730 const offset = sock._sQlen;
6d6f0db0
SR
1731
1732 buff[offset] = 251; // msg-type
1733 buff[offset + 1] = 0; // padding
1734 buff[offset + 2] = width >> 8; // width
1735 buff[offset + 3] = width;
1736 buff[offset + 4] = height >> 8; // height
1737 buff[offset + 5] = height;
1738
1739 buff[offset + 6] = 1; // number-of-screens
1740 buff[offset + 7] = 0; // padding
1741
1742 // screen array
1743 buff[offset + 8] = id >> 24; // id
1744 buff[offset + 9] = id >> 16;
1745 buff[offset + 10] = id >> 8;
1746 buff[offset + 11] = id;
1747 buff[offset + 12] = 0; // x-position
1748 buff[offset + 13] = 0;
1749 buff[offset + 14] = 0; // y-position
1750 buff[offset + 15] = 0;
1751 buff[offset + 16] = width >> 8; // width
1752 buff[offset + 17] = width;
1753 buff[offset + 18] = height >> 8; // height
1754 buff[offset + 19] = height;
1755 buff[offset + 20] = flags >> 24; // flags
1756 buff[offset + 21] = flags >> 16;
1757 buff[offset + 22] = flags >> 8;
1758 buff[offset + 23] = flags;
1759
1760 sock._sQlen += 24;
1761 sock.flush();
1762 },
1763
1764 clientFence: function (sock, flags, payload) {
2b5f94fa
JD
1765 const buff = sock._sQ;
1766 const offset = sock._sQlen;
6d6f0db0
SR
1767
1768 buff[offset] = 248; // msg-type
1769
1770 buff[offset + 1] = 0; // padding
1771 buff[offset + 2] = 0; // padding
1772 buff[offset + 3] = 0; // padding
1773
1774 buff[offset + 4] = flags >> 24; // flags
1775 buff[offset + 5] = flags >> 16;
1776 buff[offset + 6] = flags >> 8;
1777 buff[offset + 7] = flags;
1778
2b5f94fa 1779 const n = payload.length;
6d6f0db0
SR
1780
1781 buff[offset + 8] = n; // length
1782
2b5f94fa 1783 for (let i = 0; i < n; i++) {
6d6f0db0
SR
1784 buff[offset + 9 + i] = payload.charCodeAt(i);
1785 }
a7a89626 1786
6d6f0db0
SR
1787 sock._sQlen += 9 + n;
1788 sock.flush();
1789 },
3df13262 1790
6d6f0db0 1791 enableContinuousUpdates: function (sock, enable, x, y, width, height) {
2b5f94fa
JD
1792 const buff = sock._sQ;
1793 const offset = sock._sQlen;
3df13262 1794
6d6f0db0
SR
1795 buff[offset] = 150; // msg-type
1796 buff[offset + 1] = enable; // enable-flag
76a86ff5 1797
6d6f0db0
SR
1798 buff[offset + 2] = x >> 8; // x
1799 buff[offset + 3] = x;
1800 buff[offset + 4] = y >> 8; // y
1801 buff[offset + 5] = y;
1802 buff[offset + 6] = width >> 8; // width
1803 buff[offset + 7] = width;
1804 buff[offset + 8] = height >> 8; // height
1805 buff[offset + 9] = height;
76a86ff5 1806
6d6f0db0
SR
1807 sock._sQlen += 10;
1808 sock.flush();
1809 },
76a86ff5 1810
5a5f5ada 1811 pixelFormat: function (sock, depth, true_color) {
2b5f94fa
JD
1812 const buff = sock._sQ;
1813 const offset = sock._sQlen;
ae116051 1814
2b5f94fa 1815 let bpp;
5a5f5ada
PO
1816
1817 if (depth > 16) {
1818 bpp = 32;
1819 } else if (depth > 8) {
1820 bpp = 16;
1821 } else {
1822 bpp = 8;
1823 }
1824
2b5f94fa 1825 const bits = Math.floor(depth/3);
5a5f5ada 1826
6d6f0db0 1827 buff[offset] = 0; // msg-type
9ff86fb7 1828
6d6f0db0
SR
1829 buff[offset + 1] = 0; // padding
1830 buff[offset + 2] = 0; // padding
1831 buff[offset + 3] = 0; // padding
9ff86fb7 1832
5a5f5ada
PO
1833 buff[offset + 4] = bpp; // bits-per-pixel
1834 buff[offset + 5] = depth; // depth
6d6f0db0
SR
1835 buff[offset + 6] = 0; // little-endian
1836 buff[offset + 7] = true_color ? 1 : 0; // true-color
9ff86fb7 1837
6d6f0db0 1838 buff[offset + 8] = 0; // red-max
5a5f5ada 1839 buff[offset + 9] = (1 << bits) - 1; // red-max
9ff86fb7 1840
6d6f0db0 1841 buff[offset + 10] = 0; // green-max
5a5f5ada 1842 buff[offset + 11] = (1 << bits) - 1; // green-max
9ff86fb7 1843
6d6f0db0 1844 buff[offset + 12] = 0; // blue-max
5a5f5ada 1845 buff[offset + 13] = (1 << bits) - 1; // blue-max
9ff86fb7 1846
5a5f5ada
PO
1847 buff[offset + 14] = bits * 2; // red-shift
1848 buff[offset + 15] = bits * 1; // green-shift
1849 buff[offset + 16] = bits * 0; // blue-shift
9ff86fb7 1850
6d6f0db0
SR
1851 buff[offset + 17] = 0; // padding
1852 buff[offset + 18] = 0; // padding
1853 buff[offset + 19] = 0; // padding
9ff86fb7 1854
6d6f0db0
SR
1855 sock._sQlen += 20;
1856 sock.flush();
1857 },
9ff86fb7 1858
49a81837 1859 clientEncodings: function (sock, encodings) {
2b5f94fa
JD
1860 const buff = sock._sQ;
1861 const offset = sock._sQlen;
b1dee947 1862
6d6f0db0
SR
1863 buff[offset] = 2; // msg-type
1864 buff[offset + 1] = 0; // padding
b1dee947 1865
49a81837
PO
1866 buff[offset + 2] = encodings.length >> 8;
1867 buff[offset + 3] = encodings.length;
9ff86fb7 1868
2b5f94fa
JD
1869 let j = offset + 4;
1870 for (let i = 0; i < encodings.length; i++) {
1871 const enc = encodings[i];
49a81837
PO
1872 buff[j] = enc >> 24;
1873 buff[j + 1] = enc >> 16;
1874 buff[j + 2] = enc >> 8;
1875 buff[j + 3] = enc;
a7a89626 1876
49a81837
PO
1877 j += 4;
1878 }
a7a89626 1879
6d6f0db0
SR
1880 sock._sQlen += j - offset;
1881 sock.flush();
1882 },
a679a97d 1883
6d6f0db0 1884 fbUpdateRequest: function (sock, incremental, x, y, w, h) {
2b5f94fa
JD
1885 const buff = sock._sQ;
1886 const offset = sock._sQlen;
9ff86fb7 1887
6d6f0db0
SR
1888 if (typeof(x) === "undefined") { x = 0; }
1889 if (typeof(y) === "undefined") { y = 0; }
b1dee947 1890
6d6f0db0
SR
1891 buff[offset] = 3; // msg-type
1892 buff[offset + 1] = incremental ? 1 : 0;
9ff86fb7 1893
6d6f0db0
SR
1894 buff[offset + 2] = (x >> 8) & 0xFF;
1895 buff[offset + 3] = x & 0xFF;
9ff86fb7 1896
6d6f0db0
SR
1897 buff[offset + 4] = (y >> 8) & 0xFF;
1898 buff[offset + 5] = y & 0xFF;
9ff86fb7 1899
6d6f0db0
SR
1900 buff[offset + 6] = (w >> 8) & 0xFF;
1901 buff[offset + 7] = w & 0xFF;
9ff86fb7 1902
6d6f0db0
SR
1903 buff[offset + 8] = (h >> 8) & 0xFF;
1904 buff[offset + 9] = h & 0xFF;
b1dee947 1905
6d6f0db0
SR
1906 sock._sQlen += 10;
1907 sock.flush();
85b35fc0
PO
1908 },
1909
1910 xvpOp: function (sock, ver, op) {
2b5f94fa
JD
1911 const buff = sock._sQ;
1912 const offset = sock._sQlen;
85b35fc0
PO
1913
1914 buff[offset] = 250; // msg-type
1915 buff[offset + 1] = 0; // padding
1916
1917 buff[offset + 2] = ver;
1918 buff[offset + 3] = op;
1919
1920 sock._sQlen += 4;
1921 sock.flush();
1922 },
6d6f0db0 1923};
b1dee947 1924
6d6f0db0 1925RFB.genDES = function (password, challenge) {
2b5f94fa
JD
1926 const passwd = [];
1927 for (let i = 0; i < password.length; i++) {
6d6f0db0
SR
1928 passwd.push(password.charCodeAt(i));
1929 }
1930 return (new DES(passwd)).encrypt(challenge);
1931};
b1dee947 1932
6d6f0db0
SR
1933RFB.encodingHandlers = {
1934 RAW: function () {
1935 if (this._FBU.lines === 0) {
1936 this._FBU.lines = this._FBU.height;
1937 }
a7a89626 1938
2b5f94fa 1939 const pixelSize = this._fb_depth == 8 ? 1 : 4;
5a5f5ada 1940 this._FBU.bytes = this._FBU.width * pixelSize; // at least a line
6d6f0db0 1941 if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; }
2b5f94fa
JD
1942 const cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines);
1943 const curr_height = Math.min(this._FBU.lines,
5a5f5ada 1944 Math.floor(this._sock.rQlen() / (this._FBU.width * pixelSize)));
2b5f94fa
JD
1945 let data = this._sock.get_rQ();
1946 let index = this._sock.get_rQi();
5a5f5ada 1947 if (this._fb_depth == 8) {
2b5f94fa
JD
1948 const pixels = this._FBU.width * curr_height
1949 const newdata = new Uint8Array(pixels * 4);
1950 for (let i = 0; i < pixels; i++) {
5a5f5ada
PO
1951 newdata[i * 4 + 0] = ((data[index + i] >> 0) & 0x3) * 255 / 3;
1952 newdata[i * 4 + 1] = ((data[index + i] >> 2) & 0x3) * 255 / 3;
1953 newdata[i * 4 + 2] = ((data[index + i] >> 4) & 0x3) * 255 / 3;
1954 newdata[i * 4 + 4] = 0;
1955 }
1956 data = newdata;
1957 index = 0;
1958 }
6d6f0db0 1959 this._display.blitImage(this._FBU.x, cur_y, this._FBU.width,
5a5f5ada
PO
1960 curr_height, data, index);
1961 this._sock.rQskipBytes(this._FBU.width * curr_height * pixelSize);
6d6f0db0
SR
1962 this._FBU.lines -= curr_height;
1963
1964 if (this._FBU.lines > 0) {
5a5f5ada 1965 this._FBU.bytes = this._FBU.width * pixelSize; // At least another line
6d6f0db0
SR
1966 } else {
1967 this._FBU.rects--;
1968 this._FBU.bytes = 0;
1969 }
b1dee947 1970
6d6f0db0
SR
1971 return true;
1972 },
1973
1974 COPYRECT: function () {
1975 this._FBU.bytes = 4;
1976 if (this._sock.rQwait("COPYRECT", 4)) { return false; }
1977 this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
1978 this._FBU.x, this._FBU.y, this._FBU.width,
1979 this._FBU.height);
1980
1981 this._FBU.rects--;
1982 this._FBU.bytes = 0;
1983 return true;
1984 },
1985
1986 RRE: function () {
2b5f94fa 1987 let color;
6d6f0db0 1988 if (this._FBU.subrects === 0) {
26586b9d
PO
1989 this._FBU.bytes = 4 + 4;
1990 if (this._sock.rQwait("RRE", 4 + 4)) { return false; }
6d6f0db0 1991 this._FBU.subrects = this._sock.rQshift32();
26586b9d 1992 color = this._sock.rQshiftBytes(4); // Background
6d6f0db0
SR
1993 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, color);
1994 }
b1dee947 1995
26586b9d
PO
1996 while (this._FBU.subrects > 0 && this._sock.rQlen() >= (4 + 8)) {
1997 color = this._sock.rQshiftBytes(4);
2b5f94fa
JD
1998 const x = this._sock.rQshift16();
1999 const y = this._sock.rQshift16();
2000 const width = this._sock.rQshift16();
2001 const height = this._sock.rQshift16();
6d6f0db0
SR
2002 this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color);
2003 this._FBU.subrects--;
2004 }
f00193e0 2005
6d6f0db0 2006 if (this._FBU.subrects > 0) {
2b5f94fa 2007 const chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects);
26586b9d 2008 this._FBU.bytes = (4 + 8) * chunk;
6d6f0db0 2009 } else {
b1dee947
SR
2010 this._FBU.rects--;
2011 this._FBU.bytes = 0;
6d6f0db0 2012 }
b1dee947 2013
6d6f0db0
SR
2014 return true;
2015 },
b1dee947 2016
6d6f0db0 2017 HEXTILE: function () {
2b5f94fa
JD
2018 const rQ = this._sock.get_rQ();
2019 let rQi = this._sock.get_rQi();
b1dee947 2020
6d6f0db0
SR
2021 if (this._FBU.tiles === 0) {
2022 this._FBU.tiles_x = Math.ceil(this._FBU.width / 16);
2023 this._FBU.tiles_y = Math.ceil(this._FBU.height / 16);
2024 this._FBU.total_tiles = this._FBU.tiles_x * this._FBU.tiles_y;
2025 this._FBU.tiles = this._FBU.total_tiles;
2026 }
b1dee947 2027
6d6f0db0
SR
2028 while (this._FBU.tiles > 0) {
2029 this._FBU.bytes = 1;
2030 if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; }
2b5f94fa 2031 const subencoding = rQ[rQi]; // Peek
6d6f0db0 2032 if (subencoding > 30) { // Raw
d472f3f1
SM
2033 this._fail("Illegal hextile subencoding (subencoding: " +
2034 subencoding + ")");
6d6f0db0 2035 return false;
b1dee947
SR
2036 }
2037
2b5f94fa
JD
2038 let subrects = 0;
2039 const curr_tile = this._FBU.total_tiles - this._FBU.tiles;
2040 const tile_x = curr_tile % this._FBU.tiles_x;
2041 const tile_y = Math.floor(curr_tile / this._FBU.tiles_x);
2042 const x = this._FBU.x + tile_x * 16;
2043 const y = this._FBU.y + tile_y * 16;
2044 const w = Math.min(16, (this._FBU.x + this._FBU.width) - x);
2045 const h = Math.min(16, (this._FBU.y + this._FBU.height) - y);
b1dee947 2046
6d6f0db0
SR
2047 // Figure out how much we are expecting
2048 if (subencoding & 0x01) { // Raw
26586b9d 2049 this._FBU.bytes += w * h * 4;
6d6f0db0
SR
2050 } else {
2051 if (subencoding & 0x02) { // Background
26586b9d 2052 this._FBU.bytes += 4;
6d6f0db0
SR
2053 }
2054 if (subencoding & 0x04) { // Foreground
26586b9d 2055 this._FBU.bytes += 4;
6d6f0db0
SR
2056 }
2057 if (subencoding & 0x08) { // AnySubrects
2058 this._FBU.bytes++; // Since we aren't shifting it off
2059 if (this._sock.rQwait("hextile subrects header", this._FBU.bytes)) { return false; }
2060 subrects = rQ[rQi + this._FBU.bytes - 1]; // Peek
2061 if (subencoding & 0x10) { // SubrectsColoured
26586b9d 2062 this._FBU.bytes += subrects * (4 + 2);
6d6f0db0
SR
2063 } else {
2064 this._FBU.bytes += subrects * 2;
b1dee947
SR
2065 }
2066 }
6d6f0db0 2067 }
b1dee947 2068
6d6f0db0 2069 if (this._sock.rQwait("hextile", this._FBU.bytes)) { return false; }
b1dee947 2070
6d6f0db0
SR
2071 // We know the encoding and have a whole tile
2072 this._FBU.subencoding = rQ[rQi];
2073 rQi++;
2074 if (this._FBU.subencoding === 0) {
2075 if (this._FBU.lastsubencoding & 0x01) {
2076 // Weird: ignore blanks are RAW
2077 Log.Debug(" Ignoring blank after RAW");
b1dee947 2078 } else {
6d6f0db0
SR
2079 this._display.fillRect(x, y, w, h, this._FBU.background);
2080 }
2081 } else if (this._FBU.subencoding & 0x01) { // Raw
2082 this._display.blitImage(x, y, w, h, rQ, rQi);
2083 rQi += this._FBU.bytes - 1;
2084 } else {
2085 if (this._FBU.subencoding & 0x02) { // Background
26586b9d
PO
2086 this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
2087 rQi += 4;
6d6f0db0
SR
2088 }
2089 if (this._FBU.subencoding & 0x04) { // Foreground
26586b9d
PO
2090 this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
2091 rQi += 4;
6d6f0db0 2092 }
b1dee947 2093
6d6f0db0
SR
2094 this._display.startTile(x, y, w, h, this._FBU.background);
2095 if (this._FBU.subencoding & 0x08) { // AnySubrects
2096 subrects = rQ[rQi];
2097 rQi++;
b1dee947 2098
2b5f94fa
JD
2099 for (let s = 0; s < subrects; s++) {
2100 let color;
6d6f0db0 2101 if (this._FBU.subencoding & 0x10) { // SubrectsColoured
26586b9d
PO
2102 color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
2103 rQi += 4;
6d6f0db0
SR
2104 } else {
2105 color = this._FBU.foreground;
2106 }
2b5f94fa 2107 const xy = rQ[rQi];
6d6f0db0 2108 rQi++;
2b5f94fa
JD
2109 const sx = (xy >> 4);
2110 const sy = (xy & 0x0f);
a7a89626 2111
2b5f94fa 2112 const wh = rQ[rQi];
6d6f0db0 2113 rQi++;
2b5f94fa
JD
2114 const sw = (wh >> 4) + 1;
2115 const sh = (wh & 0x0f) + 1;
a7a89626 2116
6d6f0db0 2117 this._display.subTile(sx, sy, sw, sh, color);
b1dee947 2118 }
a7a89626 2119 }
6d6f0db0 2120 this._display.finishTile();
a7a89626 2121 }
6d6f0db0
SR
2122 this._sock.set_rQi(rQi);
2123 this._FBU.lastsubencoding = this._FBU.subencoding;
2124 this._FBU.bytes = 0;
2125 this._FBU.tiles--;
2126 }
d065cad9 2127
6d6f0db0
SR
2128 if (this._FBU.tiles === 0) {
2129 this._FBU.rects--;
2130 }
b1dee947 2131
6d6f0db0
SR
2132 return true;
2133 },
b1dee947 2134
5bdcf5d3 2135 TIGHT: function (isTightPNG) {
6d6f0db0
SR
2136 this._FBU.bytes = 1; // compression-control byte
2137 if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; }
2138
2b5f94fa
JD
2139 let resetStreams = 0;
2140 let streamId = -1;
2141 const decompress = function (data, expected) {
2142 for (let i = 0; i < 4; i++) {
6d6f0db0
SR
2143 if ((resetStreams >> i) & 1) {
2144 this._FBU.zlibs[i].reset();
2145 Log.Info("Reset zlib stream " + i);
b1dee947 2146 }
6d6f0db0 2147 }
de84e098 2148
2b5f94fa
JD
2149 //const uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2150 const uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected);
6d6f0db0
SR
2151 /*if (uncompressed.status !== 0) {
2152 Log.Error("Invalid data in zlib stream");
2153 }*/
2154
2155 //return uncompressed.data;
2156 return uncompressed;
2157 }.bind(this);
2158
2b5f94fa 2159 const indexedToRGBX2Color = function (data, palette, width, height) {
6d6f0db0
SR
2160 // Convert indexed (palette based) image data to RGB
2161 // TODO: reduce number of calculations inside loop
2b5f94fa
JD
2162 const dest = this._destBuff;
2163 const w = Math.floor((width + 7) / 8);
2164 const w1 = Math.floor(width / 8);
2165
2166 /*for (let y = 0; y < height; y++) {
2167 let b, x, dp, sp;
2168 const yoffset = y * width;
2169 const ybitoffset = y * w;
2170 let xoffset, targetbyte;
6d6f0db0 2171 for (x = 0; x < w1; x++) {
d1800d09
SR
2172 xoffset = yoffset + x * 8;
2173 targetbyte = data[ybitoffset + x];
6d6f0db0 2174 for (b = 7; b >= 0; b--) {
d1800d09
SR
2175 dp = (xoffset + 7 - b) * 3;
2176 sp = (targetbyte >> b & 1) * 3;
2177 dest[dp] = palette[sp];
2178 dest[dp + 1] = palette[sp + 1];
2179 dest[dp + 2] = palette[sp + 2];
2180 }
6d6f0db0
SR
2181 }
2182
2183 xoffset = yoffset + x * 8;
2184 targetbyte = data[ybitoffset + x];
2185 for (b = 7; b >= 8 - width % 8; b--) {
2186 dp = (xoffset + 7 - b) * 3;
2187 sp = (targetbyte >> b & 1) * 3;
2188 dest[dp] = palette[sp];
2189 dest[dp + 1] = palette[sp + 1];
2190 dest[dp + 2] = palette[sp + 2];
2191 }
2192 }*/
d1800d09 2193
2b5f94fa
JD
2194 for (let y = 0; y < height; y++) {
2195 let dp, sp, x;
6d6f0db0 2196 for (x = 0; x < w1; x++) {
2b5f94fa 2197 for (let b = 7; b >= 0; b--) {
d1800d09
SR
2198 dp = (y * width + x * 8 + 7 - b) * 4;
2199 sp = (data[y * w + x] >> b & 1) * 3;
2200 dest[dp] = palette[sp];
2201 dest[dp + 1] = palette[sp + 1];
2202 dest[dp + 2] = palette[sp + 2];
2203 dest[dp + 3] = 255;
e16ad2fd
JM
2204 }
2205 }
b1dee947 2206
2b5f94fa 2207 for (let b = 7; b >= 8 - width % 8; b--) {
6d6f0db0
SR
2208 dp = (y * width + x * 8 + 7 - b) * 4;
2209 sp = (data[y * w + x] >> b & 1) * 3;
2210 dest[dp] = palette[sp];
2211 dest[dp + 1] = palette[sp + 1];
2212 dest[dp + 2] = palette[sp + 2];
2213 dest[dp + 3] = 255;
d1800d09 2214 }
6d6f0db0 2215 }
d1800d09 2216
6d6f0db0
SR
2217 return dest;
2218 }.bind(this);
2219
2b5f94fa 2220 const indexedToRGBX = function (data, palette, width, height) {
6d6f0db0 2221 // Convert indexed (palette based) image data to RGB
2b5f94fa
JD
2222 const dest = this._destBuff;
2223 const total = width * height * 4;
2224 for (let i = 0, j = 0; i < total; i += 4, j++) {
2225 const sp = data[j] * 3;
6d6f0db0
SR
2226 dest[i] = palette[sp];
2227 dest[i + 1] = palette[sp + 1];
2228 dest[i + 2] = palette[sp + 2];
2229 dest[i + 3] = 255;
2230 }
2231
2232 return dest;
2233 }.bind(this);
2234
2b5f94fa
JD
2235 const rQi = this._sock.get_rQi();
2236 const rQ = this._sock.rQwhole();
2237 let cmode, data;
2238 let cl_header, cl_data;
6d6f0db0 2239
2b5f94fa
JD
2240 const handlePalette = function () {
2241 const numColors = rQ[rQi + 2] + 1;
2242 const paletteSize = numColors * 3;
6d6f0db0
SR
2243 this._FBU.bytes += paletteSize;
2244 if (this._sock.rQwait("TIGHT palette " + cmode, this._FBU.bytes)) { return false; }
2245
2b5f94fa
JD
2246 const bpp = (numColors <= 2) ? 1 : 8;
2247 const rowSize = Math.floor((this._FBU.width * bpp + 7) / 8);
2248 let raw = false;
6d6f0db0
SR
2249 if (rowSize * this._FBU.height < 12) {
2250 raw = true;
2251 cl_header = 0;
2252 cl_data = rowSize * this._FBU.height;
2253 //clength = [0, rowSize * this._FBU.height];
2254 } else {
2255 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2b5f94fa 2256 const cl_offset = rQi + 3 + paletteSize;
6d6f0db0
SR
2257 cl_header = 1;
2258 cl_data = 0;
2259 cl_data += rQ[cl_offset] & 0x7f;
2260 if (rQ[cl_offset] & 0x80) {
2261 cl_header++;
2262 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2263 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2264 cl_header++;
6d6f0db0 2265 cl_data += rQ[cl_offset + 2] << 14;
d1800d09 2266 }
e16ad2fd 2267 }
6d6f0db0
SR
2268 // end inline getTightCLength
2269 }
b1dee947 2270
6d6f0db0
SR
2271 this._FBU.bytes += cl_header + cl_data;
2272 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2273
6d6f0db0
SR
2274 // Shift ctl, filter id, num colors, palette entries, and clength off
2275 this._sock.rQskipBytes(3);
2b5f94fa 2276 //const palette = this._sock.rQshiftBytes(paletteSize);
6d6f0db0
SR
2277 this._sock.rQshiftTo(this._paletteBuff, paletteSize);
2278 this._sock.rQskipBytes(cl_header);
b1dee947 2279
6d6f0db0
SR
2280 if (raw) {
2281 data = this._sock.rQshiftBytes(cl_data);
2282 } else {
2283 data = decompress(this._sock.rQshiftBytes(cl_data), rowSize * this._FBU.height);
2284 }
b1dee947 2285
6d6f0db0 2286 // Convert indexed (palette based) image data to RGB
2b5f94fa 2287 let rgbx;
6d6f0db0
SR
2288 if (numColors == 2) {
2289 rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height);
6d6f0db0
SR
2290 } else {
2291 rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height);
6d6f0db0 2292 }
b1dee947 2293
2b5f94fa
JD
2294 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2295
b1dee947 2296
6d6f0db0
SR
2297 return true;
2298 }.bind(this);
2299
2b5f94fa
JD
2300 const handleCopy = function () {
2301 let raw = false;
2302 const uncompressedSize = this._FBU.width * this._FBU.height * 3;
6d6f0db0
SR
2303 if (uncompressedSize < 12) {
2304 raw = true;
2305 cl_header = 0;
2306 cl_data = uncompressedSize;
2307 } else {
2308 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2b5f94fa 2309 const cl_offset = rQi + 1;
6d6f0db0
SR
2310 cl_header = 1;
2311 cl_data = 0;
2312 cl_data += rQ[cl_offset] & 0x7f;
2313 if (rQ[cl_offset] & 0x80) {
2314 cl_header++;
2315 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2316 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2317 cl_header++;
6d6f0db0 2318 cl_data += rQ[cl_offset + 2] << 14;
d1800d09 2319 }
b1dee947 2320 }
6d6f0db0
SR
2321 // end inline getTightCLength
2322 }
2323 this._FBU.bytes = 1 + cl_header + cl_data;
2324 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2325
6d6f0db0
SR
2326 // Shift ctl, clength off
2327 this._sock.rQshiftBytes(1 + cl_header);
b1dee947 2328
6d6f0db0
SR
2329 if (raw) {
2330 data = this._sock.rQshiftBytes(cl_data);
2331 } else {
2332 data = decompress(this._sock.rQshiftBytes(cl_data), uncompressedSize);
2333 }
b1dee947 2334
6d6f0db0 2335 this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
b1dee947 2336
6d6f0db0
SR
2337 return true;
2338 }.bind(this);
b1dee947 2339
2b5f94fa 2340 let ctl = this._sock.rQpeek8();
b1dee947 2341
6d6f0db0
SR
2342 // Keep tight reset bits
2343 resetStreams = ctl & 0xF;
b1dee947 2344
6d6f0db0
SR
2345 // Figure out filter
2346 ctl = ctl >> 4;
2347 streamId = ctl & 0x3;
b1dee947 2348
6d6f0db0
SR
2349 if (ctl === 0x08) cmode = "fill";
2350 else if (ctl === 0x09) cmode = "jpeg";
2351 else if (ctl === 0x0A) cmode = "png";
2352 else if (ctl & 0x04) cmode = "filter";
2353 else if (ctl < 0x04) cmode = "copy";
d472f3f1
SM
2354 else return this._fail("Illegal tight compression received (ctl: " +
2355 ctl + ")");
b1dee947 2356
5bdcf5d3
PO
2357 if (isTightPNG && (ctl < 0x08)) {
2358 return this._fail("BasicCompression received in TightPNG rect");
2359 }
2360 if (!isTightPNG && (ctl === 0x0A)) {
2361 return this._fail("PNG received in standard Tight rect");
2362 }
2363
6d6f0db0 2364 switch (cmode) {
26586b9d 2365 // fill use depth because TPIXELs drop the padding byte
6d6f0db0 2366 case "fill": // TPIXEL
26586b9d 2367 this._FBU.bytes += 3;
6d6f0db0
SR
2368 break;
2369 case "jpeg": // max clength
2370 this._FBU.bytes += 3;
2371 break;
2372 case "png": // max clength
2373 this._FBU.bytes += 3;
2374 break;
2375 case "filter": // filter id + num colors if palette
2376 this._FBU.bytes += 2;
2377 break;
2378 case "copy":
2379 break;
2380 }
d065cad9 2381
6d6f0db0 2382 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2383
6d6f0db0 2384 // Determine FBU.bytes
2b5f94fa 2385 let cl_offset, filterId;
6d6f0db0
SR
2386 switch (cmode) {
2387 case "fill":
2388 // skip ctl byte
2389 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, [rQ[rQi + 3], rQ[rQi + 2], rQ[rQi + 1]], false);
2390 this._sock.rQskipBytes(4);
2391 break;
2392 case "png":
2393 case "jpeg":
2394 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2b5f94fa 2395 cl_offset = rQi + 1;
6d6f0db0
SR
2396 cl_header = 1;
2397 cl_data = 0;
2398 cl_data += rQ[cl_offset] & 0x7f;
2399 if (rQ[cl_offset] & 0x80) {
2400 cl_header++;
2401 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2402 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2403 cl_header++;
6d6f0db0 2404 cl_data += rQ[cl_offset + 2] << 14;
b1dee947 2405 }
6d6f0db0
SR
2406 }
2407 // end inline getTightCLength
2408 this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
2409 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
798340b9 2410
6d6f0db0
SR
2411 // We have everything, render it
2412 this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
2413 data = this._sock.rQshiftBytes(cl_data);
2414 this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data);
2415 break;
2416 case "filter":
2b5f94fa 2417 filterId = rQ[rQi + 1];
6d6f0db0
SR
2418 if (filterId === 1) {
2419 if (!handlePalette()) { return false; }
b0ec6509 2420 } else {
6d6f0db0
SR
2421 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2422 // Filter 2, Gradient is valid but not use if jpeg is enabled
d472f3f1
SM
2423 this._fail("Unsupported tight subencoding received " +
2424 "(filter: " + filterId + ")");
b0ec6509 2425 }
6d6f0db0
SR
2426 break;
2427 case "copy":
2428 if (!handleCopy()) { return false; }
2429 break;
2430 }
b0ec6509 2431
6d6f0db0
SR
2432
2433 this._FBU.bytes = 0;
2434 this._FBU.rects--;
2435
2436 return true;
2437 },
2438
6d6f0db0
SR
2439 last_rect: function () {
2440 this._FBU.rects = 0;
2441 return true;
2442 },
2443
6d6f0db0
SR
2444 ExtendedDesktopSize: function () {
2445 this._FBU.bytes = 1;
2446 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2447
2b5f94fa 2448 const firstUpdate = !this._supportsSetDesktopSize;
6d6f0db0 2449 this._supportsSetDesktopSize = true;
9b84f516
PO
2450
2451 // Normally we only apply the current resize mode after a
2452 // window resize event. However there is no such trigger on the
2453 // initial connect. And we don't know if the server supports
2454 // resizing until we've gotten here.
2455 if (firstUpdate) {
2456 this._requestRemoteResize();
2457 }
832be262 2458
2b5f94fa 2459 const number_of_screens = this._sock.rQpeek8();
6d6f0db0
SR
2460
2461 this._FBU.bytes = 4 + (number_of_screens * 16);
2462 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2463
2464 this._sock.rQskipBytes(1); // number-of-screens
2465 this._sock.rQskipBytes(3); // padding
2466
2b5f94fa 2467 for (let i = 0; i < number_of_screens; i += 1) {
6d6f0db0
SR
2468 // Save the id and flags of the first screen
2469 if (i === 0) {
2470 this._screen_id = this._sock.rQshiftBytes(4); // id
2471 this._sock.rQskipBytes(2); // x-position
2472 this._sock.rQskipBytes(2); // y-position
2473 this._sock.rQskipBytes(2); // width
2474 this._sock.rQskipBytes(2); // height
2475 this._screen_flags = this._sock.rQshiftBytes(4); // flags
2476 } else {
2477 this._sock.rQskipBytes(16);
798340b9 2478 }
6d6f0db0 2479 }
b0ec6509 2480
6d6f0db0
SR
2481 /*
2482 * The x-position indicates the reason for the change:
2483 *
2484 * 0 - server resized on its own
2485 * 1 - this client requested the resize
2486 * 2 - another client requested the resize
2487 */
b0ec6509 2488
6d6f0db0
SR
2489 // We need to handle errors when we requested the resize.
2490 if (this._FBU.x === 1 && this._FBU.y !== 0) {
2b5f94fa 2491 let msg = "";
6d6f0db0
SR
2492 // The y-position indicates the status code from the server
2493 switch (this._FBU.y) {
2494 case 1:
2495 msg = "Resize is administratively prohibited";
2496 break;
2497 case 2:
2498 msg = "Out of resources";
2499 break;
2500 case 3:
2501 msg = "Invalid screen layout";
2502 break;
2503 default:
2504 msg = "Unknown reason";
2505 break;
2506 }
5b20d338
SM
2507 Log.Warn("Server did not accept the resize request: "
2508 + msg);
910fd3af
PO
2509 } else {
2510 this._resize(this._FBU.width, this._FBU.height);
6d6f0db0 2511 }
b1dee947 2512
91d5c625
PO
2513 this._FBU.bytes = 0;
2514 this._FBU.rects -= 1;
6d6f0db0
SR
2515 return true;
2516 },
b1dee947 2517
6d6f0db0 2518 DesktopSize: function () {
91d5c625
PO
2519 this._resize(this._FBU.width, this._FBU.height);
2520 this._FBU.bytes = 0;
2521 this._FBU.rects -= 1;
6d6f0db0
SR
2522 return true;
2523 },
8db09746 2524
6d6f0db0
SR
2525 Cursor: function () {
2526 Log.Debug(">> set_cursor");
2b5f94fa
JD
2527 const x = this._FBU.x; // hotspot-x
2528 const y = this._FBU.y; // hotspot-y
2529 const w = this._FBU.width;
2530 const h = this._FBU.height;
8db09746 2531
2b5f94fa
JD
2532 const pixelslength = w * h * 4;
2533 const masklength = Math.floor((w + 7) / 8) * h;
a7a89626 2534
6d6f0db0
SR
2535 this._FBU.bytes = pixelslength + masklength;
2536 if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
b1dee947 2537
6d6f0db0
SR
2538 this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
2539 this._sock.rQshiftBytes(masklength),
2540 x, y, w, h);
b1dee947 2541
6d6f0db0
SR
2542 this._FBU.bytes = 0;
2543 this._FBU.rects--;
8f06673a 2544
6d6f0db0
SR
2545 Log.Debug("<< set_cursor");
2546 return true;
2547 },
25e4928f 2548
6d6f0db0
SR
2549 QEMUExtendedKeyEvent: function () {
2550 this._FBU.rects--;
25e4928f 2551
2bf4cf5a
PO
2552 // Old Safari doesn't support creating keyboard events
2553 try {
2b5f94fa 2554 const keyboardEvent = document.createEvent("keyboardEvent");
2bf4cf5a
PO
2555 if (keyboardEvent.code !== undefined) {
2556 this._qemuExtKeyEventSupported = true;
2557 }
2558 } catch (err) {
8727f598 2559 // Do nothing
058be785 2560 }
6d6f0db0 2561 },
8727f598 2562}