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)
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 // How many seconds to wait for a disconnect to finish
29 var DISCONNECT_TIMEOUT
= 3;
31 export default function RFB(target
, url
, options
) {
33 throw Error("Must specify target");
36 throw Error("Must specify URL");
39 this._target
= target
;
43 options
= options
|| {};
44 this._rfb_credentials
= options
.credentials
|| {};
45 this._shared
= 'shared' in options
? !!options
.shared
: true;
46 this._repeaterID
= options
.repeaterID
|| '';
49 this._rfb_connection_state
= '';
50 this._rfb_init_state
= '';
51 this._rfb_auth_scheme
= '';
52 this._rfb_clean_disconnect
= true;
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;
65 this._capabilities
= { power
: false };
67 this._supportsFence
= false;
69 this._supportsContinuousUpdates
= false;
70 this._enabledContinuousUpdates
= false;
72 this._supportsSetDesktopSize
= false;
74 this._screen_flags
= 0;
76 this._qemuExtKeyEventSupported
= false;
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
86 this._disconnTimer
= null; // disconnection timer
87 this._resizeTimeout
= null; // resize rate limiting
89 // Decoder states and stats
90 this._encHandlers
= {};
95 subrects
: 0, // RRE and HEXTILE
106 zlibs
: [] // TIGHT zlib streams
108 for (var i
= 0; i
< 4; i
++) {
109 this._FBU
.zlibs
[i
] = new Inflator();
112 this._destBuff
= null;
113 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
115 this._rre_chunk_sz
= 100;
131 this._mouse_buttonMask
= 0;
132 this._mouse_arr
= [];
133 this._viewportDragging
= false;
134 this._viewportDragPos
= {};
135 this._viewportHasMoved
= false;
137 // Bound event handlers
138 this._eventHandlers
= {
139 focusCanvas
: this._focusCanvas
.bind(this),
140 windowResize
: this._windowResize
.bind(this),
144 Log
.Debug(">> RFB.constructor");
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
);
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);
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);
178 // NB: nothing that needs explicit teardown should be done
179 // before this point, since this can throw an exception
181 this._display
= new Display(this._canvas
);
183 Log
.Error("Display exception: " + exc
);
186 this._display
.onflush
= this._onFlush
.bind(this);
187 this._display
.clear();
189 this._keyboard
= new Keyboard(this._canvas
);
190 this._keyboard
.onkeyevent
= this._handleKeyEvent
.bind(this);
192 this._mouse
= new Mouse(this._canvas
);
193 this._mouse
.onmousebutton
= this._handleMouseButton
.bind(this);
194 this._mouse
.onmousemove
= this._handleMouseMove
.bind(this);
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");
204 this._fail("Unexpected server connection while " +
205 this._rfb_connection_state
);
208 this._sock
.on('close', function (e
) {
209 Log
.Debug("WebSocket on-close event");
212 msg
= "(code: " + e
.code
;
214 msg
+= ", reason: " + e
.reason
;
218 switch (this._rfb_connection_state
) {
220 this._fail("Connection closed " + msg
);
223 // Handle disconnects that were initiated server-side
224 this._updateConnectionState('disconnecting');
225 this._updateConnectionState('disconnected');
227 case 'disconnecting':
228 // Normal disconnection path
229 this._updateConnectionState('disconnected');
232 this._fail("Unexpected server disconnect " +
233 "when already disconnected " + msg
);
236 this._fail("Unexpected server disconnect before connecting " +
240 this._sock
.off('close');
242 this._sock
.on('error', function (e
) {
243 Log
.Warn("WebSocket on-error event");
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'));
250 Log
.Debug("<< RFB.constructor");
254 // ===== PROPERTIES =====
260 get viewOnly() { return this._viewOnly
; },
261 set viewOnly(viewOnly
) {
262 this._viewOnly
= viewOnly
;
264 if (this._rfb_connection_state
=== "connecting" ||
265 this._rfb_connection_state
=== "connected") {
267 this._keyboard
.ungrab();
268 this._mouse
.ungrab();
270 this._keyboard
.grab();
276 get capabilities() { return this._capabilities
; },
278 get touchButton() { return this._mouse
.touchButton
; },
279 set touchButton(button
) { this._mouse
.touchButton
= button
; },
281 _clipViewport
: false,
282 get clipViewport() { return this._clipViewport
; },
283 set clipViewport(viewport
) {
284 this._clipViewport
= viewport
;
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
) {
298 if (!scale
&& this._clipViewport
) {
303 _resizeSession
: false,
304 get resizeSession() { return this._resizeSession
; },
305 set resizeSession(resize
) {
306 this._resizeSession
= resize
;
308 this._requestRemoteResize();
312 // ===== PUBLIC METHODS =====
314 disconnect: function () {
315 this._updateConnectionState('disconnecting');
316 this._sock
.off('error');
317 this._sock
.off('message');
318 this._sock
.off('open');
321 sendCredentials: function (creds
) {
322 this._rfb_credentials
= creds
;
323 setTimeout(this._init_msg
.bind(this), 0);
326 sendCtrlAltDel: function () {
327 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
328 Log
.Info("Sending Ctrl-Alt-Del");
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);
338 machineShutdown: function () {
342 machineReboot: function () {
346 machineReset: function () {
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; }
355 if (down
=== undefined) {
356 this.sendKey(keysym
, code
, true);
357 this.sendKey(keysym
, code
, false);
361 var scancode
= XtScancode
[code
];
363 if (this._qemuExtKeyEventSupported
&& scancode
) {
365 keysym
= keysym
|| 0;
367 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
369 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
374 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
375 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
380 this._canvas
.focus();
387 clipboardPasteFrom: function (text
) {
388 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
389 RFB
.messages
.clientCutText(this._sock
, text
);
392 // ===== PRIVATE METHODS =====
394 _connect: function () {
395 Log
.Debug(">> RFB.connect");
397 Log
.Info("connecting to " + this._url
);
400 // WebSocket.onopen transitions to the RFB init states
401 this._sock
.open(this._url
, ['binary']);
403 if (e
.name
=== 'SyntaxError') {
404 this._fail("Invalid host or port (" + e
+ ")");
406 this._fail("Error when opening socket (" + e
+ ")");
410 // Make our elements part of the page
411 this._target
.appendChild(this._screen
);
413 // Monitor size changes of the screen
414 // FIXME: Use ResizeObserver, or hidden overflow
415 window
.addEventListener('resize', this._eventHandlers
.windowResize
);
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
);
421 Log
.Debug("<< RFB.connect");
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();
434 this._target
.removeChild(this._screen
);
436 if (e
.name
=== 'NotFoundError') {
437 // Some cases where the initial connection fails
438 // can disconnect before the _screen is created
443 clearTimeout(this._resizeTimeout
);
444 Log
.Debug("<< RFB.disconnect");
447 _print_stats: function () {
448 var stats
= this._encStats
;
450 Log
.Info("Encoding stats for this connection:");
451 Object
.keys(stats
).forEach(function (key
) {
453 if (s
[0] + s
[1] > 0) {
454 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
458 Log
.Info("Encoding stats since page load:");
459 Object
.keys(stats
).forEach(function (key
) {
461 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
465 _focusCanvas: function(event
) {
466 // Respect earlier handlers' request to not do side-effects
467 if (event
.defaultPrevented
) {
471 if (!this.focusOnClick
) {
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 () {
486 if (this._resizeSession
) {
487 // Request changing the resolution of the remote display to
488 // the size of the local browser viewport.
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);
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
;
503 if (this._scaleViewport
) {
504 // Disable viewport clipping if we are scaling
508 if (cur_clip
!== new_clip
) {
509 this._display
.clipViewport
= 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();
521 _updateScale: function () {
522 if (!this._scaleViewport
) {
523 this._display
.scale
= 1.0;
525 let size
= this._screenSize();
526 this._display
.autoscale(size
.w
, size
.h
);
528 this._fixScrollbars();
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;
537 if (!this._resizeSession
|| this._viewOnly
||
538 !this._supportsSetDesktopSize
) {
542 let size
= this._screenSize();
543 RFB
.messages
.setDesktopSize(this._sock
, size
.w
, size
.h
,
544 this._screen_id
, this._screen_flags
);
546 Log
.Debug('Requested new desktop size: ' +
547 size
.w
+ 'x' + size
.h
);
550 // Gets the the size of the available screen
551 _screenSize: function () {
552 return { w
: this._screen
.offsetWidth
,
553 h
: this._screen
.offsetHeight
};
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
;
573 * disconnected - permanent state
575 _updateConnectionState: function (state
) {
576 var oldstate
= this._rfb_connection_state
;
578 if (state
=== oldstate
) {
579 Log
.Debug("Already in state '" + state
+ "', ignoring");
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");
589 // Ensure proper transitions before doing anything
592 if (oldstate
!== 'connecting') {
593 Log
.Error("Bad transition to connected state, " +
594 "previous connection state: " + oldstate
);
600 if (oldstate
!== 'disconnecting') {
601 Log
.Error("Bad transition to disconnected state, " +
602 "previous connection state: " + oldstate
);
608 if (oldstate
!== '') {
609 Log
.Error("Bad transition to connecting state, " +
610 "previous connection state: " + oldstate
);
615 case 'disconnecting':
616 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
617 Log
.Error("Bad transition to disconnecting state, " +
618 "previous connection state: " + oldstate
);
624 Log
.Error("Unknown connection state: " + state
);
628 // State change actions
630 this._rfb_connection_state
= state
;
632 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
635 if (this._disconnTimer
&& state
!== 'disconnecting') {
636 Log
.Debug("Clearing disconnect timer");
637 clearTimeout(this._disconnTimer
);
638 this._disconnTimer
= null;
640 // make sure we don't get a double event
641 this._sock
.off('close');
650 var event
= new CustomEvent("connect", { detail
: {} });
651 this.dispatchEvent(event
);
654 case 'disconnecting':
657 this._disconnTimer
= setTimeout(function () {
658 Log
.Error("Disconnection timed out.");
659 this._updateConnectionState('disconnected');
660 }.bind(this), DISCONNECT_TIMEOUT
* 1000);
664 event
= new CustomEvent(
665 "disconnect", { detail
:
666 { clean
: this._rfb_clean_disconnect
} });
667 this.dispatchEvent(event
);
672 /* Print errors and disconnect
674 * The parameter 'details' is used for information that
675 * should be logged but not sent to the user interface.
677 _fail: function (details
) {
678 switch (this._rfb_connection_state
) {
679 case 'disconnecting':
680 Log
.Error("Failed when disconnecting: " + details
);
683 Log
.Error("Failed while connected: " + details
);
686 Log
.Error("Failed when connecting: " + details
);
689 Log
.Error("RFB failure: " + details
);
692 this._rfb_clean_disconnect
= false; //This is sent to the UI
694 // Transition to disconnected without waiting for socket to close
695 this._updateConnectionState('disconnecting');
696 this._updateConnectionState('disconnected');
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
);
708 _handle_message: function () {
709 if (this._sock
.rQlen() === 0) {
710 Log
.Warn("handle_message called on an empty receive queue");
714 switch (this._rfb_connection_state
) {
716 Log
.Error("Got data while disconnected");
720 if (this._flushing
) {
723 if (!this._normal_msg()) {
726 if (this._sock
.rQlen() === 0) {
737 _handleKeyEvent: function (keysym
, code
, down
) {
738 this.sendKey(keysym
, code
, down
);
741 _handleMouseButton: function (x
, y
, down
, bmask
) {
743 this._mouse_buttonMask
|= bmask
;
745 this._mouse_buttonMask
&= ~bmask
;
748 if (this.dragViewport
) {
749 if (down
&& !this._viewportDragging
) {
750 this._viewportDragging
= true;
751 this._viewportDragPos
= {'x': x
, 'y': y
};
752 this._viewportHasMoved
= false;
754 // Skip sending mouse events
757 this._viewportDragging
= false;
759 // If we actually performed a drag then we are done
760 // here and should not send any mouse events
761 if (this._viewportHasMoved
) {
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
),
775 if (this._viewOnly
) { return; } // View only, skip mouse events
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
);
781 _handleMouseMove: function (x
, y
) {
782 if (this._viewportDragging
) {
783 var deltaX
= this._viewportDragPos
.x
- x
;
784 var deltaY
= this._viewportDragPos
.y
- y
;
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);
790 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
791 Math
.abs(deltaY
) > dragThreshold
)) {
792 this._viewportHasMoved
= true;
794 this._viewportDragPos
= {'x': x
, 'y': y
};
795 this._display
.viewportChangePos(deltaX
, deltaY
);
798 // Skip sending mouse events
802 if (this._viewOnly
) { return; } // View only, skip mouse events
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
);
810 _negotiate_protocol_version: function () {
811 if (this._sock
.rQlen() < 12) {
812 return this._fail("Received incomplete protocol version.");
815 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
816 Log
.Info("Server ProtocolVersion: " + sversion
);
819 case "000.000": // UltraVNC repeater
823 case "003.006": // UltraVNC
824 case "003.889": // Apple Remote Desktop
825 this._rfb_version
= 3.3;
828 this._rfb_version
= 3.7;
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;
837 return this._fail("Invalid server version " + sversion
);
841 var repeaterID
= "ID:" + this._repeaterID
;
842 while (repeaterID
.length
< 250) {
845 this._sock
.send_string(repeaterID
);
849 if (this._rfb_version
> this._rfb_max_version
) {
850 this._rfb_version
= this._rfb_max_version
;
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
);
858 this._rfb_init_state
= 'Security';
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
) {
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; }
878 if (num_types
=== 0) {
879 return this._handle_security_failure("no security types");
882 var types
= this._sock
.rQshiftBytes(num_types
);
883 Log
.Debug("Server security types: " + types
);
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
896 return this._fail("Unsupported security types (types: " + types
+ ")");
899 this._sock
.send([this._rfb_auth_scheme
]);
902 if (this._sock
.rQwait("security scheme", 4)) { return false; }
903 this._rfb_auth_scheme
= this._sock
.rQshift32();
906 this._rfb_init_state
= 'Authentication';
907 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
909 return this._init_msg(); // jump to authentication
913 * Get the security failure reason if sent from the server and
914 * send the 'securityfailure' event.
916 * - The optional parameter context can be used to add some extra
917 * context to the log output.
919 * - The optional parameter security_result_status can be used to
920 * add a custom status code to the event.
922 _handle_security_failure: function (context
, security_result_status
) {
924 if (typeof context
=== 'undefined') {
927 context
= " on " + context
;
930 if (typeof security_result_status
=== 'undefined') {
931 security_result_status
= 1; // fail
934 if (this._sock
.rQwait("reason length", 4)) {
937 let strlen
= this._sock
.rQshift32();
941 if (this._sock
.rQwait("reason", strlen
, 8)) { return false; }
942 reason
= this._sock
.rQshiftStr(strlen
);
947 let event
= new CustomEvent(
949 { detail
: { status
: security_result_status
, reason
: reason
} });
950 this.dispatchEvent(event
);
952 return this._fail("Security negotiation failed" + context
+
953 " (reason: " + reason
+ ")");
956 let event
= new CustomEvent(
958 { detail
: { status
: security_result_status
} });
959 this.dispatchEvent(event
);
961 return this._fail("Security negotiation failed" + context
);
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
);
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();
985 _negotiate_std_vnc_auth: function () {
986 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
988 if (!this._rfb_credentials
.password
) {
989 var event
= new CustomEvent("credentialsrequired",
990 { detail
: { types
: ["password"] } });
991 this.dispatchEvent(event
);
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";
1003 _negotiate_tight_tunnels: function (numTunnels
) {
1004 var clientSupportedTunnelTypes
= {
1005 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
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
};
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");
1023 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
1024 return false; // wait until we receive the sub auth count to continue
1026 return this._fail("Server wanted tunnels, but doesn't support " +
1027 "the notunnel type");
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; }
1037 this._rfb_tightvnc
= true;
1039 if (numTunnels
> 0) {
1040 this._negotiate_tight_tunnels(numTunnels
);
1041 return false; // wait until we receive the sub auth to continue
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';
1053 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
1055 var clientSupportedTypes
= {
1060 var serverSupportedTypes
= [];
1062 for (var i
= 0; i
< subAuthCount
; i
++) {
1063 this._sock
.rQshift32(); // capNum
1064 var capabilities
= this._sock
.rQshiftStr(12);
1065 serverSupportedTypes
.push(capabilities
);
1068 for (var authType
in clientSupportedTypes
) {
1069 if (serverSupportedTypes
.indexOf(authType
) != -1) {
1070 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
1073 case 'STDVNOAUTH__': // no auth
1074 this._rfb_init_state
= 'SecurityResult';
1076 case 'STDVVNCAUTH_': // VNC auth
1077 this._rfb_auth_scheme
= 2;
1078 return this._init_msg();
1080 return this._fail("Unsupported tiny auth scheme " +
1081 "(scheme: " + authType
+ ")");
1086 return this._fail("No supported sub-auth types!");
1089 _negotiate_authentication: function () {
1090 switch (this._rfb_auth_scheme
) {
1091 case 0: // connection failed
1092 return this._handle_security_failure("authentication scheme");
1095 if (this._rfb_version
>= 3.8) {
1096 this._rfb_init_state
= 'SecurityResult';
1099 this._rfb_init_state
= 'ClientInitialisation';
1100 return this._init_msg();
1102 case 22: // XVP auth
1103 return this._negotiate_xvp_auth();
1105 case 2: // VNC authentication
1106 return this._negotiate_std_vnc_auth();
1108 case 16: // TightVNC Security Type
1109 return this._negotiate_tight_auth();
1112 return this._fail("Unsupported auth scheme (scheme: " +
1113 this._rfb_auth_scheme
+ ")");
1117 _handle_security_result: function () {
1118 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
1120 let status
= this._sock
.rQshift32();
1122 if (status
=== 0) { // OK
1123 this._rfb_init_state
= 'ClientInitialisation';
1124 Log
.Debug('Authentication OK');
1125 return this._init_msg();
1127 if (this._rfb_version
>= 3.8) {
1128 return this._handle_security_failure("security result", status
);
1130 let event
= new CustomEvent("securityfailure",
1131 { detail
: { status
: status
} });
1132 this.dispatchEvent(event
);
1134 return this._fail("Security handshake failed");
1139 _negotiate_server_init: function () {
1140 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1143 var width
= this._sock
.rQshift16();
1144 var height
= this._sock
.rQshift16();
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();
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
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
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));
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
1176 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1177 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1179 // we don't actually do anything with the capability information that TIGHT sends,
1180 // so we just skip the all of this.
1182 // TIGHT server message capabilities
1183 this._sock.rQskipBytes(16 * numServerMessages);
1185 // TIGHT client message capabilities
1186 this._sock.rQskipBytes(16 * numClientMessages);
1188 // TIGHT encoding capabilities
1189 this._sock.rQskipBytes(16 * numEncodings);
1192 // NB(directxman12): these are down here so that we don't run them multiple times
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);
1205 if (big_endian !== 0) {
1206 Log.Warn("Server native endian is not little endian");
1209 if (red_shift !== 16) {
1210 Log.Warn("Server native red-shift is not 16");
1213 if (blue_shift !== 0) {
1214 Log.Warn("Server native blue-shift is not 0");
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);
1222 this._resize(width, height);
1224 if (!this._viewOnly) { this._keyboard.grab(); }
1225 if (!this._viewOnly) { this._mouse.grab(); }
1227 this._fb_depth = 24;
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.");
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);
1238 this._timing.fbu_rt_start = (new Date()).getTime();
1239 this._timing.pixels = 0;
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();
1245 this._updateConnectionState('connected');
1249 _sendEncodings: function () {
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);
1261 encs.push(encodings.encodingRaw);
1263 // Psuedo-encoding settings
1264 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1265 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
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);
1275 if (supportsCursorURIs() &&
1276 !isTouchDevice && this._fb_depth == 24) {
1277 encs.push(encodings.pseudoEncodingCursor);
1280 RFB.messages.clientEncodings(this._sock, encs);
1283 /* RFB protocol initialization states:
1288 * ClientInitialization - not triggered by server message
1289 * ServerInitialization
1291 _init_msg: function () {
1292 switch (this._rfb_init_state
) {
1293 case 'ProtocolVersion':
1294 return this._negotiate_protocol_version();
1297 return this._negotiate_security();
1299 case 'Authentication':
1300 return this._negotiate_authentication();
1302 case 'SecurityResult':
1303 return this._handle_security_result();
1305 case 'ClientInitialisation':
1306 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1307 this._rfb_init_state
= 'ServerInitialisation';
1310 case 'ServerInitialisation':
1311 return this._negotiate_server_init();
1314 return this._fail("Unknown init state (state: " +
1315 this._rfb_init_state
+ ")");
1319 _handle_set_colour_map_msg: function () {
1320 Log
.Debug("SetColorMapEntries");
1322 return this._fail("Unexpected SetColorMapEntries message");
1325 _handle_server_cut_text: function () {
1326 Log
.Debug("ServerCutText");
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; }
1333 var text
= this._sock
.rQshiftStr(length
);
1335 if (this._viewOnly
) { return true; }
1337 var event
= new CustomEvent("clipboard",
1338 { detail
: { text
: text
} });
1339 this.dispatchEvent(event
);
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();
1350 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1353 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1357 var payload
= this._sock
.rQshiftStr(length
);
1359 this._supportsFence
= true;
1364 * (1<<0) - BlockBefore
1365 * (1<<1) - BlockAfter
1370 if (!(flags
& (1<<31))) {
1371 return this._fail("Unexpected fence response");
1374 // Filter out unsupported flags
1375 // FIXME: support syncNext
1376 flags
&= (1<<0) | (1<<1);
1378 // BlockBefore and BlockAfter are automatically handled by
1379 // the fact that we process each incoming message
1381 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
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();
1394 Log
.Error("XVP Operation Failed");
1397 this._rfb_xvp_ver
= xvp_ver
;
1398 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1399 this._setCapability("power", true);
1402 this._fail("Illegal server XVP message (msg: " + xvp_msg
+ ")");
1409 _normal_msg: function () {
1412 if (this._FBU
.rects
> 0) {
1415 msg_type
= this._sock
.rQshift8();
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
);
1427 case 1: // SetColorMapEntries
1428 return this._handle_set_colour_map_msg();
1432 var event
= new CustomEvent("bell", { detail
: {} });
1433 this.dispatchEvent(event
);
1436 case 3: // ServerCutText
1437 return this._handle_server_cut_text();
1439 case 150: // EndOfContinuousUpdates
1440 var first
= !(this._supportsContinuousUpdates
);
1441 this._supportsContinuousUpdates
= true;
1442 this._enabledContinuousUpdates
= false;
1444 this._enabledContinuousUpdates
= true;
1445 this._updateContinuousUpdates();
1446 Log
.Info("Enabling continuous updates.");
1448 // FIXME: We need to send a framebufferupdaterequest here
1449 // if we add support for turning off continuous updates
1453 case 248: // ServerFence
1454 return this._handle_server_fence_msg();
1457 return this._handle_xvp_msg();
1460 this._fail("Unexpected server message (type " + msg_type
+ ")");
1461 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1466 _onFlush: function() {
1467 this._flushing
= false;
1468 // Resume processing
1469 if (this._sock
.rQlen() > 0) {
1470 this._handle_message();
1474 _framebufferUpdate: function () {
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
));
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();
1498 while (this._FBU
.rects
> 0) {
1499 if (this._rfb_connection_state
!== 'connected') { return false; }
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 */
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);
1514 if (!this._encHandlers
[this._FBU
.encoding
]) {
1515 this._fail("Unsupported encoding (encoding: " +
1516 this._FBU
.encoding
+ ")");
1521 this._timing
.last_fbu
= (new Date()).getTime();
1523 ret
= this._encHandlers
[this._FBU
.encoding
]();
1525 now
= (new Date()).getTime();
1526 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1529 if (!(this._FBU
.encoding
in this._encStats
)) {
1530 this._encStats
[this._FBU
.encoding
] = [0, 0];
1532 this._encStats
[this._FBU
.encoding
][0]++;
1533 this._encStats
[this._FBU
.encoding
][1]++;
1534 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
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
));
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;
1562 if (!ret
) { return ret
; } // need more data
1565 this._display
.flip();
1567 return true; // We finished this FBU
1570 _updateContinuousUpdates: function() {
1571 if (!this._enabledContinuousUpdates
) { return; }
1573 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1574 this._fb_width
, this._fb_height
);
1577 _resize: function(width
, height
) {
1578 this._fb_width
= width
;
1579 this._fb_height
= height
;
1581 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1583 this._display
.resize(this._fb_width
, this._fb_height
);
1585 // Adjust the visible viewport based on the new dimensions
1587 this._updateScale();
1589 this._timing
.fbu_rt_start
= (new Date()).getTime();
1590 this._updateContinuousUpdates();
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
);
1600 Object
.assign(RFB
.prototype, EventTargetMixin
);
1604 keyEvent: function (sock
, keysym
, down
) {
1605 var buff
= sock
._sQ
;
1606 var offset
= sock
._sQlen
;
1608 buff
[offset
] = 4; // msg-type
1609 buff
[offset
+ 1] = down
;
1611 buff
[offset
+ 2] = 0;
1612 buff
[offset
+ 3] = 0;
1614 buff
[offset
+ 4] = (keysym
>> 24);
1615 buff
[offset
+ 5] = (keysym
>> 16);
1616 buff
[offset
+ 6] = (keysym
>> 8);
1617 buff
[offset
+ 7] = keysym
;
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;
1634 var buff
= sock
._sQ
;
1635 var offset
= sock
._sQlen
;
1637 buff
[offset
] = 255; // msg-type
1638 buff
[offset
+ 1] = 0; // sub msg-type
1640 buff
[offset
+ 2] = (down
>> 8);
1641 buff
[offset
+ 3] = down
;
1643 buff
[offset
+ 4] = (keysym
>> 24);
1644 buff
[offset
+ 5] = (keysym
>> 16);
1645 buff
[offset
+ 6] = (keysym
>> 8);
1646 buff
[offset
+ 7] = keysym
;
1648 var RFBkeycode
= getRFBkeycode(keycode
);
1650 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1651 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1652 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1653 buff
[offset
+ 11] = RFBkeycode
;
1659 pointerEvent: function (sock
, x
, y
, mask
) {
1660 var buff
= sock
._sQ
;
1661 var offset
= sock
._sQlen
;
1663 buff
[offset
] = 5; // msg-type
1665 buff
[offset
+ 1] = mask
;
1667 buff
[offset
+ 2] = x
>> 8;
1668 buff
[offset
+ 3] = x
;
1670 buff
[offset
+ 4] = y
>> 8;
1671 buff
[offset
+ 5] = y
;
1677 // TODO(directxman12): make this unicode compatible?
1678 clientCutText: function (sock
, text
) {
1679 var buff
= sock
._sQ
;
1680 var offset
= sock
._sQlen
;
1682 buff
[offset
] = 6; // msg-type
1684 buff
[offset
+ 1] = 0; // padding
1685 buff
[offset
+ 2] = 0; // padding
1686 buff
[offset
+ 3] = 0; // padding
1688 let length
= text
.length
;
1690 buff
[offset
+ 4] = length
>> 24;
1691 buff
[offset
+ 5] = length
>> 16;
1692 buff
[offset
+ 6] = length
>> 8;
1693 buff
[offset
+ 7] = length
;
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.
1701 let remaining
= length
;
1702 while (remaining
> 0) {
1704 let flushSize
= Math
.min(remaining
, (sock
._sQbufferSize
- sock
._sQlen
));
1705 if (flushSize
<= 0) {
1706 this._fail("Clipboard contents could not be sent");
1710 offset
= sock
._sQlen
;
1712 for (let i
= 0; i
< flushSize
; i
++) {
1713 buff
[offset
+ i
] = text
.charCodeAt(textOffset
+ i
);
1716 sock
._sQlen
+= flushSize
;
1719 remaining
-= flushSize
;
1720 textOffset
+= flushSize
;
1724 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1725 var buff
= sock
._sQ
;
1726 var offset
= sock
._sQlen
;
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
;
1735 buff
[offset
+ 6] = 1; // number-of-screens
1736 buff
[offset
+ 7] = 0; // padding
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
;
1760 clientFence: function (sock
, flags
, payload
) {
1761 var buff
= sock
._sQ
;
1762 var offset
= sock
._sQlen
;
1764 buff
[offset
] = 248; // msg-type
1766 buff
[offset
+ 1] = 0; // padding
1767 buff
[offset
+ 2] = 0; // padding
1768 buff
[offset
+ 3] = 0; // padding
1770 buff
[offset
+ 4] = flags
>> 24; // flags
1771 buff
[offset
+ 5] = flags
>> 16;
1772 buff
[offset
+ 6] = flags
>> 8;
1773 buff
[offset
+ 7] = flags
;
1775 var n
= payload
.length
;
1777 buff
[offset
+ 8] = n
; // length
1779 for (var i
= 0; i
< n
; i
++) {
1780 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1783 sock
._sQlen
+= 9 + n
;
1787 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1788 var buff
= sock
._sQ
;
1789 var offset
= sock
._sQlen
;
1791 buff
[offset
] = 150; // msg-type
1792 buff
[offset
+ 1] = enable
; // enable-flag
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
;
1807 pixelFormat: function (sock
, depth
, true_color
) {
1808 var buff
= sock
._sQ
;
1809 var offset
= sock
._sQlen
;
1815 } else if (depth
> 8) {
1821 bits
= Math
.floor(depth
/3);
1823 buff
[offset
] = 0; // msg-type
1825 buff
[offset
+ 1] = 0; // padding
1826 buff
[offset
+ 2] = 0; // padding
1827 buff
[offset
+ 3] = 0; // padding
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
1834 buff
[offset
+ 8] = 0; // red-max
1835 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1837 buff
[offset
+ 10] = 0; // green-max
1838 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1840 buff
[offset
+ 12] = 0; // blue-max
1841 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1843 buff
[offset
+ 14] = bits
* 2; // red-shift
1844 buff
[offset
+ 15] = bits
* 1; // green-shift
1845 buff
[offset
+ 16] = bits
* 0; // blue-shift
1847 buff
[offset
+ 17] = 0; // padding
1848 buff
[offset
+ 18] = 0; // padding
1849 buff
[offset
+ 19] = 0; // padding
1855 clientEncodings: function (sock
, encodings
) {
1856 var buff
= sock
._sQ
;
1857 var offset
= sock
._sQlen
;
1859 buff
[offset
] = 2; // msg-type
1860 buff
[offset
+ 1] = 0; // padding
1862 buff
[offset
+ 2] = encodings
.length
>> 8;
1863 buff
[offset
+ 3] = encodings
.length
;
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;
1876 sock
._sQlen
+= j
- offset
;
1880 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1881 var buff
= sock
._sQ
;
1882 var offset
= sock
._sQlen
;
1884 if (typeof(x
) === "undefined") { x
= 0; }
1885 if (typeof(y
) === "undefined") { y
= 0; }
1887 buff
[offset
] = 3; // msg-type
1888 buff
[offset
+ 1] = incremental
? 1 : 0;
1890 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1891 buff
[offset
+ 3] = x
& 0xFF;
1893 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1894 buff
[offset
+ 5] = y
& 0xFF;
1896 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1897 buff
[offset
+ 7] = w
& 0xFF;
1899 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1900 buff
[offset
+ 9] = h
& 0xFF;
1906 xvpOp: function (sock
, ver
, op
) {
1907 var buff
= sock
._sQ
;
1908 var offset
= sock
._sQlen
;
1910 buff
[offset
] = 250; // msg-type
1911 buff
[offset
+ 1] = 0; // padding
1913 buff
[offset
+ 2] = ver
;
1914 buff
[offset
+ 3] = op
;
1921 RFB
.genDES = function (password
, challenge
) {
1923 for (var i
= 0; i
< password
.length
; i
++) {
1924 passwd
.push(password
.charCodeAt(i
));
1926 return (new DES(passwd
)).encrypt(challenge
);
1929 RFB
.encodingHandlers
= {
1931 if (this._FBU
.lines
=== 0) {
1932 this._FBU
.lines
= this._FBU
.height
;
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);
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;
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
;
1961 if (this._FBU
.lines
> 0) {
1962 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1965 this._FBU
.bytes
= 0;
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
,
1979 this._FBU
.bytes
= 0;
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
);
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
--;
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
;
2008 this._FBU
.bytes
= 0;
2014 HEXTILE: function () {
2015 var rQ
= this._sock
.get_rQ();
2016 var rQi
= this._sock
.get_rQi();
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
;
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: " +
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
);
2044 // Figure out how much we are expecting
2045 if (subencoding
& 0x01) { // Raw
2046 this._FBU
.bytes
+= w
* h
* 4;
2048 if (subencoding
& 0x02) { // Background
2049 this._FBU
.bytes
+= 4;
2051 if (subencoding
& 0x04) { // Foreground
2052 this._FBU
.bytes
+= 4;
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);
2061 this._FBU
.bytes
+= subrects
* 2;
2066 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
2068 // We know the encoding and have a whole tile
2069 this._FBU
.subencoding
= rQ
[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");
2076 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
2078 } else if (this._FBU
.subencoding
& 0x01) { // Raw
2079 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
2080 rQi
+= this._FBU
.bytes
- 1;
2082 if (this._FBU
.subencoding
& 0x02) { // Background
2083 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2086 if (this._FBU
.subencoding
& 0x04) { // Foreground
2087 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2091 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
2092 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
2096 for (var s
= 0; s
< subrects
; s
++) {
2098 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
2099 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2102 color
= this._FBU
.foreground
;
2107 var sy
= (xy
& 0x0f);
2111 var sw
= (wh
>> 4) + 1;
2112 var sh
= (wh
& 0x0f) + 1;
2114 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2117 this._display
.finishTile();
2119 this._sock
.set_rQi(rQi
);
2120 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2121 this._FBU
.bytes
= 0;
2125 if (this._FBU
.tiles
=== 0) {
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; }
2136 var resetStreams
= 0;
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
);
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");
2152 //return uncompressed.data;
2153 return uncompressed
;
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);
2163 /*for (var y = 0; y < height; y++) {
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];
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];
2191 for (var y
= 0; y
< height
; y
++) {
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];
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];
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];
2232 var rQi
= this._sock
.get_rQi();
2233 var rQ
= this._sock
.rQwhole();
2235 var cl_header
, cl_data
;
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; }
2243 var bpp
= (numColors
<= 2) ? 1 : 8;
2244 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2246 if (rowSize
* this._FBU
.height
< 12) {
2249 cl_data
= rowSize
* this._FBU
.height
;
2250 //clength = [0, rowSize * this._FBU.height];
2252 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2253 var cl_offset
= rQi
+ 3 + paletteSize
;
2256 cl_data
+= rQ
[cl_offset
] & 0x7f;
2257 if (rQ
[cl_offset
] & 0x80) {
2259 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2260 if (rQ
[cl_offset
+ 1] & 0x80) {
2262 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2265 // end inline getTightCLength
2268 this._FBU
.bytes
+= cl_header
+ cl_data
;
2269 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
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
);
2278 data
= this._sock
.rQshiftBytes(cl_data
);
2280 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2283 // Convert indexed (palette based) image data to RGB
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);
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);
2297 var handleCopy = function () {
2299 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2300 if (uncompressedSize
< 12) {
2303 cl_data
= uncompressedSize
;
2305 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2306 var cl_offset
= rQi
+ 1;
2309 cl_data
+= rQ
[cl_offset
] & 0x7f;
2310 if (rQ
[cl_offset
] & 0x80) {
2312 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2313 if (rQ
[cl_offset
+ 1] & 0x80) {
2315 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2318 // end inline getTightCLength
2320 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2321 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2323 // Shift ctl, clength off
2324 this._sock
.rQshiftBytes(1 + cl_header
);
2327 data
= this._sock
.rQshiftBytes(cl_data
);
2329 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2332 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2337 var ctl
= this._sock
.rQpeek8();
2339 // Keep tight reset bits
2340 resetStreams
= ctl
& 0xF;
2342 // Figure out filter
2344 streamId
= ctl
& 0x3;
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: " +
2354 if (isTightPNG
&& (ctl
< 0x08)) {
2355 return this._fail("BasicCompression received in TightPNG rect");
2357 if (!isTightPNG
&& (ctl
=== 0x0A)) {
2358 return this._fail("PNG received in standard Tight rect");
2362 // fill use depth because TPIXELs drop the padding byte
2363 case "fill": // TPIXEL
2364 this._FBU
.bytes
+= 3;
2366 case "jpeg": // max clength
2367 this._FBU
.bytes
+= 3;
2369 case "png": // max clength
2370 this._FBU
.bytes
+= 3;
2372 case "filter": // filter id + num colors if palette
2373 this._FBU
.bytes
+= 2;
2379 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2381 // Determine FBU.bytes
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);
2390 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2391 var cl_offset
= rQi
+ 1;
2394 cl_data
+= rQ
[cl_offset
] & 0x7f;
2395 if (rQ
[cl_offset
] & 0x80) {
2397 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2398 if (rQ
[cl_offset
+ 1] & 0x80) {
2400 cl_data
+= rQ
[cl_offset
+ 2] << 14;
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; }
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
);
2413 var filterId
= rQ
[rQi
+ 1];
2414 if (filterId
=== 1) {
2415 if (!handlePalette()) { return false; }
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
+ ")");
2424 if (!handleCopy()) { return false; }
2429 this._FBU
.bytes
= 0;
2435 last_rect: function () {
2436 this._FBU
.rects
= 0;
2440 ExtendedDesktopSize: function () {
2441 this._FBU
.bytes
= 1;
2442 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2444 var firstUpdate
= !this._supportsSetDesktopSize
;
2445 this._supportsSetDesktopSize
= true;
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.
2452 this._requestRemoteResize();
2455 var number_of_screens
= this._sock
.rQpeek8();
2457 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2458 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2460 this._sock
.rQskipBytes(1); // number-of-screens
2461 this._sock
.rQskipBytes(3); // padding
2463 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2464 // Save the id and flags of the first screen
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
2473 this._sock
.rQskipBytes(16);
2478 * The x-position indicates the reason for the change:
2480 * 0 - server resized on its own
2481 * 1 - this client requested the resize
2482 * 2 - another client requested the resize
2485 // We need to handle errors when we requested the resize.
2486 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2488 // The y-position indicates the status code from the server
2489 switch (this._FBU
.y
) {
2491 msg
= "Resize is administratively prohibited";
2494 msg
= "Out of resources";
2497 msg
= "Invalid screen layout";
2500 msg
= "Unknown reason";
2503 Log
.Warn("Server did not accept the resize request: "
2506 this._resize(this._FBU
.width
, this._FBU
.height
);
2509 this._FBU
.bytes
= 0;
2510 this._FBU
.rects
-= 1;
2514 DesktopSize: function () {
2515 this._resize(this._FBU
.width
, this._FBU
.height
);
2516 this._FBU
.bytes
= 0;
2517 this._FBU
.rects
-= 1;
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
;
2528 var pixelslength
= w
* h
* 4;
2529 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2531 this._FBU
.bytes
= pixelslength
+ masklength
;
2532 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2534 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2535 this._sock
.rQshiftBytes(masklength
),
2538 this._FBU
.bytes
= 0;
2541 Log
.Debug("<< set_cursor");
2545 QEMUExtendedKeyEvent: function () {
2548 // Old Safari doesn't support creating keyboard events
2550 var keyboardEvent
= document
.createEvent("keyboardEvent");
2551 if (keyboardEvent
.code
!== undefined) {
2552 this._qemuExtKeyEventSupported
= true;