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