2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2012 Joel Martin
4 * Copyright (C) 2016 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 _
from './util/localization.js';
15 import { decodeUTF8
} from './util/strings.js';
16 import { set_defaults
, make_properties
} from './util/properties.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 Base64
from "./base64.js";
22 import DES
from "./des.js";
23 import KeyTable
from "./input/keysym.js";
24 import XtScancode
from "./input/xtscancodes.js";
25 import Inflator
from "./inflator.js";
26 import { encodings
, encodingName
} from "./encodings.js";
28 /*jslint white: false, browser: true */
29 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
31 export default function RFB(defaults
) {
38 this._rfb_port
= 5900;
39 this._rfb_password
= '';
42 this._rfb_connection_state
= '';
43 this._rfb_init_state
= '';
44 this._rfb_version
= 0;
45 this._rfb_max_version
= 3.8;
46 this._rfb_auth_scheme
= '';
47 this._rfb_disconnect_reason
= "";
49 this._rfb_tightvnc
= false;
50 this._rfb_xvp_ver
= 0;
52 this._encHandlers
= {};
55 this._sock
= null; // Websock object
56 this._display
= null; // Display object
57 this._flushing
= false; // Display flushing state
58 this._keyboard
= null; // Keyboard input handler object
59 this._mouse
= null; // Mouse input handler object
60 this._disconnTimer
= null; // disconnection timer
62 this._supportsFence
= false;
64 this._supportsContinuousUpdates
= false;
65 this._enabledContinuousUpdates
= false;
67 // Frame buffer update state
81 zlib
: [] // TIGHT zlib streams
88 this._destBuff
= null;
89 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
91 this._rre_chunk_sz
= 100;
106 this._supportsSetDesktopSize
= false;
108 this._screen_flags
= 0;
111 this._mouse_buttonMask
= 0;
112 this._mouse_arr
= [];
113 this._viewportDragging
= false;
114 this._viewportDragPos
= {};
115 this._viewportHasMoved
= false;
117 // QEMU Extended Key Event support - default to false
118 this._qemuExtKeyEventSupported
= false;
120 // set the default value on user-facing properties
121 set_defaults(this, defaults
, {
122 'target': 'null', // VNC display rendering Canvas object
123 'encrypt': false, // Use TLS/SSL/wss encryption
124 'local_cursor': false, // Request locally rendered cursor
125 'shared': true, // Request shared mode
126 'view_only': false, // Disable client mouse/keyboard
127 'focus_on_click': true, // Grab focus on canvas on mouse click
128 'xvp_password_sep': '@', // Separator for XVP password fields
129 'disconnectTimeout': 3, // Time (s) to wait for disconnection
130 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
131 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
132 'viewportDrag': false, // Move the viewport on mouse drags
134 // Callback functions
135 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
136 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
137 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
138 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
139 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
140 'onBell': function () { }, // onBell(rfb): RFB Bell message received
141 'onFBUReceive': function () { }, // onFBUReceive(rfb, rect): RFB FBU rect received but not yet processed
142 'onFBUComplete': function () { }, // onFBUComplete(rfb): RFB FBU received and processed
143 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
144 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
145 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
148 // Bound event handlers
149 this._eventHandlers
= {
150 focusCanvas
: this._focusCanvas
.bind(this),
154 Log
.Debug(">> RFB.constructor");
156 // Target canvas must be able to have focus
157 if (!this._target
.hasAttribute('tabindex')) {
158 this._target
.tabIndex
= -1;
161 // populate encHandlers with bound versions
162 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
163 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
164 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
165 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
166 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
168 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
169 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
170 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
171 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
172 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
174 // NB: nothing that needs explicit teardown should be done
175 // before this point, since this can throw an exception
177 this._display
= new Display({target
: this._target
,
178 onFlush
: this._onFlush
.bind(this)});
180 Log
.Error("Display exception: " + exc
);
184 this._keyboard
= new Keyboard({target
: this._target
,
185 onKeyEvent
: this._handleKeyEvent
.bind(this)});
187 this._mouse
= new Mouse({target
: this._target
,
188 onMouseButton
: this._handleMouseButton
.bind(this),
189 onMouseMove
: this._handleMouseMove
.bind(this)});
191 this._sock
= new Websock();
192 this._sock
.on('message', this._handle_message
.bind(this));
193 this._sock
.on('open', function () {
194 if ((this._rfb_connection_state
=== 'connecting') &&
195 (this._rfb_init_state
=== '')) {
196 this._rfb_init_state
= 'ProtocolVersion';
197 Log
.Debug("Starting VNC handshake");
199 this._fail("Unexpected server connection");
202 this._sock
.on('close', function (e
) {
203 Log
.Warn("WebSocket on-close event");
206 msg
= " (code: " + e
.code
;
208 msg
+= ", reason: " + e
.reason
;
212 switch (this._rfb_connection_state
) {
213 case 'disconnecting':
214 this._updateConnectionState('disconnected');
217 this._fail('Failed to connect to server', msg
);
220 // Handle disconnects that were initiated server-side
221 this._updateConnectionState('disconnecting');
222 this._updateConnectionState('disconnected');
225 this._fail("Unexpected server disconnect",
226 "Already disconnected: " + msg
);
229 this._fail("Unexpected server disconnect",
230 "Not in any state yet: " + msg
);
233 this._sock
.off('close');
235 this._sock
.on('error', function (e
) {
236 Log
.Warn("WebSocket on-error event");
242 var rmode
= this._display
.get_render_mode();
243 Log
.Info("Using native WebSockets, render mode: " + rmode
);
245 Log
.Debug("<< RFB.constructor");
250 connect: function (host
, port
, password
, path
) {
251 this._rfb_host
= host
;
252 this._rfb_port
= port
;
253 this._rfb_password
= (password
!== undefined) ? password
: "";
254 this._rfb_path
= (path
!== undefined) ? path
: "";
256 if (!this._rfb_host
) {
261 this._rfb_init_state
= '';
262 this._updateConnectionState('connecting');
266 disconnect: function () {
267 this._updateConnectionState('disconnecting');
268 this._sock
.off('error');
269 this._sock
.off('message');
270 this._sock
.off('open');
273 sendPassword: function (passwd
) {
274 this._rfb_password
= passwd
;
275 setTimeout(this._init_msg
.bind(this), 0);
278 sendCtrlAltDel: function () {
279 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
280 Log
.Info("Sending Ctrl-Alt-Del");
282 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
283 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
284 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
285 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
286 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
287 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
292 xvpOp: function (ver
, op
) {
293 if (this._rfb_xvp_ver
< ver
) { return false; }
294 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
295 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
299 xvpShutdown: function () {
300 return this.xvpOp(1, 2);
303 xvpReboot: function () {
304 return this.xvpOp(1, 3);
307 xvpReset: function () {
308 return this.xvpOp(1, 4);
311 // Send a key press. If 'down' is not specified then send a down key
312 // followed by an up key.
313 sendKey: function (keysym
, code
, down
) {
314 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
316 if (down
=== undefined) {
317 this.sendKey(keysym
, code
, true);
318 this.sendKey(keysym
, code
, false);
322 var scancode
= XtScancode
[code
];
324 if (this._qemuExtKeyEventSupported
&& scancode
) {
326 keysym
= keysym
|| 0;
328 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
330 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
335 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
336 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
342 clipboardPasteFrom: function (text
) {
343 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
344 RFB
.messages
.clientCutText(this._sock
, text
);
347 // Requests a change of remote desktop size. This message is an extension
348 // and may only be sent if we have received an ExtendedDesktopSize message
349 requestDesktopSize: function (width
, height
) {
350 if (this._rfb_connection_state
!== 'connected' ||
355 if (this._supportsSetDesktopSize
) {
356 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
357 this._screen_id
, this._screen_flags
);
368 _connect: function () {
369 Log
.Debug(">> RFB.connect");
373 if (typeof UsingSocketIO
!== 'undefined') {
376 uri
= this._encrypt
? 'wss' : 'ws';
379 uri
+= '://' + this._rfb_host
;
381 uri
+= ':' + this._rfb_port
;
383 uri
+= '/' + this._rfb_path
;
385 Log
.Info("connecting to " + uri
);
388 // WebSocket.onopen transitions to the RFB init states
389 this._sock
.open(uri
, this._wsProtocols
);
391 if (e
.name
=== 'SyntaxError') {
392 this._fail("Invalid host or port value given", e
);
394 this._fail("Error while connecting", e
);
398 // Always grab focus on some kind of click event
399 this._target
.addEventListener("mousedown", this._eventHandlers
.focusCanvas
);
400 this._target
.addEventListener("touchstart", this._eventHandlers
.focusCanvas
);
402 Log
.Debug("<< RFB.connect");
405 _disconnect: function () {
406 Log
.Debug(">> RFB.disconnect");
407 this._target
.removeEventListener("mousedown", this._eventHandlers
.focusCanvas
);
408 this._target
.removeEventListener("touchstart", this._eventHandlers
.focusCanvas
);
412 Log
.Debug("<< RFB.disconnect");
415 _init_vars: function () {
418 this._FBU
.subrects
= 0; // RRE and HEXTILE
419 this._FBU
.lines
= 0; // RAW
420 this._FBU
.tiles
= 0; // HEXTILE
421 this._FBU
.zlibs
= []; // TIGHT zlib encoders
422 this._mouse_buttonMask
= 0;
423 this._mouse_arr
= [];
424 this._rfb_tightvnc
= false;
426 // Clear the per connection encoding stats
427 var stats
= this._encStats
;
428 Object
.keys(stats
).forEach(function (key
) {
433 for (i
= 0; i
< 4; i
++) {
434 this._FBU
.zlibs
[i
] = new Inflator();
438 _print_stats: function () {
439 var stats
= this._encStats
;
441 Log
.Info("Encoding stats for this connection:");
442 Object
.keys(stats
).forEach(function (key
) {
444 if (s
[0] + s
[1] > 0) {
445 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
449 Log
.Info("Encoding stats since page load:");
450 Object
.keys(stats
).forEach(function (key
) {
452 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
456 _cleanup: function () {
457 if (!this._view_only
) { this._keyboard
.ungrab(); }
458 if (!this._view_only
) { this._mouse
.ungrab(); }
459 this._display
.defaultCursor();
460 if (Log
.get_logging() !== 'debug') {
461 // Show noVNC logo on load and when disconnected, unless in
463 this._display
.clear();
467 _focusCanvas: function(event
) {
468 // Respect earlier handlers' request to not do side-effects
469 if (event
.defaultPrevented
) {
473 if (!this._focus_on_click
) {
477 this._target
.focus();
485 * disconnected - permanent state
487 _updateConnectionState: function (state
) {
488 var oldstate
= this._rfb_connection_state
;
490 if (state
=== oldstate
) {
491 Log
.Debug("Already in state '" + state
+ "', ignoring");
495 // The 'disconnected' state is permanent for each RFB object
496 if (oldstate
=== 'disconnected') {
497 Log
.Error("Tried changing state of a disconnected RFB object");
501 // Ensure proper transitions before doing anything
504 if (oldstate
!== 'connecting') {
505 Log
.Error("Bad transition to connected state, " +
506 "previous connection state: " + oldstate
);
512 if (oldstate
!== 'disconnecting') {
513 Log
.Error("Bad transition to disconnected state, " +
514 "previous connection state: " + oldstate
);
520 if (oldstate
!== '') {
521 Log
.Error("Bad transition to connecting state, " +
522 "previous connection state: " + oldstate
);
527 case 'disconnecting':
528 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
529 Log
.Error("Bad transition to disconnecting state, " +
530 "previous connection state: " + oldstate
);
536 Log
.Error("Unknown connection state: " + state
);
540 // State change actions
542 this._rfb_connection_state
= state
;
543 this._onUpdateState(this, state
, oldstate
);
545 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
548 if (this._disconnTimer
&& state
!== 'disconnecting') {
549 Log
.Debug("Clearing disconnect timer");
550 clearTimeout(this._disconnTimer
);
551 this._disconnTimer
= null;
553 // make sure we don't get a double event
554 this._sock
.off('close');
559 // Call onDisconnected callback after onUpdateState since
560 // we don't know if the UI only displays the latest message
561 if (this._rfb_disconnect_reason
!== "") {
562 this._onDisconnected(this, this._rfb_disconnect_reason
);
564 // No reason means clean disconnect
565 this._onDisconnected(this);
573 case 'disconnecting':
576 this._disconnTimer
= setTimeout(function () {
577 this._rfb_disconnect_reason
= _("Disconnect timeout");
578 this._updateConnectionState('disconnected');
579 }.bind(this), this._disconnectTimeout
* 1000);
584 /* Print errors and disconnect
586 * The optional parameter 'details' is used for information that
587 * should be logged but not sent to the user interface.
589 _fail: function (msg
, details
) {
591 if (typeof details
!== 'undefined') {
592 fullmsg
= msg
+ " (" + details
+ ")";
594 switch (this._rfb_connection_state
) {
595 case 'disconnecting':
596 Log
.Error("Failed when disconnecting: " + fullmsg
);
599 Log
.Error("Failed while connected: " + fullmsg
);
602 Log
.Error("Failed when connecting: " + fullmsg
);
605 Log
.Error("RFB failure: " + fullmsg
);
608 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
610 // Transition to disconnected without waiting for socket to close
611 this._updateConnectionState('disconnecting');
612 this._updateConnectionState('disconnected');
618 * Send a notification to the UI. Valid levels are:
619 * 'normal'|'warn'|'error'
621 * NOTE: Options could be added in the future.
622 * NOTE: If this function is called multiple times, remember that the
623 * interface could be only showing the latest notification.
625 _notification: function(msg
, level
, options
) {
630 Log
.Debug("Notification[" + level
+ "]:" + msg
);
633 Log
.Error("Invalid notification level: " + level
);
638 this._onNotification(this, msg
, level
, options
);
640 this._onNotification(this, msg
, level
);
644 _handle_message: function () {
645 if (this._sock
.rQlen() === 0) {
646 Log
.Warn("handle_message called on an empty receive queue");
650 switch (this._rfb_connection_state
) {
652 Log
.Error("Got data while disconnected");
656 if (this._flushing
) {
659 if (!this._normal_msg()) {
662 if (this._sock
.rQlen() === 0) {
673 _handleKeyEvent: function (keysym
, code
, down
) {
674 this.sendKey(keysym
, code
, down
);
677 _handleMouseButton: function (x
, y
, down
, bmask
) {
679 this._mouse_buttonMask
|= bmask
;
681 this._mouse_buttonMask
&= ~bmask
;
684 if (this._viewportDrag
) {
685 if (down
&& !this._viewportDragging
) {
686 this._viewportDragging
= true;
687 this._viewportDragPos
= {'x': x
, 'y': y
};
689 // Skip sending mouse events
692 this._viewportDragging
= false;
694 // If the viewport didn't actually move, then treat as a mouse click event
695 // Send the button down event here, as the button up event is sent at the end of this function
696 if (!this._viewportHasMoved
&& !this._view_only
) {
697 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
699 this._viewportHasMoved
= false;
703 if (this._view_only
) { return; } // View only, skip mouse events
705 if (this._rfb_connection_state
!== 'connected') { return; }
706 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
709 _handleMouseMove: function (x
, y
) {
710 if (this._viewportDragging
) {
711 var deltaX
= this._viewportDragPos
.x
- x
;
712 var deltaY
= this._viewportDragPos
.y
- y
;
714 // The goal is to trigger on a certain physical width, the
715 // devicePixelRatio brings us a bit closer but is not optimal.
716 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
718 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
719 Math
.abs(deltaY
) > dragThreshold
)) {
720 this._viewportHasMoved
= true;
722 this._viewportDragPos
= {'x': x
, 'y': y
};
723 this._display
.viewportChangePos(deltaX
, deltaY
);
726 // Skip sending mouse events
730 if (this._view_only
) { return; } // View only, skip mouse events
732 if (this._rfb_connection_state
!== 'connected') { return; }
733 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
738 _negotiate_protocol_version: function () {
739 if (this._sock
.rQlen() < 12) {
740 return this._fail("Error while negotiating with server",
741 "Incomplete protocol version");
744 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
745 Log
.Info("Server ProtocolVersion: " + sversion
);
748 case "000.000": // UltraVNC repeater
752 case "003.006": // UltraVNC
753 case "003.889": // Apple Remote Desktop
754 this._rfb_version
= 3.3;
757 this._rfb_version
= 3.7;
760 case "004.000": // Intel AMT KVM
761 case "004.001": // RealVNC 4.6
762 case "005.000": // RealVNC 5.3
763 this._rfb_version
= 3.8;
766 return this._fail("Unsupported server",
767 "Invalid server version: " + sversion
);
771 var repeaterID
= this._repeaterID
;
772 while (repeaterID
.length
< 250) {
775 this._sock
.send_string(repeaterID
);
779 if (this._rfb_version
> this._rfb_max_version
) {
780 this._rfb_version
= this._rfb_max_version
;
783 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
784 ".00" + ((this._rfb_version
* 10) % 10);
785 this._sock
.send_string("RFB " + cversion
+ "\n");
786 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
788 this._rfb_init_state
= 'Security';
791 _negotiate_security: function () {
792 // Polyfill since IE and PhantomJS doesn't have
793 // TypedArray.includes()
794 function includes(item
, array
) {
795 for (var i
= 0; i
< array
.length
; i
++) {
796 if (array
[i
] === item
) {
803 if (this._rfb_version
>= 3.7) {
804 // Server sends supported list, client decides
805 var num_types
= this._sock
.rQshift8();
806 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
808 if (num_types
=== 0) {
809 var strlen
= this._sock
.rQshift32();
810 var reason
= this._sock
.rQshiftStr(strlen
);
811 return this._fail("Error while negotiating with server",
812 "Security failure: " + reason
);
815 var types
= this._sock
.rQshiftBytes(num_types
);
816 Log
.Debug("Server security types: " + types
);
818 // Look for each auth in preferred order
819 this._rfb_auth_scheme
= 0;
820 if (includes(1, types
)) {
821 this._rfb_auth_scheme
= 1; // None
822 } else if (includes(22, types
)) {
823 this._rfb_auth_scheme
= 22; // XVP
824 } else if (includes(16, types
)) {
825 this._rfb_auth_scheme
= 16; // Tight
826 } else if (includes(2, types
)) {
827 this._rfb_auth_scheme
= 2; // VNC Auth
829 return this._fail("Unsupported server",
830 "Unsupported security types: " + types
);
833 this._sock
.send([this._rfb_auth_scheme
]);
836 if (this._sock
.rQwait("security scheme", 4)) { return false; }
837 this._rfb_auth_scheme
= this._sock
.rQshift32();
840 this._rfb_init_state
= 'Authentication';
841 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
843 return this._init_msg(); // jump to authentication
847 _negotiate_xvp_auth: function () {
848 var xvp_sep
= this._xvp_password_sep
;
849 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
850 if (xvp_auth
.length
< 3) {
851 var msg
= 'XVP credentials required (user' + xvp_sep
+
852 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
853 this._onPasswordRequired(this, msg
);
857 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
858 String
.fromCharCode(xvp_auth
[1].length
) +
861 this._sock
.send_string(xvp_auth_str
);
862 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
863 this._rfb_auth_scheme
= 2;
864 return this._negotiate_authentication();
867 _negotiate_std_vnc_auth: function () {
868 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
870 if (this._rfb_password
.length
=== 0) {
871 this._onPasswordRequired(this);
875 // TODO(directxman12): make genDES not require an Array
876 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
877 var response
= RFB
.genDES(this._rfb_password
, challenge
);
878 this._sock
.send(response
);
879 this._rfb_init_state
= "SecurityResult";
883 _negotiate_tight_tunnels: function (numTunnels
) {
884 var clientSupportedTunnelTypes
= {
885 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
887 var serverSupportedTunnelTypes
= {};
888 // receive tunnel capabilities
889 for (var i
= 0; i
< numTunnels
; i
++) {
890 var cap_code
= this._sock
.rQshift32();
891 var cap_vendor
= this._sock
.rQshiftStr(4);
892 var cap_signature
= this._sock
.rQshiftStr(8);
893 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
896 // choose the notunnel type
897 if (serverSupportedTunnelTypes
[0]) {
898 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
899 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
900 return this._fail("Unsupported server",
901 "Client's tunnel type had the incorrect " +
902 "vendor or signature");
904 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
905 return false; // wait until we receive the sub auth count to continue
907 return this._fail("Unsupported server",
908 "Server wanted tunnels, but doesn't support " +
909 "the notunnel type");
913 _negotiate_tight_auth: function () {
914 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
915 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
916 var numTunnels
= this._sock
.rQshift32();
917 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
919 this._rfb_tightvnc
= true;
921 if (numTunnels
> 0) {
922 this._negotiate_tight_tunnels(numTunnels
);
923 return false; // wait until we receive the sub auth to continue
927 // second pass, do the sub-auth negotiation
928 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
929 var subAuthCount
= this._sock
.rQshift32();
930 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
931 this._rfb_init_state
= 'SecurityResult';
935 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
937 var clientSupportedTypes
= {
942 var serverSupportedTypes
= [];
944 for (var i
= 0; i
< subAuthCount
; i
++) {
945 var capNum
= this._sock
.rQshift32();
946 var capabilities
= this._sock
.rQshiftStr(12);
947 serverSupportedTypes
.push(capabilities
);
950 for (var authType
in clientSupportedTypes
) {
951 if (serverSupportedTypes
.indexOf(authType
) != -1) {
952 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
955 case 'STDVNOAUTH__': // no auth
956 this._rfb_init_state
= 'SecurityResult';
958 case 'STDVVNCAUTH_': // VNC auth
959 this._rfb_auth_scheme
= 2;
960 return this._init_msg();
962 return this._fail("Unsupported server",
963 "Unsupported tiny auth scheme: " +
969 return this._fail("Unsupported server",
970 "No supported sub-auth types!");
973 _negotiate_authentication: function () {
974 switch (this._rfb_auth_scheme
) {
975 case 0: // connection failed
976 if (this._sock
.rQwait("auth reason", 4)) { return false; }
977 var strlen
= this._sock
.rQshift32();
978 var reason
= this._sock
.rQshiftStr(strlen
);
979 return this._fail("Authentication failure", reason
);
982 if (this._rfb_version
>= 3.8) {
983 this._rfb_init_state
= 'SecurityResult';
986 this._rfb_init_state
= 'ClientInitialisation';
987 return this._init_msg();
990 return this._negotiate_xvp_auth();
992 case 2: // VNC authentication
993 return this._negotiate_std_vnc_auth();
995 case 16: // TightVNC Security Type
996 return this._negotiate_tight_auth();
999 return this._fail("Unsupported server",
1000 "Unsupported auth scheme: " +
1001 this._rfb_auth_scheme
);
1005 _handle_security_result: function () {
1006 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
1007 switch (this._sock
.rQshift32()) {
1009 this._rfb_init_state
= 'ClientInitialisation';
1010 Log
.Debug('Authentication OK');
1011 return this._init_msg();
1013 if (this._rfb_version
>= 3.8) {
1014 var length
= this._sock
.rQshift32();
1015 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
1016 var reason
= this._sock
.rQshiftStr(length
);
1017 return this._fail("Authentication failure", reason
);
1019 return this._fail("Authentication failure");
1022 return this._fail("Too many authentication attempts");
1024 return this._fail("Unsupported server",
1025 "Unknown SecurityResult");
1029 _negotiate_server_init: function () {
1030 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1033 var width
= this._sock
.rQshift16();
1034 var height
= this._sock
.rQshift16();
1037 var bpp
= this._sock
.rQshift8();
1038 var depth
= this._sock
.rQshift8();
1039 var big_endian
= this._sock
.rQshift8();
1040 var true_color
= this._sock
.rQshift8();
1042 var red_max
= this._sock
.rQshift16();
1043 var green_max
= this._sock
.rQshift16();
1044 var blue_max
= this._sock
.rQshift16();
1045 var red_shift
= this._sock
.rQshift8();
1046 var green_shift
= this._sock
.rQshift8();
1047 var blue_shift
= this._sock
.rQshift8();
1048 this._sock
.rQskipBytes(3); // padding
1050 // NB(directxman12): we don't want to call any callbacks or print messages until
1051 // *after* we're past the point where we could backtrack
1053 /* Connection name/title */
1054 var name_length = this._sock.rQshift32();
1055 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1056 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1058 if (this._rfb_tightvnc) {
1059 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1060 // In TightVNC mode, ServerInit message is extended
1061 var numServerMessages = this._sock.rQshift16();
1062 var numClientMessages = this._sock.rQshift16();
1063 var numEncodings = this._sock.rQshift16();
1064 this._sock.rQskipBytes(2); // padding
1066 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1067 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1069 // we don't actually do anything with the capability information that TIGHT sends,
1070 // so we just skip the all of this.
1072 // TIGHT server message capabilities
1073 this._sock.rQskipBytes(16 * numServerMessages);
1075 // TIGHT client message capabilities
1076 this._sock.rQskipBytes(16 * numClientMessages);
1078 // TIGHT encoding capabilities
1079 this._sock.rQskipBytes(16 * numEncodings);
1082 // NB(directxman12): these are down here so that we don't run them multiple times
1084 Log.Info("Screen: " + width + "x" + height +
1085 ", bpp: " + bpp + ", depth: " + depth +
1086 ", big_endian: " + big_endian +
1087 ", true_color: " + true_color +
1088 ", red_max: " + red_max +
1089 ", green_max: " + green_max +
1090 ", blue_max: " + blue_max +
1091 ", red_shift: " + red_shift +
1092 ", green_shift: " + green_shift +
1093 ", blue_shift: " + blue_shift);
1095 if (big_endian !== 0) {
1096 Log.Warn("Server native endian is not little endian");
1099 if (red_shift !== 16) {
1100 Log.Warn("Server native red-shift is not 16");
1103 if (blue_shift !== 0) {
1104 Log.Warn("Server native blue-shift is not 0");
1107 // we're past the point where we could backtrack, so it's safe to call this
1108 this._onDesktopName(this, this._fb_name);
1110 this._resize(width, height);
1112 if (!this._view_only) { this._keyboard.grab(); }
1113 if (!this._view_only) { this._mouse.grab(); }
1115 this._fb_depth = 24;
1117 if (this._fb_name === "Intel(r) AMT KVM") {
1118 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1122 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1123 this._sendEncodings();
1124 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1126 this._timing.fbu_rt_start = (new Date()).getTime();
1127 this._timing.pixels = 0;
1129 // Cursor will be server side until the server decides to honor
1130 // our request and send over the cursor image
1131 this._display.disableLocalCursor();
1133 this._updateConnectionState('connected');
1137 _sendEncodings: function () {
1140 // In preference order
1141 encs.push(encodings.encodingCopyRect);
1142 // Only supported with full depth support
1143 if (this._fb_depth == 24) {
1144 encs.push(encodings.encodingTight);
1145 encs.push(encodings.encodingHextile);
1146 encs.push(encodings.encodingRRE);
1148 encs.push(encodings.encodingRaw);
1150 // Psuedo-encoding settings
1151 encs.push(encodings.pseudoEncodingTightPNG);
1152 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1153 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1155 encs.push(encodings.pseudoEncodingDesktopSize);
1156 encs.push(encodings.pseudoEncodingLastRect);
1157 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1158 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1159 encs.push(encodings.pseudoEncodingXvp);
1160 encs.push(encodings.pseudoEncodingFence);
1161 encs.push(encodings.pseudoEncodingContinuousUpdates);
1163 if (this._local_cursor && this._fb_depth == 24) {
1164 encs.push(encodings.pseudoEncodingCursor);
1167 RFB.messages.clientEncodings(this._sock, encs);
1170 /* RFB protocol initialization states:
1175 * ClientInitialization - not triggered by server message
1176 * ServerInitialization
1178 _init_msg: function () {
1179 switch (this._rfb_init_state
) {
1180 case 'ProtocolVersion':
1181 return this._negotiate_protocol_version();
1184 return this._negotiate_security();
1186 case 'Authentication':
1187 return this._negotiate_authentication();
1189 case 'SecurityResult':
1190 return this._handle_security_result();
1192 case 'ClientInitialisation':
1193 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1194 this._rfb_init_state
= 'ServerInitialisation';
1197 case 'ServerInitialisation':
1198 return this._negotiate_server_init();
1201 return this._fail("Internal error", "Unknown init state: " +
1202 this._rfb_init_state
);
1206 _handle_set_colour_map_msg: function () {
1207 Log
.Debug("SetColorMapEntries");
1209 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1212 _handle_server_cut_text: function () {
1213 Log
.Debug("ServerCutText");
1215 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1216 this._sock
.rQskipBytes(3); // Padding
1217 var length
= this._sock
.rQshift32();
1218 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1220 var text
= this._sock
.rQshiftStr(length
);
1222 if (this._view_only
) { return true; }
1224 this._onClipboard(this, text
);
1229 _handle_server_fence_msg: function() {
1230 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1231 this._sock
.rQskipBytes(3); // Padding
1232 var flags
= this._sock
.rQshift32();
1233 var length
= this._sock
.rQshift8();
1235 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1238 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1242 var payload
= this._sock
.rQshiftStr(length
);
1244 this._supportsFence
= true;
1249 * (1<<0) - BlockBefore
1250 * (1<<1) - BlockAfter
1255 if (!(flags
& (1<<31))) {
1256 return this._fail("Internal error",
1257 "Unexpected fence response");
1260 // Filter out unsupported flags
1261 // FIXME: support syncNext
1262 flags
&= (1<<0) | (1<<1);
1264 // BlockBefore and BlockAfter are automatically handled by
1265 // the fact that we process each incoming message
1267 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1272 _handle_xvp_msg: function () {
1273 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1274 this._sock
.rQskip8(); // Padding
1275 var xvp_ver
= this._sock
.rQshift8();
1276 var xvp_msg
= this._sock
.rQshift8();
1280 Log
.Error("Operation Failed");
1281 this._notification("XVP Operation Failed", 'error');
1284 this._rfb_xvp_ver
= xvp_ver
;
1285 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1286 this._onXvpInit(this._rfb_xvp_ver
);
1289 this._fail("Unexpected server message",
1290 "Illegal server XVP message " + xvp_msg
);
1297 _normal_msg: function () {
1300 if (this._FBU
.rects
> 0) {
1303 msg_type
= this._sock
.rQshift8();
1307 case 0: // FramebufferUpdate
1308 var ret
= this._framebufferUpdate();
1309 if (ret
&& !this._enabledContinuousUpdates
) {
1310 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1311 this._fb_width
, this._fb_height
);
1315 case 1: // SetColorMapEntries
1316 return this._handle_set_colour_map_msg();
1323 case 3: // ServerCutText
1324 return this._handle_server_cut_text();
1326 case 150: // EndOfContinuousUpdates
1327 var first
= !(this._supportsContinuousUpdates
);
1328 this._supportsContinuousUpdates
= true;
1329 this._enabledContinuousUpdates
= false;
1331 this._enabledContinuousUpdates
= true;
1332 this._updateContinuousUpdates();
1333 Log
.Info("Enabling continuous updates.");
1335 // FIXME: We need to send a framebufferupdaterequest here
1336 // if we add support for turning off continuous updates
1340 case 248: // ServerFence
1341 return this._handle_server_fence_msg();
1344 return this._handle_xvp_msg();
1347 this._fail("Unexpected server message", "Type:" + msg_type
);
1348 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1353 _onFlush: function() {
1354 this._flushing
= false;
1355 // Resume processing
1356 if (this._sock
.rQlen() > 0) {
1357 this._handle_message();
1361 _framebufferUpdate: function () {
1365 if (this._FBU
.rects
=== 0) {
1366 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1367 this._sock
.rQskip8(); // Padding
1368 this._FBU
.rects
= this._sock
.rQshift16();
1369 this._FBU
.bytes
= 0;
1370 this._timing
.cur_fbu
= 0;
1371 if (this._timing
.fbu_rt_start
> 0) {
1372 now
= (new Date()).getTime();
1373 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1376 // Make sure the previous frame is fully rendered first
1377 // to avoid building up an excessive queue
1378 if (this._display
.pending()) {
1379 this._flushing
= true;
1380 this._display
.flush();
1385 while (this._FBU
.rects
> 0) {
1386 if (this._rfb_connection_state
!== 'connected') { return false; }
1388 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1389 if (this._FBU
.bytes
=== 0) {
1390 if (this._sock
.rQwait("rect header", 12)) { return false; }
1391 /* New FramebufferUpdate */
1393 var hdr
= this._sock
.rQshiftBytes(12);
1394 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1395 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1396 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1397 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1398 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1399 (hdr
[10] << 8) + hdr
[11], 10);
1401 this._onFBUReceive(this,
1402 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1403 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1404 'encoding': this._FBU
.encoding
,
1405 'encodingName': encodingName(this._FBU
.encoding
)});
1407 if (!this._encHandlers
[this._FBU
.encoding
]) {
1408 this._fail("Unexpected server message",
1409 "Unsupported encoding " +
1410 this._FBU
.encoding
);
1415 this._timing
.last_fbu
= (new Date()).getTime();
1417 ret
= this._encHandlers
[this._FBU
.encoding
]();
1419 now
= (new Date()).getTime();
1420 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1423 if (!(this._FBU
.encoding
in this._encStats
)) {
1424 this._encStats
[this._FBU
.encoding
] = [0, 0];
1426 this._encStats
[this._FBU
.encoding
][0]++;
1427 this._encStats
[this._FBU
.encoding
][1]++;
1428 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1431 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1432 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1433 this._timing
.fbu_rt_start
> 0) {
1434 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1435 this._timing
.full_fbu_cnt
++;
1436 Log
.Info("Timing of full FBU, curr: " +
1437 this._timing
.cur_fbu
+ ", total: " +
1438 this._timing
.full_fbu_total
+ ", cnt: " +
1439 this._timing
.full_fbu_cnt
+ ", avg: " +
1440 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1443 if (this._timing
.fbu_rt_start
> 0) {
1444 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1445 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1446 this._timing
.fbu_rt_cnt
++;
1447 Log
.Info("full FBU round-trip, cur: " +
1448 fbu_rt_diff
+ ", total: " +
1449 this._timing
.fbu_rt_total
+ ", cnt: " +
1450 this._timing
.fbu_rt_cnt
+ ", avg: " +
1451 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1452 this._timing
.fbu_rt_start
= 0;
1456 if (!ret
) { return ret
; } // need more data
1459 this._display
.flip();
1461 this._onFBUComplete(this);
1463 return true; // We finished this FBU
1466 _updateContinuousUpdates: function() {
1467 if (!this._enabledContinuousUpdates
) { return; }
1469 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1470 this._fb_width
, this._fb_height
);
1473 _resize: function(width
, height
) {
1474 this._fb_width
= width
;
1475 this._fb_height
= height
;
1477 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1479 this._display
.resize(this._fb_width
, this._fb_height
);
1480 this._onFBResize(this, this._fb_width
, this._fb_height
);
1482 this._timing
.fbu_rt_start
= (new Date()).getTime();
1483 this._updateContinuousUpdates();
1487 make_properties(RFB
, [
1488 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1489 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1490 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1491 ['shared', 'rw', 'bool'], // Request shared mode
1492 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1493 ['focus_on_click', 'rw', 'bool'], // Grab focus on canvas on mouse click
1494 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1495 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1496 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1497 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1498 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1500 // Callback functions
1501 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1502 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1503 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1504 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1505 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1506 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1507 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1508 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1509 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1510 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1511 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1514 RFB
.prototype.set_local_cursor = function (cursor
) {
1515 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1516 this._local_cursor
= false;
1517 this._display
.disableLocalCursor(); //Only show server-side cursor
1519 if (this._display
.get_cursor_uri()) {
1520 this._local_cursor
= true;
1522 Log
.Warn("Browser does not support local cursor");
1523 this._display
.disableLocalCursor();
1527 // Need to send an updated list of encodings if we are connected
1528 if (this._rfb_connection_state
=== "connected") {
1529 this._sendEncodings();
1533 RFB
.prototype.set_view_only = function (view_only
) {
1534 this._view_only
= view_only
;
1536 if (this._rfb_connection_state
=== "connecting" ||
1537 this._rfb_connection_state
=== "connected") {
1539 this._keyboard
.ungrab();
1540 this._mouse
.ungrab();
1542 this._keyboard
.grab();
1548 RFB
.prototype.get_display = function () { return this._display
; };
1549 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1550 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1554 keyEvent: function (sock
, keysym
, down
) {
1555 var buff
= sock
._sQ
;
1556 var offset
= sock
._sQlen
;
1558 buff
[offset
] = 4; // msg-type
1559 buff
[offset
+ 1] = down
;
1561 buff
[offset
+ 2] = 0;
1562 buff
[offset
+ 3] = 0;
1564 buff
[offset
+ 4] = (keysym
>> 24);
1565 buff
[offset
+ 5] = (keysym
>> 16);
1566 buff
[offset
+ 6] = (keysym
>> 8);
1567 buff
[offset
+ 7] = keysym
;
1573 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1574 function getRFBkeycode(xt_scancode
) {
1575 var upperByte
= (keycode
>> 8);
1576 var lowerByte
= (keycode
& 0x00ff);
1577 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1578 lowerByte
= lowerByte
| 0x80;
1584 var buff
= sock
._sQ
;
1585 var offset
= sock
._sQlen
;
1587 buff
[offset
] = 255; // msg-type
1588 buff
[offset
+ 1] = 0; // sub msg-type
1590 buff
[offset
+ 2] = (down
>> 8);
1591 buff
[offset
+ 3] = down
;
1593 buff
[offset
+ 4] = (keysym
>> 24);
1594 buff
[offset
+ 5] = (keysym
>> 16);
1595 buff
[offset
+ 6] = (keysym
>> 8);
1596 buff
[offset
+ 7] = keysym
;
1598 var RFBkeycode
= getRFBkeycode(keycode
);
1600 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1601 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1602 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1603 buff
[offset
+ 11] = RFBkeycode
;
1609 pointerEvent: function (sock
, x
, y
, mask
) {
1610 var buff
= sock
._sQ
;
1611 var offset
= sock
._sQlen
;
1613 buff
[offset
] = 5; // msg-type
1615 buff
[offset
+ 1] = mask
;
1617 buff
[offset
+ 2] = x
>> 8;
1618 buff
[offset
+ 3] = x
;
1620 buff
[offset
+ 4] = y
>> 8;
1621 buff
[offset
+ 5] = y
;
1627 // TODO(directxman12): make this unicode compatible?
1628 clientCutText: function (sock
, text
) {
1629 var buff
= sock
._sQ
;
1630 var offset
= sock
._sQlen
;
1632 buff
[offset
] = 6; // msg-type
1634 buff
[offset
+ 1] = 0; // padding
1635 buff
[offset
+ 2] = 0; // padding
1636 buff
[offset
+ 3] = 0; // padding
1638 var n
= text
.length
;
1640 buff
[offset
+ 4] = n
>> 24;
1641 buff
[offset
+ 5] = n
>> 16;
1642 buff
[offset
+ 6] = n
>> 8;
1643 buff
[offset
+ 7] = n
;
1645 for (var i
= 0; i
< n
; i
++) {
1646 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1649 sock
._sQlen
+= 8 + n
;
1653 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1654 var buff
= sock
._sQ
;
1655 var offset
= sock
._sQlen
;
1657 buff
[offset
] = 251; // msg-type
1658 buff
[offset
+ 1] = 0; // padding
1659 buff
[offset
+ 2] = width
>> 8; // width
1660 buff
[offset
+ 3] = width
;
1661 buff
[offset
+ 4] = height
>> 8; // height
1662 buff
[offset
+ 5] = height
;
1664 buff
[offset
+ 6] = 1; // number-of-screens
1665 buff
[offset
+ 7] = 0; // padding
1668 buff
[offset
+ 8] = id
>> 24; // id
1669 buff
[offset
+ 9] = id
>> 16;
1670 buff
[offset
+ 10] = id
>> 8;
1671 buff
[offset
+ 11] = id
;
1672 buff
[offset
+ 12] = 0; // x-position
1673 buff
[offset
+ 13] = 0;
1674 buff
[offset
+ 14] = 0; // y-position
1675 buff
[offset
+ 15] = 0;
1676 buff
[offset
+ 16] = width
>> 8; // width
1677 buff
[offset
+ 17] = width
;
1678 buff
[offset
+ 18] = height
>> 8; // height
1679 buff
[offset
+ 19] = height
;
1680 buff
[offset
+ 20] = flags
>> 24; // flags
1681 buff
[offset
+ 21] = flags
>> 16;
1682 buff
[offset
+ 22] = flags
>> 8;
1683 buff
[offset
+ 23] = flags
;
1689 clientFence: function (sock
, flags
, payload
) {
1690 var buff
= sock
._sQ
;
1691 var offset
= sock
._sQlen
;
1693 buff
[offset
] = 248; // msg-type
1695 buff
[offset
+ 1] = 0; // padding
1696 buff
[offset
+ 2] = 0; // padding
1697 buff
[offset
+ 3] = 0; // padding
1699 buff
[offset
+ 4] = flags
>> 24; // flags
1700 buff
[offset
+ 5] = flags
>> 16;
1701 buff
[offset
+ 6] = flags
>> 8;
1702 buff
[offset
+ 7] = flags
;
1704 var n
= payload
.length
;
1706 buff
[offset
+ 8] = n
; // length
1708 for (var i
= 0; i
< n
; i
++) {
1709 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1712 sock
._sQlen
+= 9 + n
;
1716 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1717 var buff
= sock
._sQ
;
1718 var offset
= sock
._sQlen
;
1720 buff
[offset
] = 150; // msg-type
1721 buff
[offset
+ 1] = enable
; // enable-flag
1723 buff
[offset
+ 2] = x
>> 8; // x
1724 buff
[offset
+ 3] = x
;
1725 buff
[offset
+ 4] = y
>> 8; // y
1726 buff
[offset
+ 5] = y
;
1727 buff
[offset
+ 6] = width
>> 8; // width
1728 buff
[offset
+ 7] = width
;
1729 buff
[offset
+ 8] = height
>> 8; // height
1730 buff
[offset
+ 9] = height
;
1736 pixelFormat: function (sock
, depth
, true_color
) {
1737 var buff
= sock
._sQ
;
1738 var offset
= sock
._sQlen
;
1744 } else if (depth
> 8) {
1750 bits
= Math
.floor(depth
/3);
1752 buff
[offset
] = 0; // msg-type
1754 buff
[offset
+ 1] = 0; // padding
1755 buff
[offset
+ 2] = 0; // padding
1756 buff
[offset
+ 3] = 0; // padding
1758 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1759 buff
[offset
+ 5] = depth
; // depth
1760 buff
[offset
+ 6] = 0; // little-endian
1761 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1763 buff
[offset
+ 8] = 0; // red-max
1764 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1766 buff
[offset
+ 10] = 0; // green-max
1767 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1769 buff
[offset
+ 12] = 0; // blue-max
1770 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1772 buff
[offset
+ 14] = bits
* 2; // red-shift
1773 buff
[offset
+ 15] = bits
* 1; // green-shift
1774 buff
[offset
+ 16] = bits
* 0; // blue-shift
1776 buff
[offset
+ 17] = 0; // padding
1777 buff
[offset
+ 18] = 0; // padding
1778 buff
[offset
+ 19] = 0; // padding
1784 clientEncodings: function (sock
, encodings
) {
1785 var buff
= sock
._sQ
;
1786 var offset
= sock
._sQlen
;
1788 buff
[offset
] = 2; // msg-type
1789 buff
[offset
+ 1] = 0; // padding
1791 buff
[offset
+ 2] = encodings
.length
>> 8;
1792 buff
[offset
+ 3] = encodings
.length
;
1794 var i
, j
= offset
+ 4;
1795 for (i
= 0; i
< encodings
.length
; i
++) {
1796 var enc
= encodings
[i
];
1797 buff
[j
] = enc
>> 24;
1798 buff
[j
+ 1] = enc
>> 16;
1799 buff
[j
+ 2] = enc
>> 8;
1805 sock
._sQlen
+= j
- offset
;
1809 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1810 var buff
= sock
._sQ
;
1811 var offset
= sock
._sQlen
;
1813 if (typeof(x
) === "undefined") { x
= 0; }
1814 if (typeof(y
) === "undefined") { y
= 0; }
1816 buff
[offset
] = 3; // msg-type
1817 buff
[offset
+ 1] = incremental
? 1 : 0;
1819 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1820 buff
[offset
+ 3] = x
& 0xFF;
1822 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1823 buff
[offset
+ 5] = y
& 0xFF;
1825 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1826 buff
[offset
+ 7] = w
& 0xFF;
1828 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1829 buff
[offset
+ 9] = h
& 0xFF;
1836 RFB
.genDES = function (password
, challenge
) {
1838 for (var i
= 0; i
< password
.length
; i
++) {
1839 passwd
.push(password
.charCodeAt(i
));
1841 return (new DES(passwd
)).encrypt(challenge
);
1844 RFB
.encodingHandlers
= {
1846 if (this._FBU
.lines
=== 0) {
1847 this._FBU
.lines
= this._FBU
.height
;
1850 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1851 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1852 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1853 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1854 var curr_height
= Math
.min(this._FBU
.lines
,
1855 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1856 var data
= this._sock
.get_rQ();
1857 var index
= this._sock
.get_rQi();
1858 if (this._fb_depth
== 8) {
1859 var pixels
= this._FBU
.width
* curr_height
1860 var newdata
= new Uint8Array(pixels
* 4);
1862 for (i
= 0;i
< pixels
;i
++) {
1863 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1864 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1865 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1866 newdata
[i
* 4 + 4] = 0;
1871 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1872 curr_height
, data
, index
);
1873 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1874 this._FBU
.lines
-= curr_height
;
1876 if (this._FBU
.lines
> 0) {
1877 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1880 this._FBU
.bytes
= 0;
1886 COPYRECT: function () {
1887 this._FBU
.bytes
= 4;
1888 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1889 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1890 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1894 this._FBU
.bytes
= 0;
1900 if (this._FBU
.subrects
=== 0) {
1901 this._FBU
.bytes
= 4 + 4;
1902 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1903 this._FBU
.subrects
= this._sock
.rQshift32();
1904 color
= this._sock
.rQshiftBytes(4); // Background
1905 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1908 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1909 color
= this._sock
.rQshiftBytes(4);
1910 var x
= this._sock
.rQshift16();
1911 var y
= this._sock
.rQshift16();
1912 var width
= this._sock
.rQshift16();
1913 var height
= this._sock
.rQshift16();
1914 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1915 this._FBU
.subrects
--;
1918 if (this._FBU
.subrects
> 0) {
1919 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1920 this._FBU
.bytes
= (4 + 8) * chunk
;
1923 this._FBU
.bytes
= 0;
1929 HEXTILE: function () {
1930 var rQ
= this._sock
.get_rQ();
1931 var rQi
= this._sock
.get_rQi();
1933 if (this._FBU
.tiles
=== 0) {
1934 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1935 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1936 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1937 this._FBU
.tiles
= this._FBU
.total_tiles
;
1940 while (this._FBU
.tiles
> 0) {
1941 this._FBU
.bytes
= 1;
1942 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1943 var subencoding
= rQ
[rQi
]; // Peek
1944 if (subencoding
> 30) { // Raw
1945 this._fail("Unexpected server message",
1946 "Illegal hextile subencoding: " + subencoding
);
1951 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1952 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1953 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1954 var x
= this._FBU
.x
+ tile_x
* 16;
1955 var y
= this._FBU
.y
+ tile_y
* 16;
1956 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1957 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1959 // Figure out how much we are expecting
1960 if (subencoding
& 0x01) { // Raw
1961 this._FBU
.bytes
+= w
* h
* 4;
1963 if (subencoding
& 0x02) { // Background
1964 this._FBU
.bytes
+= 4;
1966 if (subencoding
& 0x04) { // Foreground
1967 this._FBU
.bytes
+= 4;
1969 if (subencoding
& 0x08) { // AnySubrects
1970 this._FBU
.bytes
++; // Since we aren't shifting it off
1971 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1972 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1973 if (subencoding
& 0x10) { // SubrectsColoured
1974 this._FBU
.bytes
+= subrects
* (4 + 2);
1976 this._FBU
.bytes
+= subrects
* 2;
1981 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1983 // We know the encoding and have a whole tile
1984 this._FBU
.subencoding
= rQ
[rQi
];
1986 if (this._FBU
.subencoding
=== 0) {
1987 if (this._FBU
.lastsubencoding
& 0x01) {
1988 // Weird: ignore blanks are RAW
1989 Log
.Debug(" Ignoring blank after RAW");
1991 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1993 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1994 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1995 rQi
+= this._FBU
.bytes
- 1;
1997 if (this._FBU
.subencoding
& 0x02) { // Background
1998 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2001 if (this._FBU
.subencoding
& 0x04) { // Foreground
2002 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2006 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
2007 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
2011 for (var s
= 0; s
< subrects
; s
++) {
2013 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
2014 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2017 color
= this._FBU
.foreground
;
2022 var sy
= (xy
& 0x0f);
2026 var sw
= (wh
>> 4) + 1;
2027 var sh
= (wh
& 0x0f) + 1;
2029 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2032 this._display
.finishTile();
2034 this._sock
.set_rQi(rQi
);
2035 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2036 this._FBU
.bytes
= 0;
2040 if (this._FBU
.tiles
=== 0) {
2047 TIGHT: function () {
2048 this._FBU
.bytes
= 1; // compression-control byte
2049 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2051 var checksum = function (data
) {
2053 for (var i
= 0; i
< data
.length
; i
++) {
2055 if (sum
> 65536) sum
-= 65536;
2060 var resetStreams
= 0;
2062 var decompress = function (data
, expected
) {
2063 for (var i
= 0; i
< 4; i
++) {
2064 if ((resetStreams
>> i
) & 1) {
2065 this._FBU
.zlibs
[i
].reset();
2066 Log
.Info("Reset zlib stream " + i
);
2070 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2071 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2072 /*if (uncompressed.status !== 0) {
2073 Log.Error("Invalid data in zlib stream");
2076 //return uncompressed.data;
2077 return uncompressed
;
2080 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2081 // Convert indexed (palette based) image data to RGB
2082 // TODO: reduce number of calculations inside loop
2083 var dest
= this._destBuff
;
2084 var w
= Math
.floor((width
+ 7) / 8);
2085 var w1
= Math
.floor(width
/ 8);
2087 /*for (var y = 0; y < height; y++) {
2089 var yoffset = y * width;
2090 var ybitoffset = y * w;
2091 var xoffset, targetbyte;
2092 for (x = 0; x < w1; x++) {
2093 xoffset = yoffset + x * 8;
2094 targetbyte = data[ybitoffset + x];
2095 for (b = 7; b >= 0; b--) {
2096 dp = (xoffset + 7 - b) * 3;
2097 sp = (targetbyte >> b & 1) * 3;
2098 dest[dp] = palette[sp];
2099 dest[dp + 1] = palette[sp + 1];
2100 dest[dp + 2] = palette[sp + 2];
2104 xoffset = yoffset + x * 8;
2105 targetbyte = data[ybitoffset + x];
2106 for (b = 7; b >= 8 - width % 8; b--) {
2107 dp = (xoffset + 7 - b) * 3;
2108 sp = (targetbyte >> b & 1) * 3;
2109 dest[dp] = palette[sp];
2110 dest[dp + 1] = palette[sp + 1];
2111 dest[dp + 2] = palette[sp + 2];
2115 for (var y
= 0; y
< height
; y
++) {
2117 for (x
= 0; x
< w1
; x
++) {
2118 for (b
= 7; b
>= 0; b
--) {
2119 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2120 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2121 dest
[dp
] = palette
[sp
];
2122 dest
[dp
+ 1] = palette
[sp
+ 1];
2123 dest
[dp
+ 2] = palette
[sp
+ 2];
2128 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2129 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2130 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2131 dest
[dp
] = palette
[sp
];
2132 dest
[dp
+ 1] = palette
[sp
+ 1];
2133 dest
[dp
+ 2] = palette
[sp
+ 2];
2141 var indexedToRGBX = function (data
, palette
, width
, height
) {
2142 // Convert indexed (palette based) image data to RGB
2143 var dest
= this._destBuff
;
2144 var total
= width
* height
* 4;
2145 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2146 var sp
= data
[j
] * 3;
2147 dest
[i
] = palette
[sp
];
2148 dest
[i
+ 1] = palette
[sp
+ 1];
2149 dest
[i
+ 2] = palette
[sp
+ 2];
2156 var rQi
= this._sock
.get_rQi();
2157 var rQ
= this._sock
.rQwhole();
2159 var cl_header
, cl_data
;
2161 var handlePalette = function () {
2162 var numColors
= rQ
[rQi
+ 2] + 1;
2163 var paletteSize
= numColors
* 3;
2164 this._FBU
.bytes
+= paletteSize
;
2165 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2167 var bpp
= (numColors
<= 2) ? 1 : 8;
2168 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2170 if (rowSize
* this._FBU
.height
< 12) {
2173 cl_data
= rowSize
* this._FBU
.height
;
2174 //clength = [0, rowSize * this._FBU.height];
2176 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2177 var cl_offset
= rQi
+ 3 + paletteSize
;
2180 cl_data
+= rQ
[cl_offset
] & 0x7f;
2181 if (rQ
[cl_offset
] & 0x80) {
2183 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2184 if (rQ
[cl_offset
+ 1] & 0x80) {
2186 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2189 // end inline getTightCLength
2192 this._FBU
.bytes
+= cl_header
+ cl_data
;
2193 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2195 // Shift ctl, filter id, num colors, palette entries, and clength off
2196 this._sock
.rQskipBytes(3);
2197 //var palette = this._sock.rQshiftBytes(paletteSize);
2198 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2199 this._sock
.rQskipBytes(cl_header
);
2202 data
= this._sock
.rQshiftBytes(cl_data
);
2204 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2207 // Convert indexed (palette based) image data to RGB
2209 if (numColors
== 2) {
2210 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2211 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2213 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2214 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2221 var handleCopy = function () {
2223 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2224 if (uncompressedSize
< 12) {
2227 cl_data
= uncompressedSize
;
2229 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2230 var cl_offset
= rQi
+ 1;
2233 cl_data
+= rQ
[cl_offset
] & 0x7f;
2234 if (rQ
[cl_offset
] & 0x80) {
2236 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2237 if (rQ
[cl_offset
+ 1] & 0x80) {
2239 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2242 // end inline getTightCLength
2244 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2245 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2247 // Shift ctl, clength off
2248 this._sock
.rQshiftBytes(1 + cl_header
);
2251 data
= this._sock
.rQshiftBytes(cl_data
);
2253 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2256 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2261 var ctl
= this._sock
.rQpeek8();
2263 // Keep tight reset bits
2264 resetStreams
= ctl
& 0xF;
2266 // Figure out filter
2268 streamId
= ctl
& 0x3;
2270 if (ctl
=== 0x08) cmode
= "fill";
2271 else if (ctl
=== 0x09) cmode
= "jpeg";
2272 else if (ctl
=== 0x0A) cmode
= "png";
2273 else if (ctl
& 0x04) cmode
= "filter";
2274 else if (ctl
< 0x04) cmode
= "copy";
2275 else return this._fail("Unexpected server message",
2276 "Illegal tight compression received, " +
2280 // fill use depth because TPIXELs drop the padding byte
2281 case "fill": // TPIXEL
2282 this._FBU
.bytes
+= 3;
2284 case "jpeg": // max clength
2285 this._FBU
.bytes
+= 3;
2287 case "png": // max clength
2288 this._FBU
.bytes
+= 3;
2290 case "filter": // filter id + num colors if palette
2291 this._FBU
.bytes
+= 2;
2297 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2299 // Determine FBU.bytes
2303 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);
2304 this._sock
.rQskipBytes(4);
2308 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2309 var cl_offset
= rQi
+ 1;
2312 cl_data
+= rQ
[cl_offset
] & 0x7f;
2313 if (rQ
[cl_offset
] & 0x80) {
2315 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2316 if (rQ
[cl_offset
+ 1] & 0x80) {
2318 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2321 // end inline getTightCLength
2322 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2323 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2325 // We have everything, render it
2326 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2327 data
= this._sock
.rQshiftBytes(cl_data
);
2328 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2331 var filterId
= rQ
[rQi
+ 1];
2332 if (filterId
=== 1) {
2333 if (!handlePalette()) { return false; }
2335 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2336 // Filter 2, Gradient is valid but not use if jpeg is enabled
2337 this._fail("Unexpected server message",
2338 "Unsupported tight subencoding received, " +
2339 "filter: " + filterId
);
2343 if (!handleCopy()) { return false; }
2348 this._FBU
.bytes
= 0;
2354 last_rect: function () {
2355 this._FBU
.rects
= 0;
2359 ExtendedDesktopSize: function () {
2360 this._FBU
.bytes
= 1;
2361 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2363 this._supportsSetDesktopSize
= true;
2364 var number_of_screens
= this._sock
.rQpeek8();
2366 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2367 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2369 this._sock
.rQskipBytes(1); // number-of-screens
2370 this._sock
.rQskipBytes(3); // padding
2372 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2373 // Save the id and flags of the first screen
2375 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2376 this._sock
.rQskipBytes(2); // x-position
2377 this._sock
.rQskipBytes(2); // y-position
2378 this._sock
.rQskipBytes(2); // width
2379 this._sock
.rQskipBytes(2); // height
2380 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2382 this._sock
.rQskipBytes(16);
2387 * The x-position indicates the reason for the change:
2389 * 0 - server resized on its own
2390 * 1 - this client requested the resize
2391 * 2 - another client requested the resize
2394 // We need to handle errors when we requested the resize.
2395 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2397 // The y-position indicates the status code from the server
2398 switch (this._FBU
.y
) {
2400 msg
= "Resize is administratively prohibited";
2403 msg
= "Out of resources";
2406 msg
= "Invalid screen layout";
2409 msg
= "Unknown reason";
2412 this._notification("Server did not accept the resize request: "
2415 this._resize(this._FBU
.width
, this._FBU
.height
);
2418 this._FBU
.bytes
= 0;
2419 this._FBU
.rects
-= 1;
2423 DesktopSize: function () {
2424 this._resize(this._FBU
.width
, this._FBU
.height
);
2425 this._FBU
.bytes
= 0;
2426 this._FBU
.rects
-= 1;
2430 Cursor: function () {
2431 Log
.Debug(">> set_cursor");
2432 var x
= this._FBU
.x
; // hotspot-x
2433 var y
= this._FBU
.y
; // hotspot-y
2434 var w
= this._FBU
.width
;
2435 var h
= this._FBU
.height
;
2437 var pixelslength
= w
* h
* 4;
2438 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2440 this._FBU
.bytes
= pixelslength
+ masklength
;
2441 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2443 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2444 this._sock
.rQshiftBytes(masklength
),
2447 this._FBU
.bytes
= 0;
2450 Log
.Debug("<< set_cursor");
2454 QEMUExtendedKeyEvent: function () {
2457 // Old Safari doesn't support creating keyboard events
2459 var keyboardEvent
= document
.createEvent("keyboardEvent");
2460 if (keyboardEvent
.code
!== undefined) {
2461 this._qemuExtKeyEventSupported
= true;