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