2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2012 Joel Martin
4 * Copyright (C) 2017 Samuel Mannehed for Cendio AB
5 * Licensed under MPL 2.0 (see LICENSE.txt)
7 * See README.md for usage and integration instructions.
9 * TIGHT decoder portion:
10 * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
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";
28 /*jslint white: false, browser: true */
29 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
31 // How many seconds to wait for a disconnect to finish
32 var DISCONNECT_TIMEOUT
= 3;
34 export default function RFB(target
, url
, options
) {
36 throw Error("Must specify target");
39 throw Error("Must specify URL");
42 this._target
= target
;
46 options
= options
|| {};
47 this._rfb_credentials
= options
.credentials
|| {};
48 this._shared
= 'shared' in options
? !!options
.shared
: true;
49 this._repeaterID
= options
.repeaterID
|| '';
52 this._rfb_connection_state
= '';
53 this._rfb_init_state
= '';
54 this._rfb_auth_scheme
= '';
55 this._rfb_clean_disconnect
= true;
57 // Server capabilities
58 this._rfb_version
= 0;
59 this._rfb_max_version
= 3.8;
60 this._rfb_tightvnc
= false;
61 this._rfb_xvp_ver
= 0;
68 this._capabilities
= { power
: false };
70 this._supportsFence
= false;
72 this._supportsContinuousUpdates
= false;
73 this._enabledContinuousUpdates
= false;
75 this._supportsSetDesktopSize
= false;
77 this._screen_flags
= 0;
79 this._qemuExtKeyEventSupported
= false;
82 this._sock
= null; // Websock object
83 this._display
= null; // Display object
84 this._flushing
= false; // Display flushing state
85 this._keyboard
= null; // Keyboard input handler object
86 this._mouse
= null; // Mouse input handler object
89 this._disconnTimer
= null; // disconnection timer
90 this._resizeTimeout
= null; // resize rate limiting
92 // Decoder states and stats
93 this._encHandlers
= {};
98 subrects
: 0, // RRE and HEXTILE
109 zlibs
: [] // TIGHT zlib streams
111 for (var i
= 0; i
< 4; i
++) {
112 this._FBU
.zlibs
[i
] = new Inflator();
115 this._destBuff
= null;
116 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
118 this._rre_chunk_sz
= 100;
134 this._mouse_buttonMask
= 0;
135 this._mouse_arr
= [];
136 this._viewportDragging
= false;
137 this._viewportDragPos
= {};
138 this._viewportHasMoved
= false;
140 // Bound event handlers
141 this._eventHandlers
= {
142 focusCanvas
: this._focusCanvas
.bind(this),
143 windowResize
: this._windowResize
.bind(this),
147 Log
.Debug(">> RFB.constructor");
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
);
167 // populate encHandlers with bound versions
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);
172 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this, false);
173 this._encHandlers
[encodings
.encodingTightPNG
] = RFB
.encodingHandlers
.TIGHT
.bind(this, true);
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);
181 // NB: nothing that needs explicit teardown should be done
182 // before this point, since this can throw an exception
184 this._display
= new Display(this._canvas
);
186 Log
.Error("Display exception: " + exc
);
189 this._display
.onflush
= this._onFlush
.bind(this);
190 this._display
.clear();
192 this._keyboard
= new Keyboard(this._canvas
);
193 this._keyboard
.onkeyevent
= this._handleKeyEvent
.bind(this);
195 this._mouse
= new Mouse(this._canvas
);
196 this._mouse
.onmousebutton
= this._handleMouseButton
.bind(this);
197 this._mouse
.onmousemove
= this._handleMouseMove
.bind(this);
199 this._sock
= new Websock();
200 this._sock
.on('message', this._handle_message
.bind(this));
201 this._sock
.on('open', function () {
202 if ((this._rfb_connection_state
=== 'connecting') &&
203 (this._rfb_init_state
=== '')) {
204 this._rfb_init_state
= 'ProtocolVersion';
205 Log
.Debug("Starting VNC handshake");
207 this._fail("Unexpected server connection while " +
208 this._rfb_connection_state
);
211 this._sock
.on('close', function (e
) {
212 Log
.Debug("WebSocket on-close event");
215 msg
= "(code: " + e
.code
;
217 msg
+= ", reason: " + e
.reason
;
221 switch (this._rfb_connection_state
) {
223 this._fail("Connection closed " + msg
);
226 // Handle disconnects that were initiated server-side
227 this._updateConnectionState('disconnecting');
228 this._updateConnectionState('disconnected');
230 case 'disconnecting':
231 // Normal disconnection path
232 this._updateConnectionState('disconnected');
235 this._fail("Unexpected server disconnect " +
236 "when already disconnected " + msg
);
239 this._fail("Unexpected server disconnect before connecting " +
243 this._sock
.off('close');
245 this._sock
.on('error', function (e
) {
246 Log
.Warn("WebSocket on-error event");
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'));
253 Log
.Debug("<< RFB.constructor");
257 // ===== PROPERTIES =====
263 get viewOnly() { return this._viewOnly
; },
264 set viewOnly(viewOnly
) {
265 this._viewOnly
= viewOnly
;
267 if (this._rfb_connection_state
=== "connecting" ||
268 this._rfb_connection_state
=== "connected") {
270 this._keyboard
.ungrab();
271 this._mouse
.ungrab();
273 this._keyboard
.grab();
279 get capabilities() { return this._capabilities
; },
281 get touchButton() { return this._mouse
.touchButton
; },
282 set touchButton(button
) { this._mouse
.touchButton
= button
; },
284 _clipViewport
: false,
285 get clipViewport() { return this._clipViewport
; },
286 set clipViewport(viewport
) {
287 this._clipViewport
= viewport
;
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
) {
301 if (!scale
&& this._clipViewport
) {
306 _resizeSession
: false,
307 get resizeSession() { return this._resizeSession
; },
308 set resizeSession(resize
) {
309 this._resizeSession
= resize
;
311 this._requestRemoteResize();
315 // ===== PUBLIC METHODS =====
317 disconnect: function () {
318 this._updateConnectionState('disconnecting');
319 this._sock
.off('error');
320 this._sock
.off('message');
321 this._sock
.off('open');
324 sendCredentials: function (creds
) {
325 this._rfb_credentials
= creds
;
326 setTimeout(this._init_msg
.bind(this), 0);
329 sendCtrlAltDel: function () {
330 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
331 Log
.Info("Sending Ctrl-Alt-Del");
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);
341 machineShutdown: function () {
345 machineReboot: function () {
349 machineReset: function () {
353 // Send a key press. If 'down' is not specified then send a down key
354 // followed by an up key.
355 sendKey: function (keysym
, code
, down
) {
356 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
358 if (down
=== undefined) {
359 this.sendKey(keysym
, code
, true);
360 this.sendKey(keysym
, code
, false);
364 var scancode
= XtScancode
[code
];
366 if (this._qemuExtKeyEventSupported
&& scancode
) {
368 keysym
= keysym
|| 0;
370 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
372 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
377 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
378 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
383 this._canvas
.focus();
390 clipboardPasteFrom: function (text
) {
391 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
392 RFB
.messages
.clientCutText(this._sock
, text
);
395 // ===== PRIVATE METHODS =====
397 _connect: function () {
398 Log
.Debug(">> RFB.connect");
400 Log
.Info("connecting to " + this._url
);
403 // WebSocket.onopen transitions to the RFB init states
404 this._sock
.open(this._url
, ['binary']);
406 if (e
.name
=== 'SyntaxError') {
407 this._fail("Invalid host or port (" + e
+ ")");
409 this._fail("Error when opening socket (" + e
+ ")");
413 // Make our elements part of the page
414 this._target
.appendChild(this._screen
);
416 // Monitor size changes of the screen
417 // FIXME: Use ResizeObserver, or hidden overflow
418 window
.addEventListener('resize', this._eventHandlers
.windowResize
);
420 // Always grab focus on some kind of click event
421 this._canvas
.addEventListener("mousedown", this._eventHandlers
.focusCanvas
);
422 this._canvas
.addEventListener("touchstart", this._eventHandlers
.focusCanvas
);
424 Log
.Debug("<< RFB.connect");
427 _disconnect: function () {
428 Log
.Debug(">> RFB.disconnect");
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();
437 this._target
.removeChild(this._screen
);
439 if (e
.name
=== 'NotFoundError') {
440 // Some cases where the initial connection fails
441 // can disconnect before the _screen is created
446 clearTimeout(this._resizeTimeout
);
447 Log
.Debug("<< RFB.disconnect");
450 _print_stats: function () {
451 var stats
= this._encStats
;
453 Log
.Info("Encoding stats for this connection:");
454 Object
.keys(stats
).forEach(function (key
) {
456 if (s
[0] + s
[1] > 0) {
457 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
461 Log
.Info("Encoding stats since page load:");
462 Object
.keys(stats
).forEach(function (key
) {
464 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
468 _focusCanvas: function(event
) {
469 // Respect earlier handlers' request to not do side-effects
470 if (event
.defaultPrevented
) {
474 if (!this.focusOnClick
) {
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 () {
489 if (this._resizeSession
) {
490 // Request changing the resolution of the remote display to
491 // the size of the local browser viewport.
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);
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
;
506 if (this._scaleViewport
) {
507 // Disable viewport clipping if we are scaling
511 if (cur_clip
!== new_clip
) {
512 this._display
.clipViewport
= 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();
524 _updateScale: function () {
525 if (!this._scaleViewport
) {
526 this._display
.scale
= 1.0;
528 let size
= this._screenSize();
529 this._display
.autoscale(size
.w
, size
.h
);
531 this._fixScrollbars();
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;
540 if (!this._resizeSession
|| this._viewOnly
||
541 !this._supportsSetDesktopSize
) {
545 let size
= this._screenSize();
546 RFB
.messages
.setDesktopSize(this._sock
, size
.w
, size
.h
,
547 this._screen_id
, this._screen_flags
);
549 Log
.Debug('Requested new desktop size: ' +
550 size
.w
+ 'x' + size
.h
);
553 // Gets the the size of the available screen
554 _screenSize: function () {
555 return { w
: this._screen
.offsetWidth
,
556 h
: this._screen
.offsetHeight
};
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
;
576 * disconnected - permanent state
578 _updateConnectionState: function (state
) {
579 var oldstate
= this._rfb_connection_state
;
581 if (state
=== oldstate
) {
582 Log
.Debug("Already in state '" + state
+ "', ignoring");
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");
592 // Ensure proper transitions before doing anything
595 if (oldstate
!== 'connecting') {
596 Log
.Error("Bad transition to connected state, " +
597 "previous connection state: " + oldstate
);
603 if (oldstate
!== 'disconnecting') {
604 Log
.Error("Bad transition to disconnected state, " +
605 "previous connection state: " + oldstate
);
611 if (oldstate
!== '') {
612 Log
.Error("Bad transition to connecting state, " +
613 "previous connection state: " + oldstate
);
618 case 'disconnecting':
619 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
620 Log
.Error("Bad transition to disconnecting state, " +
621 "previous connection state: " + oldstate
);
627 Log
.Error("Unknown connection state: " + state
);
631 // State change actions
633 this._rfb_connection_state
= state
;
635 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
638 if (this._disconnTimer
&& state
!== 'disconnecting') {
639 Log
.Debug("Clearing disconnect timer");
640 clearTimeout(this._disconnTimer
);
641 this._disconnTimer
= null;
643 // make sure we don't get a double event
644 this._sock
.off('close');
653 var event
= new CustomEvent("connect", { detail
: {} });
654 this.dispatchEvent(event
);
657 case 'disconnecting':
660 this._disconnTimer
= setTimeout(function () {
661 Log
.Error("Disconnection timed out.");
662 this._updateConnectionState('disconnected');
663 }.bind(this), DISCONNECT_TIMEOUT
* 1000);
667 event
= new CustomEvent(
668 "disconnect", { detail
:
669 { clean
: this._rfb_clean_disconnect
} });
670 this.dispatchEvent(event
);
675 /* Print errors and disconnect
677 * The parameter 'details' is used for information that
678 * should be logged but not sent to the user interface.
680 _fail: function (details
) {
681 switch (this._rfb_connection_state
) {
682 case 'disconnecting':
683 Log
.Error("Failed when disconnecting: " + details
);
686 Log
.Error("Failed while connected: " + details
);
689 Log
.Error("Failed when connecting: " + details
);
692 Log
.Error("RFB failure: " + details
);
695 this._rfb_clean_disconnect
= false; //This is sent to the UI
697 // Transition to disconnected without waiting for socket to close
698 this._updateConnectionState('disconnecting');
699 this._updateConnectionState('disconnected');
704 _setCapability: function (cap
, val
) {
705 this._capabilities
[cap
] = val
;
706 var event
= new CustomEvent("capabilities",
707 { detail
: { capabilities
: this._capabilities
} });
708 this.dispatchEvent(event
);
711 _handle_message: function () {
712 if (this._sock
.rQlen() === 0) {
713 Log
.Warn("handle_message called on an empty receive queue");
717 switch (this._rfb_connection_state
) {
719 Log
.Error("Got data while disconnected");
723 if (this._flushing
) {
726 if (!this._normal_msg()) {
729 if (this._sock
.rQlen() === 0) {
740 _handleKeyEvent: function (keysym
, code
, down
) {
741 this.sendKey(keysym
, code
, down
);
744 _handleMouseButton: function (x
, y
, down
, bmask
) {
746 this._mouse_buttonMask
|= bmask
;
748 this._mouse_buttonMask
&= ~bmask
;
751 if (this.dragViewport
) {
752 if (down
&& !this._viewportDragging
) {
753 this._viewportDragging
= true;
754 this._viewportDragPos
= {'x': x
, 'y': y
};
755 this._viewportHasMoved
= false;
757 // Skip sending mouse events
760 this._viewportDragging
= false;
762 // If we actually performed a drag then we are done
763 // here and should not send any mouse events
764 if (this._viewportHasMoved
) {
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
),
778 if (this._viewOnly
) { return; } // View only, skip mouse events
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
);
784 _handleMouseMove: function (x
, y
) {
785 if (this._viewportDragging
) {
786 var deltaX
= this._viewportDragPos
.x
- x
;
787 var deltaY
= this._viewportDragPos
.y
- y
;
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);
793 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
794 Math
.abs(deltaY
) > dragThreshold
)) {
795 this._viewportHasMoved
= true;
797 this._viewportDragPos
= {'x': x
, 'y': y
};
798 this._display
.viewportChangePos(deltaX
, deltaY
);
801 // Skip sending mouse events
805 if (this._viewOnly
) { return; } // View only, skip mouse events
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
);
813 _negotiate_protocol_version: function () {
814 if (this._sock
.rQlen() < 12) {
815 return this._fail("Received incomplete protocol version.");
818 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
819 Log
.Info("Server ProtocolVersion: " + sversion
);
822 case "000.000": // UltraVNC repeater
826 case "003.006": // UltraVNC
827 case "003.889": // Apple Remote Desktop
828 this._rfb_version
= 3.3;
831 this._rfb_version
= 3.7;
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;
840 return this._fail("Invalid server version " + sversion
);
844 var repeaterID
= "ID:" + this._repeaterID
;
845 while (repeaterID
.length
< 250) {
848 this._sock
.send_string(repeaterID
);
852 if (this._rfb_version
> this._rfb_max_version
) {
853 this._rfb_version
= this._rfb_max_version
;
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
);
861 this._rfb_init_state
= 'Security';
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
) {
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; }
881 if (num_types
=== 0) {
882 return this._handle_security_failure("no security types");
885 var types
= this._sock
.rQshiftBytes(num_types
);
886 Log
.Debug("Server security types: " + types
);
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
899 return this._fail("Unsupported security types (types: " + types
+ ")");
902 this._sock
.send([this._rfb_auth_scheme
]);
905 if (this._sock
.rQwait("security scheme", 4)) { return false; }
906 this._rfb_auth_scheme
= this._sock
.rQshift32();
909 this._rfb_init_state
= 'Authentication';
910 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
912 return this._init_msg(); // jump to authentication
916 * Get the security failure reason if sent from the server and
917 * send the 'securityfailure' event.
919 * - The optional parameter context can be used to add some extra
920 * context to the log output.
922 * - The optional parameter security_result_status can be used to
923 * add a custom status code to the event.
925 _handle_security_failure: function (context
, security_result_status
) {
927 if (typeof context
=== 'undefined') {
930 context
= " on " + context
;
933 if (typeof security_result_status
=== 'undefined') {
934 security_result_status
= 1; // fail
937 if (this._sock
.rQwait("reason length", 4)) {
940 let strlen
= this._sock
.rQshift32();
944 if (this._sock
.rQwait("reason", strlen
, 8)) { return false; }
945 reason
= this._sock
.rQshiftStr(strlen
);
950 let event
= new CustomEvent(
952 { detail
: { status
: security_result_status
, reason
: reason
} });
953 this.dispatchEvent(event
);
955 return this._fail("Security negotiation failed" + context
+
956 " (reason: " + reason
+ ")");
959 let event
= new CustomEvent(
961 { detail
: { status
: security_result_status
} });
962 this.dispatchEvent(event
);
964 return this._fail("Security negotiation failed" + context
);
969 _negotiate_xvp_auth: function () {
970 if (!this._rfb_credentials
.username
||
971 !this._rfb_credentials
.password
||
972 !this._rfb_credentials
.target
) {
973 var event
= new CustomEvent("credentialsrequired",
974 { detail
: { types
: ["username", "password", "target"] } });
975 this.dispatchEvent(event
);
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
;
983 this._sock
.send_string(xvp_auth_str
);
984 this._rfb_auth_scheme
= 2;
985 return this._negotiate_authentication();
988 _negotiate_std_vnc_auth: function () {
989 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
991 if (!this._rfb_credentials
.password
) {
992 var event
= new CustomEvent("credentialsrequired",
993 { detail
: { types
: ["password"] } });
994 this.dispatchEvent(event
);
998 // TODO(directxman12): make genDES not require an Array
999 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
1000 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
1001 this._sock
.send(response
);
1002 this._rfb_init_state
= "SecurityResult";
1006 _negotiate_tight_tunnels: function (numTunnels
) {
1007 var clientSupportedTunnelTypes
= {
1008 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
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
};
1019 // choose the notunnel type
1020 if (serverSupportedTunnelTypes
[0]) {
1021 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
1022 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
1023 return this._fail("Client's tunnel type had the incorrect " +
1024 "vendor or signature");
1026 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
1027 return false; // wait until we receive the sub auth count to continue
1029 return this._fail("Server wanted tunnels, but doesn't support " +
1030 "the notunnel type");
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; }
1040 this._rfb_tightvnc
= true;
1042 if (numTunnels
> 0) {
1043 this._negotiate_tight_tunnels(numTunnels
);
1044 return false; // wait until we receive the sub auth to continue
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';
1056 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
1058 var clientSupportedTypes
= {
1063 var serverSupportedTypes
= [];
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
);
1071 for (var authType
in clientSupportedTypes
) {
1072 if (serverSupportedTypes
.indexOf(authType
) != -1) {
1073 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
1076 case 'STDVNOAUTH__': // no auth
1077 this._rfb_init_state
= 'SecurityResult';
1079 case 'STDVVNCAUTH_': // VNC auth
1080 this._rfb_auth_scheme
= 2;
1081 return this._init_msg();
1083 return this._fail("Unsupported tiny auth scheme " +
1084 "(scheme: " + authType
+ ")");
1089 return this._fail("No supported sub-auth types!");
1092 _negotiate_authentication: function () {
1093 switch (this._rfb_auth_scheme
) {
1094 case 0: // connection failed
1095 return this._handle_security_failure("authentication scheme");
1098 if (this._rfb_version
>= 3.8) {
1099 this._rfb_init_state
= 'SecurityResult';
1102 this._rfb_init_state
= 'ClientInitialisation';
1103 return this._init_msg();
1105 case 22: // XVP auth
1106 return this._negotiate_xvp_auth();
1108 case 2: // VNC authentication
1109 return this._negotiate_std_vnc_auth();
1111 case 16: // TightVNC Security Type
1112 return this._negotiate_tight_auth();
1115 return this._fail("Unsupported auth scheme (scheme: " +
1116 this._rfb_auth_scheme
+ ")");
1120 _handle_security_result: function () {
1121 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
1123 let status
= this._sock
.rQshift32();
1125 if (status
=== 0) { // OK
1126 this._rfb_init_state
= 'ClientInitialisation';
1127 Log
.Debug('Authentication OK');
1128 return this._init_msg();
1130 if (this._rfb_version
>= 3.8) {
1131 return this._handle_security_failure("security result", status
);
1133 let event
= new CustomEvent("securityfailure",
1134 { detail
: { status
: status
} });
1135 this.dispatchEvent(event
);
1137 return this._fail("Security handshake failed");
1142 _negotiate_server_init: function () {
1143 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1146 var width
= this._sock
.rQshift16();
1147 var height
= this._sock
.rQshift16();
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();
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
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
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));
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
1179 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1180 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1182 // we don't actually do anything with the capability information that TIGHT sends,
1183 // so we just skip the all of this.
1185 // TIGHT server message capabilities
1186 this._sock.rQskipBytes(16 * numServerMessages);
1188 // TIGHT client message capabilities
1189 this._sock.rQskipBytes(16 * numClientMessages);
1191 // TIGHT encoding capabilities
1192 this._sock.rQskipBytes(16 * numEncodings);
1195 // NB(directxman12): these are down here so that we don't run them multiple times
1197 Log.Info("Screen: " + width + "x" + height +
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);
1208 if (big_endian !== 0) {
1209 Log.Warn("Server native endian is not little endian");
1212 if (red_shift !== 16) {
1213 Log.Warn("Server native red-shift is not 16");
1216 if (blue_shift !== 0) {
1217 Log.Warn("Server native blue-shift is not 0");
1220 // we're past the point where we could backtrack, so it's safe to call this
1221 var event = new CustomEvent("desktopname",
1222 { detail: { name: this._fb_name } });
1223 this.dispatchEvent(event);
1225 this._resize(width, height);
1227 if (!this._viewOnly) { this._keyboard.grab(); }
1228 if (!this._viewOnly) { this._mouse.grab(); }
1230 this._fb_depth = 24;
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.");
1237 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1238 this._sendEncodings();
1239 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1241 this._timing.fbu_rt_start = (new Date()).getTime();
1242 this._timing.pixels = 0;
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();
1248 this._updateConnectionState('connected');
1252 _sendEncodings: function () {
1255 // In preference order
1256 encs.push(encodings.encodingCopyRect);
1257 // Only supported with full depth support
1258 if (this._fb_depth == 24) {
1259 encs.push(encodings.encodingTight);
1260 encs.push(encodings.encodingTightPNG);
1261 encs.push(encodings.encodingHextile);
1262 encs.push(encodings.encodingRRE);
1264 encs.push(encodings.encodingRaw);
1266 // Psuedo-encoding settings
1267 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1268 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
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);
1278 if (supportsCursorURIs() &&
1279 !isTouchDevice && this._fb_depth == 24) {
1280 encs.push(encodings.pseudoEncodingCursor);
1283 RFB.messages.clientEncodings(this._sock, encs);
1286 /* RFB protocol initialization states:
1291 * ClientInitialization - not triggered by server message
1292 * ServerInitialization
1294 _init_msg: function () {
1295 switch (this._rfb_init_state
) {
1296 case 'ProtocolVersion':
1297 return this._negotiate_protocol_version();
1300 return this._negotiate_security();
1302 case 'Authentication':
1303 return this._negotiate_authentication();
1305 case 'SecurityResult':
1306 return this._handle_security_result();
1308 case 'ClientInitialisation':
1309 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1310 this._rfb_init_state
= 'ServerInitialisation';
1313 case 'ServerInitialisation':
1314 return this._negotiate_server_init();
1317 return this._fail("Unknown init state (state: " +
1318 this._rfb_init_state
+ ")");
1322 _handle_set_colour_map_msg: function () {
1323 Log
.Debug("SetColorMapEntries");
1325 return this._fail("Unexpected SetColorMapEntries message");
1328 _handle_server_cut_text: function () {
1329 Log
.Debug("ServerCutText");
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; }
1336 var text
= this._sock
.rQshiftStr(length
);
1338 if (this._viewOnly
) { return true; }
1340 var event
= new CustomEvent("clipboard",
1341 { detail
: { text
: text
} });
1342 this.dispatchEvent(event
);
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();
1353 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1356 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1360 var payload
= this._sock
.rQshiftStr(length
);
1362 this._supportsFence
= true;
1367 * (1<<0) - BlockBefore
1368 * (1<<1) - BlockAfter
1373 if (!(flags
& (1<<31))) {
1374 return this._fail("Unexpected fence response");
1377 // Filter out unsupported flags
1378 // FIXME: support syncNext
1379 flags
&= (1<<0) | (1<<1);
1381 // BlockBefore and BlockAfter are automatically handled by
1382 // the fact that we process each incoming message
1384 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
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();
1397 Log
.Error("XVP Operation Failed");
1400 this._rfb_xvp_ver
= xvp_ver
;
1401 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1402 this._setCapability("power", true);
1405 this._fail("Illegal server XVP message (msg: " + xvp_msg
+ ")");
1412 _normal_msg: function () {
1415 if (this._FBU
.rects
> 0) {
1418 msg_type
= this._sock
.rQshift8();
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
);
1430 case 1: // SetColorMapEntries
1431 return this._handle_set_colour_map_msg();
1435 var event
= new CustomEvent("bell", { detail
: {} });
1436 this.dispatchEvent(event
);
1439 case 3: // ServerCutText
1440 return this._handle_server_cut_text();
1442 case 150: // EndOfContinuousUpdates
1443 var first
= !(this._supportsContinuousUpdates
);
1444 this._supportsContinuousUpdates
= true;
1445 this._enabledContinuousUpdates
= false;
1447 this._enabledContinuousUpdates
= true;
1448 this._updateContinuousUpdates();
1449 Log
.Info("Enabling continuous updates.");
1451 // FIXME: We need to send a framebufferupdaterequest here
1452 // if we add support for turning off continuous updates
1456 case 248: // ServerFence
1457 return this._handle_server_fence_msg();
1460 return this._handle_xvp_msg();
1463 this._fail("Unexpected server message (type " + msg_type
+ ")");
1464 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1469 _onFlush: function() {
1470 this._flushing
= false;
1471 // Resume processing
1472 if (this._sock
.rQlen() > 0) {
1473 this._handle_message();
1477 _framebufferUpdate: function () {
1481 if (this._FBU
.rects
=== 0) {
1482 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1483 this._sock
.rQskip8(); // Padding
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
));
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();
1501 while (this._FBU
.rects
> 0) {
1502 if (this._rfb_connection_state
!== 'connected') { return false; }
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 */
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);
1517 if (!this._encHandlers
[this._FBU
.encoding
]) {
1518 this._fail("Unsupported encoding (encoding: " +
1519 this._FBU
.encoding
+ ")");
1524 this._timing
.last_fbu
= (new Date()).getTime();
1526 ret
= this._encHandlers
[this._FBU
.encoding
]();
1528 now
= (new Date()).getTime();
1529 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1532 if (!(this._FBU
.encoding
in this._encStats
)) {
1533 this._encStats
[this._FBU
.encoding
] = [0, 0];
1535 this._encStats
[this._FBU
.encoding
][0]++;
1536 this._encStats
[this._FBU
.encoding
][1]++;
1537 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
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
));
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;
1565 if (!ret
) { return ret
; } // need more data
1568 this._display
.flip();
1570 return true; // We finished this FBU
1573 _updateContinuousUpdates: function() {
1574 if (!this._enabledContinuousUpdates
) { return; }
1576 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1577 this._fb_width
, this._fb_height
);
1580 _resize: function(width
, height
) {
1581 this._fb_width
= width
;
1582 this._fb_height
= height
;
1584 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1586 this._display
.resize(this._fb_width
, this._fb_height
);
1588 // Adjust the visible viewport based on the new dimensions
1590 this._updateScale();
1592 this._timing
.fbu_rt_start
= (new Date()).getTime();
1593 this._updateContinuousUpdates();
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
);
1603 Object
.assign(RFB
.prototype, EventTargetMixin
);
1607 keyEvent: function (sock
, keysym
, down
) {
1608 var buff
= sock
._sQ
;
1609 var offset
= sock
._sQlen
;
1611 buff
[offset
] = 4; // msg-type
1612 buff
[offset
+ 1] = down
;
1614 buff
[offset
+ 2] = 0;
1615 buff
[offset
+ 3] = 0;
1617 buff
[offset
+ 4] = (keysym
>> 24);
1618 buff
[offset
+ 5] = (keysym
>> 16);
1619 buff
[offset
+ 6] = (keysym
>> 8);
1620 buff
[offset
+ 7] = keysym
;
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;
1637 var buff
= sock
._sQ
;
1638 var offset
= sock
._sQlen
;
1640 buff
[offset
] = 255; // msg-type
1641 buff
[offset
+ 1] = 0; // sub msg-type
1643 buff
[offset
+ 2] = (down
>> 8);
1644 buff
[offset
+ 3] = down
;
1646 buff
[offset
+ 4] = (keysym
>> 24);
1647 buff
[offset
+ 5] = (keysym
>> 16);
1648 buff
[offset
+ 6] = (keysym
>> 8);
1649 buff
[offset
+ 7] = keysym
;
1651 var RFBkeycode
= getRFBkeycode(keycode
);
1653 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1654 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1655 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1656 buff
[offset
+ 11] = RFBkeycode
;
1662 pointerEvent: function (sock
, x
, y
, mask
) {
1663 var buff
= sock
._sQ
;
1664 var offset
= sock
._sQlen
;
1666 buff
[offset
] = 5; // msg-type
1668 buff
[offset
+ 1] = mask
;
1670 buff
[offset
+ 2] = x
>> 8;
1671 buff
[offset
+ 3] = x
;
1673 buff
[offset
+ 4] = y
>> 8;
1674 buff
[offset
+ 5] = y
;
1680 // TODO(directxman12): make this unicode compatible?
1681 clientCutText: function (sock
, text
) {
1682 var buff
= sock
._sQ
;
1683 var offset
= sock
._sQlen
;
1685 buff
[offset
] = 6; // msg-type
1687 buff
[offset
+ 1] = 0; // padding
1688 buff
[offset
+ 2] = 0; // padding
1689 buff
[offset
+ 3] = 0; // padding
1691 var n
= text
.length
;
1693 buff
[offset
+ 4] = n
>> 24;
1694 buff
[offset
+ 5] = n
>> 16;
1695 buff
[offset
+ 6] = n
>> 8;
1696 buff
[offset
+ 7] = n
;
1698 for (var i
= 0; i
< n
; i
++) {
1699 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1702 sock
._sQlen
+= 8 + n
;
1706 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1707 var buff
= sock
._sQ
;
1708 var offset
= sock
._sQlen
;
1710 buff
[offset
] = 251; // msg-type
1711 buff
[offset
+ 1] = 0; // padding
1712 buff
[offset
+ 2] = width
>> 8; // width
1713 buff
[offset
+ 3] = width
;
1714 buff
[offset
+ 4] = height
>> 8; // height
1715 buff
[offset
+ 5] = height
;
1717 buff
[offset
+ 6] = 1; // number-of-screens
1718 buff
[offset
+ 7] = 0; // padding
1721 buff
[offset
+ 8] = id
>> 24; // id
1722 buff
[offset
+ 9] = id
>> 16;
1723 buff
[offset
+ 10] = id
>> 8;
1724 buff
[offset
+ 11] = id
;
1725 buff
[offset
+ 12] = 0; // x-position
1726 buff
[offset
+ 13] = 0;
1727 buff
[offset
+ 14] = 0; // y-position
1728 buff
[offset
+ 15] = 0;
1729 buff
[offset
+ 16] = width
>> 8; // width
1730 buff
[offset
+ 17] = width
;
1731 buff
[offset
+ 18] = height
>> 8; // height
1732 buff
[offset
+ 19] = height
;
1733 buff
[offset
+ 20] = flags
>> 24; // flags
1734 buff
[offset
+ 21] = flags
>> 16;
1735 buff
[offset
+ 22] = flags
>> 8;
1736 buff
[offset
+ 23] = flags
;
1742 clientFence: function (sock
, flags
, payload
) {
1743 var buff
= sock
._sQ
;
1744 var offset
= sock
._sQlen
;
1746 buff
[offset
] = 248; // msg-type
1748 buff
[offset
+ 1] = 0; // padding
1749 buff
[offset
+ 2] = 0; // padding
1750 buff
[offset
+ 3] = 0; // padding
1752 buff
[offset
+ 4] = flags
>> 24; // flags
1753 buff
[offset
+ 5] = flags
>> 16;
1754 buff
[offset
+ 6] = flags
>> 8;
1755 buff
[offset
+ 7] = flags
;
1757 var n
= payload
.length
;
1759 buff
[offset
+ 8] = n
; // length
1761 for (var i
= 0; i
< n
; i
++) {
1762 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1765 sock
._sQlen
+= 9 + n
;
1769 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1770 var buff
= sock
._sQ
;
1771 var offset
= sock
._sQlen
;
1773 buff
[offset
] = 150; // msg-type
1774 buff
[offset
+ 1] = enable
; // enable-flag
1776 buff
[offset
+ 2] = x
>> 8; // x
1777 buff
[offset
+ 3] = x
;
1778 buff
[offset
+ 4] = y
>> 8; // y
1779 buff
[offset
+ 5] = y
;
1780 buff
[offset
+ 6] = width
>> 8; // width
1781 buff
[offset
+ 7] = width
;
1782 buff
[offset
+ 8] = height
>> 8; // height
1783 buff
[offset
+ 9] = height
;
1789 pixelFormat: function (sock
, depth
, true_color
) {
1790 var buff
= sock
._sQ
;
1791 var offset
= sock
._sQlen
;
1797 } else if (depth
> 8) {
1803 bits
= Math
.floor(depth
/3);
1805 buff
[offset
] = 0; // msg-type
1807 buff
[offset
+ 1] = 0; // padding
1808 buff
[offset
+ 2] = 0; // padding
1809 buff
[offset
+ 3] = 0; // padding
1811 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1812 buff
[offset
+ 5] = depth
; // depth
1813 buff
[offset
+ 6] = 0; // little-endian
1814 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1816 buff
[offset
+ 8] = 0; // red-max
1817 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1819 buff
[offset
+ 10] = 0; // green-max
1820 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1822 buff
[offset
+ 12] = 0; // blue-max
1823 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1825 buff
[offset
+ 14] = bits
* 2; // red-shift
1826 buff
[offset
+ 15] = bits
* 1; // green-shift
1827 buff
[offset
+ 16] = bits
* 0; // blue-shift
1829 buff
[offset
+ 17] = 0; // padding
1830 buff
[offset
+ 18] = 0; // padding
1831 buff
[offset
+ 19] = 0; // padding
1837 clientEncodings: function (sock
, encodings
) {
1838 var buff
= sock
._sQ
;
1839 var offset
= sock
._sQlen
;
1841 buff
[offset
] = 2; // msg-type
1842 buff
[offset
+ 1] = 0; // padding
1844 buff
[offset
+ 2] = encodings
.length
>> 8;
1845 buff
[offset
+ 3] = encodings
.length
;
1847 var i
, j
= offset
+ 4;
1848 for (i
= 0; i
< encodings
.length
; i
++) {
1849 var enc
= encodings
[i
];
1850 buff
[j
] = enc
>> 24;
1851 buff
[j
+ 1] = enc
>> 16;
1852 buff
[j
+ 2] = enc
>> 8;
1858 sock
._sQlen
+= j
- offset
;
1862 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1863 var buff
= sock
._sQ
;
1864 var offset
= sock
._sQlen
;
1866 if (typeof(x
) === "undefined") { x
= 0; }
1867 if (typeof(y
) === "undefined") { y
= 0; }
1869 buff
[offset
] = 3; // msg-type
1870 buff
[offset
+ 1] = incremental
? 1 : 0;
1872 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1873 buff
[offset
+ 3] = x
& 0xFF;
1875 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1876 buff
[offset
+ 5] = y
& 0xFF;
1878 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1879 buff
[offset
+ 7] = w
& 0xFF;
1881 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1882 buff
[offset
+ 9] = h
& 0xFF;
1888 xvpOp: function (sock
, ver
, op
) {
1889 var buff
= sock
._sQ
;
1890 var offset
= sock
._sQlen
;
1892 buff
[offset
] = 250; // msg-type
1893 buff
[offset
+ 1] = 0; // padding
1895 buff
[offset
+ 2] = ver
;
1896 buff
[offset
+ 3] = op
;
1903 RFB
.genDES = function (password
, challenge
) {
1905 for (var i
= 0; i
< password
.length
; i
++) {
1906 passwd
.push(password
.charCodeAt(i
));
1908 return (new DES(passwd
)).encrypt(challenge
);
1911 RFB
.encodingHandlers
= {
1913 if (this._FBU
.lines
=== 0) {
1914 this._FBU
.lines
= this._FBU
.height
;
1917 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1918 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1919 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1920 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1921 var curr_height
= Math
.min(this._FBU
.lines
,
1922 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1923 var data
= this._sock
.get_rQ();
1924 var index
= this._sock
.get_rQi();
1925 if (this._fb_depth
== 8) {
1926 var pixels
= this._FBU
.width
* curr_height
1927 var newdata
= new Uint8Array(pixels
* 4);
1929 for (i
= 0;i
< pixels
;i
++) {
1930 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1931 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1932 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1933 newdata
[i
* 4 + 4] = 0;
1938 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1939 curr_height
, data
, index
);
1940 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1941 this._FBU
.lines
-= curr_height
;
1943 if (this._FBU
.lines
> 0) {
1944 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1947 this._FBU
.bytes
= 0;
1953 COPYRECT: function () {
1954 this._FBU
.bytes
= 4;
1955 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1956 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1957 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1961 this._FBU
.bytes
= 0;
1967 if (this._FBU
.subrects
=== 0) {
1968 this._FBU
.bytes
= 4 + 4;
1969 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1970 this._FBU
.subrects
= this._sock
.rQshift32();
1971 color
= this._sock
.rQshiftBytes(4); // Background
1972 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1975 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1976 color
= this._sock
.rQshiftBytes(4);
1977 var x
= this._sock
.rQshift16();
1978 var y
= this._sock
.rQshift16();
1979 var width
= this._sock
.rQshift16();
1980 var height
= this._sock
.rQshift16();
1981 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1982 this._FBU
.subrects
--;
1985 if (this._FBU
.subrects
> 0) {
1986 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1987 this._FBU
.bytes
= (4 + 8) * chunk
;
1990 this._FBU
.bytes
= 0;
1996 HEXTILE: function () {
1997 var rQ
= this._sock
.get_rQ();
1998 var rQi
= this._sock
.get_rQi();
2000 if (this._FBU
.tiles
=== 0) {
2001 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
2002 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
2003 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
2004 this._FBU
.tiles
= this._FBU
.total_tiles
;
2007 while (this._FBU
.tiles
> 0) {
2008 this._FBU
.bytes
= 1;
2009 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
2010 var subencoding
= rQ
[rQi
]; // Peek
2011 if (subencoding
> 30) { // Raw
2012 this._fail("Illegal hextile subencoding (subencoding: " +
2018 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
2019 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
2020 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
2021 var x
= this._FBU
.x
+ tile_x
* 16;
2022 var y
= this._FBU
.y
+ tile_y
* 16;
2023 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
2024 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
2026 // Figure out how much we are expecting
2027 if (subencoding
& 0x01) { // Raw
2028 this._FBU
.bytes
+= w
* h
* 4;
2030 if (subencoding
& 0x02) { // Background
2031 this._FBU
.bytes
+= 4;
2033 if (subencoding
& 0x04) { // Foreground
2034 this._FBU
.bytes
+= 4;
2036 if (subencoding
& 0x08) { // AnySubrects
2037 this._FBU
.bytes
++; // Since we aren't shifting it off
2038 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
2039 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
2040 if (subencoding
& 0x10) { // SubrectsColoured
2041 this._FBU
.bytes
+= subrects
* (4 + 2);
2043 this._FBU
.bytes
+= subrects
* 2;
2048 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
2050 // We know the encoding and have a whole tile
2051 this._FBU
.subencoding
= rQ
[rQi
];
2053 if (this._FBU
.subencoding
=== 0) {
2054 if (this._FBU
.lastsubencoding
& 0x01) {
2055 // Weird: ignore blanks are RAW
2056 Log
.Debug(" Ignoring blank after RAW");
2058 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
2060 } else if (this._FBU
.subencoding
& 0x01) { // Raw
2061 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
2062 rQi
+= this._FBU
.bytes
- 1;
2064 if (this._FBU
.subencoding
& 0x02) { // Background
2065 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2068 if (this._FBU
.subencoding
& 0x04) { // Foreground
2069 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2073 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
2074 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
2078 for (var s
= 0; s
< subrects
; s
++) {
2080 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
2081 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2084 color
= this._FBU
.foreground
;
2089 var sy
= (xy
& 0x0f);
2093 var sw
= (wh
>> 4) + 1;
2094 var sh
= (wh
& 0x0f) + 1;
2096 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2099 this._display
.finishTile();
2101 this._sock
.set_rQi(rQi
);
2102 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2103 this._FBU
.bytes
= 0;
2107 if (this._FBU
.tiles
=== 0) {
2114 TIGHT: function (isTightPNG
) {
2115 this._FBU
.bytes
= 1; // compression-control byte
2116 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2118 var checksum = function (data
) {
2120 for (var i
= 0; i
< data
.length
; i
++) {
2122 if (sum
> 65536) sum
-= 65536;
2127 var resetStreams
= 0;
2129 var decompress = function (data
, expected
) {
2130 for (var i
= 0; i
< 4; i
++) {
2131 if ((resetStreams
>> i
) & 1) {
2132 this._FBU
.zlibs
[i
].reset();
2133 Log
.Info("Reset zlib stream " + i
);
2137 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2138 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2139 /*if (uncompressed.status !== 0) {
2140 Log.Error("Invalid data in zlib stream");
2143 //return uncompressed.data;
2144 return uncompressed
;
2147 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2148 // Convert indexed (palette based) image data to RGB
2149 // TODO: reduce number of calculations inside loop
2150 var dest
= this._destBuff
;
2151 var w
= Math
.floor((width
+ 7) / 8);
2152 var w1
= Math
.floor(width
/ 8);
2154 /*for (var y = 0; y < height; y++) {
2156 var yoffset = y * width;
2157 var ybitoffset = y * w;
2158 var xoffset, targetbyte;
2159 for (x = 0; x < w1; x++) {
2160 xoffset = yoffset + x * 8;
2161 targetbyte = data[ybitoffset + x];
2162 for (b = 7; b >= 0; b--) {
2163 dp = (xoffset + 7 - b) * 3;
2164 sp = (targetbyte >> b & 1) * 3;
2165 dest[dp] = palette[sp];
2166 dest[dp + 1] = palette[sp + 1];
2167 dest[dp + 2] = palette[sp + 2];
2171 xoffset = yoffset + x * 8;
2172 targetbyte = data[ybitoffset + x];
2173 for (b = 7; b >= 8 - width % 8; b--) {
2174 dp = (xoffset + 7 - b) * 3;
2175 sp = (targetbyte >> b & 1) * 3;
2176 dest[dp] = palette[sp];
2177 dest[dp + 1] = palette[sp + 1];
2178 dest[dp + 2] = palette[sp + 2];
2182 for (var y
= 0; y
< height
; y
++) {
2184 for (x
= 0; x
< w1
; x
++) {
2185 for (b
= 7; b
>= 0; b
--) {
2186 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2187 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2188 dest
[dp
] = palette
[sp
];
2189 dest
[dp
+ 1] = palette
[sp
+ 1];
2190 dest
[dp
+ 2] = palette
[sp
+ 2];
2195 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2196 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2197 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2198 dest
[dp
] = palette
[sp
];
2199 dest
[dp
+ 1] = palette
[sp
+ 1];
2200 dest
[dp
+ 2] = palette
[sp
+ 2];
2208 var indexedToRGBX = function (data
, palette
, width
, height
) {
2209 // Convert indexed (palette based) image data to RGB
2210 var dest
= this._destBuff
;
2211 var total
= width
* height
* 4;
2212 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2213 var sp
= data
[j
] * 3;
2214 dest
[i
] = palette
[sp
];
2215 dest
[i
+ 1] = palette
[sp
+ 1];
2216 dest
[i
+ 2] = palette
[sp
+ 2];
2223 var rQi
= this._sock
.get_rQi();
2224 var rQ
= this._sock
.rQwhole();
2226 var cl_header
, cl_data
;
2228 var handlePalette = function () {
2229 var numColors
= rQ
[rQi
+ 2] + 1;
2230 var paletteSize
= numColors
* 3;
2231 this._FBU
.bytes
+= paletteSize
;
2232 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2234 var bpp
= (numColors
<= 2) ? 1 : 8;
2235 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2237 if (rowSize
* this._FBU
.height
< 12) {
2240 cl_data
= rowSize
* this._FBU
.height
;
2241 //clength = [0, rowSize * this._FBU.height];
2243 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2244 var cl_offset
= rQi
+ 3 + paletteSize
;
2247 cl_data
+= rQ
[cl_offset
] & 0x7f;
2248 if (rQ
[cl_offset
] & 0x80) {
2250 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2251 if (rQ
[cl_offset
+ 1] & 0x80) {
2253 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2256 // end inline getTightCLength
2259 this._FBU
.bytes
+= cl_header
+ cl_data
;
2260 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2262 // Shift ctl, filter id, num colors, palette entries, and clength off
2263 this._sock
.rQskipBytes(3);
2264 //var palette = this._sock.rQshiftBytes(paletteSize);
2265 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2266 this._sock
.rQskipBytes(cl_header
);
2269 data
= this._sock
.rQshiftBytes(cl_data
);
2271 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2274 // Convert indexed (palette based) image data to RGB
2276 if (numColors
== 2) {
2277 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2278 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2280 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2281 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2288 var handleCopy = function () {
2290 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2291 if (uncompressedSize
< 12) {
2294 cl_data
= uncompressedSize
;
2296 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2297 var cl_offset
= rQi
+ 1;
2300 cl_data
+= rQ
[cl_offset
] & 0x7f;
2301 if (rQ
[cl_offset
] & 0x80) {
2303 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2304 if (rQ
[cl_offset
+ 1] & 0x80) {
2306 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2309 // end inline getTightCLength
2311 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2312 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2314 // Shift ctl, clength off
2315 this._sock
.rQshiftBytes(1 + cl_header
);
2318 data
= this._sock
.rQshiftBytes(cl_data
);
2320 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2323 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2328 var ctl
= this._sock
.rQpeek8();
2330 // Keep tight reset bits
2331 resetStreams
= ctl
& 0xF;
2333 // Figure out filter
2335 streamId
= ctl
& 0x3;
2337 if (ctl
=== 0x08) cmode
= "fill";
2338 else if (ctl
=== 0x09) cmode
= "jpeg";
2339 else if (ctl
=== 0x0A) cmode
= "png";
2340 else if (ctl
& 0x04) cmode
= "filter";
2341 else if (ctl
< 0x04) cmode
= "copy";
2342 else return this._fail("Illegal tight compression received (ctl: " +
2345 if (isTightPNG
&& (ctl
< 0x08)) {
2346 return this._fail("BasicCompression received in TightPNG rect");
2348 if (!isTightPNG
&& (ctl
=== 0x0A)) {
2349 return this._fail("PNG received in standard Tight rect");
2353 // fill use depth because TPIXELs drop the padding byte
2354 case "fill": // TPIXEL
2355 this._FBU
.bytes
+= 3;
2357 case "jpeg": // max clength
2358 this._FBU
.bytes
+= 3;
2360 case "png": // max clength
2361 this._FBU
.bytes
+= 3;
2363 case "filter": // filter id + num colors if palette
2364 this._FBU
.bytes
+= 2;
2370 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2372 // Determine FBU.bytes
2376 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);
2377 this._sock
.rQskipBytes(4);
2381 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2382 var cl_offset
= rQi
+ 1;
2385 cl_data
+= rQ
[cl_offset
] & 0x7f;
2386 if (rQ
[cl_offset
] & 0x80) {
2388 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2389 if (rQ
[cl_offset
+ 1] & 0x80) {
2391 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2394 // end inline getTightCLength
2395 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2396 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2398 // We have everything, render it
2399 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2400 data
= this._sock
.rQshiftBytes(cl_data
);
2401 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2404 var filterId
= rQ
[rQi
+ 1];
2405 if (filterId
=== 1) {
2406 if (!handlePalette()) { return false; }
2408 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2409 // Filter 2, Gradient is valid but not use if jpeg is enabled
2410 this._fail("Unsupported tight subencoding received " +
2411 "(filter: " + filterId
+ ")");
2415 if (!handleCopy()) { return false; }
2420 this._FBU
.bytes
= 0;
2426 last_rect: function () {
2427 this._FBU
.rects
= 0;
2431 ExtendedDesktopSize: function () {
2432 this._FBU
.bytes
= 1;
2433 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2435 var firstUpdate
= !this._supportsSetDesktopSize
;
2436 this._supportsSetDesktopSize
= true;
2438 // Normally we only apply the current resize mode after a
2439 // window resize event. However there is no such trigger on the
2440 // initial connect. And we don't know if the server supports
2441 // resizing until we've gotten here.
2443 this._requestRemoteResize();
2446 var number_of_screens
= this._sock
.rQpeek8();
2448 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2449 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2451 this._sock
.rQskipBytes(1); // number-of-screens
2452 this._sock
.rQskipBytes(3); // padding
2454 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2455 // Save the id and flags of the first screen
2457 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2458 this._sock
.rQskipBytes(2); // x-position
2459 this._sock
.rQskipBytes(2); // y-position
2460 this._sock
.rQskipBytes(2); // width
2461 this._sock
.rQskipBytes(2); // height
2462 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2464 this._sock
.rQskipBytes(16);
2469 * The x-position indicates the reason for the change:
2471 * 0 - server resized on its own
2472 * 1 - this client requested the resize
2473 * 2 - another client requested the resize
2476 // We need to handle errors when we requested the resize.
2477 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2479 // The y-position indicates the status code from the server
2480 switch (this._FBU
.y
) {
2482 msg
= "Resize is administratively prohibited";
2485 msg
= "Out of resources";
2488 msg
= "Invalid screen layout";
2491 msg
= "Unknown reason";
2494 Log
.Warn("Server did not accept the resize request: "
2497 this._resize(this._FBU
.width
, this._FBU
.height
);
2500 this._FBU
.bytes
= 0;
2501 this._FBU
.rects
-= 1;
2505 DesktopSize: function () {
2506 this._resize(this._FBU
.width
, this._FBU
.height
);
2507 this._FBU
.bytes
= 0;
2508 this._FBU
.rects
-= 1;
2512 Cursor: function () {
2513 Log
.Debug(">> set_cursor");
2514 var x
= this._FBU
.x
; // hotspot-x
2515 var y
= this._FBU
.y
; // hotspot-y
2516 var w
= this._FBU
.width
;
2517 var h
= this._FBU
.height
;
2519 var pixelslength
= w
* h
* 4;
2520 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2522 this._FBU
.bytes
= pixelslength
+ masklength
;
2523 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2525 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2526 this._sock
.rQshiftBytes(masklength
),
2529 this._FBU
.bytes
= 0;
2532 Log
.Debug("<< set_cursor");
2536 QEMUExtendedKeyEvent: function () {
2539 // Old Safari doesn't support creating keyboard events
2541 var keyboardEvent
= document
.createEvent("keyboardEvent");
2542 if (keyboardEvent
.code
!== undefined) {
2543 this._qemuExtKeyEventSupported
= true;