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
, Mouse
} from "./input/devices.js";
19 import Websock
from "./websock.js";
20 import Base64
from "./base64.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";
27 /*jslint white: false, browser: true */
28 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
30 export default function RFB(defaults
) {
37 this._rfb_port
= 5900;
38 this._rfb_password
= '';
41 this._rfb_connection_state
= '';
42 this._rfb_init_state
= '';
43 this._rfb_version
= 0;
44 this._rfb_max_version
= 3.8;
45 this._rfb_auth_scheme
= '';
46 this._rfb_disconnect_reason
= "";
48 this._rfb_tightvnc
= false;
49 this._rfb_xvp_ver
= 0;
51 this._encHandlers
= {};
54 this._sock
= null; // Websock object
55 this._display
= null; // Display object
56 this._flushing
= false; // Display flushing state
57 this._keyboard
= null; // Keyboard input handler object
58 this._mouse
= null; // Mouse input handler object
59 this._disconnTimer
= null; // disconnection timer
61 this._supportsFence
= false;
63 this._supportsContinuousUpdates
= false;
64 this._enabledContinuousUpdates
= false;
66 // Frame buffer update state
80 zlib
: [] // TIGHT zlib streams
87 this._destBuff
= null;
88 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
90 this._rre_chunk_sz
= 100;
105 this._supportsSetDesktopSize
= false;
107 this._screen_flags
= 0;
110 this._mouse_buttonMask
= 0;
111 this._mouse_arr
= [];
112 this._viewportDragging
= false;
113 this._viewportDragPos
= {};
114 this._viewportHasMoved
= false;
116 // QEMU Extended Key Event support - default to false
117 this._qemuExtKeyEventSupported
= false;
119 // set the default value on user-facing properties
120 set_defaults(this, defaults
, {
121 'target': 'null', // VNC display rendering Canvas object
122 'focusContainer': document
, // DOM element that captures keyboard input
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 'xvp_password_sep': '@', // Separator for XVP password fields
128 'disconnectTimeout': 3, // Time (s) to wait for disconnection
129 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
130 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
131 'viewportDrag': false, // Move the viewport on mouse drags
133 // Callback functions
134 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
135 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
136 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
137 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
138 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
139 'onBell': function () { }, // onBell(rfb): RFB Bell message received
140 'onFBUReceive': function () { }, // onFBUReceive(rfb, rect): RFB FBU rect received but not yet processed
141 'onFBUComplete': function () { }, // onFBUComplete(rfb): RFB FBU received and processed
142 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
143 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
144 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
148 Log
.Debug(">> RFB.constructor");
150 // populate encHandlers with bound versions
151 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this)
152 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this)
153 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this)
154 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this)
155 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this)
157 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this)
158 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this)
159 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this)
160 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this)
161 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this)
163 // NB: nothing that needs explicit teardown should be done
164 // before this point, since this can throw an exception
166 this._display
= new Display({target
: this._target
,
167 onFlush
: this._onFlush
.bind(this)});
169 Log
.Error("Display exception: " + exc
);
173 this._keyboard
= new Keyboard({target
: this._focusContainer
,
174 onKeyEvent
: this._handleKeyEvent
.bind(this)});
176 this._mouse
= new Mouse({target
: this._target
,
177 onMouseButton
: this._handleMouseButton
.bind(this),
178 onMouseMove
: this._handleMouseMove
.bind(this)});
180 this._sock
= new Websock();
181 this._sock
.on('message', this._handle_message
.bind(this));
182 this._sock
.on('open', function () {
183 if ((this._rfb_connection_state
=== 'connecting') &&
184 (this._rfb_init_state
=== '')) {
185 this._rfb_init_state
= 'ProtocolVersion';
186 Log
.Debug("Starting VNC handshake");
188 this._fail("Unexpected server connection");
191 this._sock
.on('close', function (e
) {
192 Log
.Warn("WebSocket on-close event");
195 msg
= " (code: " + e
.code
;
197 msg
+= ", reason: " + e
.reason
;
201 switch (this._rfb_connection_state
) {
202 case 'disconnecting':
203 this._updateConnectionState('disconnected');
206 this._fail('Failed to connect to server', msg
);
209 // Handle disconnects that were initiated server-side
210 this._updateConnectionState('disconnecting');
211 this._updateConnectionState('disconnected');
214 this._fail("Unexpected server disconnect",
215 "Already disconnected: " + msg
);
218 this._fail("Unexpected server disconnect",
219 "Not in any state yet: " + msg
);
222 this._sock
.off('close');
224 this._sock
.on('error', function (e
) {
225 Log
.Warn("WebSocket on-error event");
231 var rmode
= this._display
.get_render_mode();
232 Log
.Info("Using native WebSockets, render mode: " + rmode
);
234 Log
.Debug("<< RFB.constructor");
239 connect: function (host
, port
, password
, path
) {
240 this._rfb_host
= host
;
241 this._rfb_port
= port
;
242 this._rfb_password
= (password
!== undefined) ? password
: "";
243 this._rfb_path
= (path
!== undefined) ? path
: "";
245 if (!this._rfb_host
|| !this._rfb_port
) {
247 _("Must set host and port"));
250 this._rfb_init_state
= '';
251 this._updateConnectionState('connecting');
255 disconnect: function () {
256 this._updateConnectionState('disconnecting');
257 this._sock
.off('error');
258 this._sock
.off('message');
259 this._sock
.off('open');
262 sendPassword: function (passwd
) {
263 this._rfb_password
= passwd
;
264 setTimeout(this._init_msg
.bind(this), 0);
267 sendCtrlAltDel: function () {
268 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
269 Log
.Info("Sending Ctrl-Alt-Del");
271 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
272 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
273 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
274 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
275 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
276 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
281 xvpOp: function (ver
, op
) {
282 if (this._rfb_xvp_ver
< ver
) { return false; }
283 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
284 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
288 xvpShutdown: function () {
289 return this.xvpOp(1, 2);
292 xvpReboot: function () {
293 return this.xvpOp(1, 3);
296 xvpReset: function () {
297 return this.xvpOp(1, 4);
300 // Send a key press. If 'down' is not specified then send a down key
301 // followed by an up key.
302 sendKey: function (keysym
, code
, down
) {
303 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
305 if (down
=== undefined) {
306 this.sendKey(keysym
, code
, true);
307 this.sendKey(keysym
, code
, false);
311 var scancode
= XtScancode
[code
];
313 if (this._qemuExtKeyEventSupported
&& scancode
) {
315 keysym
= keysym
|| 0;
317 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
319 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
324 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
325 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
331 clipboardPasteFrom: function (text
) {
332 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
333 RFB
.messages
.clientCutText(this._sock
, text
);
336 // Requests a change of remote desktop size. This message is an extension
337 // and may only be sent if we have received an ExtendedDesktopSize message
338 requestDesktopSize: function (width
, height
) {
339 if (this._rfb_connection_state
!== 'connected' ||
344 if (this._supportsSetDesktopSize
) {
345 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
346 this._screen_id
, this._screen_flags
);
357 _connect: function () {
358 Log
.Debug(">> RFB.connect");
362 if (typeof UsingSocketIO
!== 'undefined') {
365 uri
= this._encrypt
? 'wss' : 'ws';
368 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
369 Log
.Info("connecting to " + uri
);
372 // WebSocket.onopen transitions to the RFB init states
373 this._sock
.open(uri
, this._wsProtocols
);
375 if (e
.name
=== 'SyntaxError') {
376 this._fail("Invalid host or port value given", e
);
378 this._fail("Error while connecting", e
);
382 Log
.Debug("<< RFB.connect");
385 _disconnect: function () {
386 Log
.Debug(">> RFB.disconnect");
390 Log
.Debug("<< RFB.disconnect");
393 _init_vars: function () {
396 this._FBU
.subrects
= 0; // RRE and HEXTILE
397 this._FBU
.lines
= 0; // RAW
398 this._FBU
.tiles
= 0; // HEXTILE
399 this._FBU
.zlibs
= []; // TIGHT zlib encoders
400 this._mouse_buttonMask
= 0;
401 this._mouse_arr
= [];
402 this._rfb_tightvnc
= false;
404 // Clear the per connection encoding stats
405 var stats
= this._encStats
;
406 Object
.keys(stats
).forEach(function (key
) {
411 for (i
= 0; i
< 4; i
++) {
412 this._FBU
.zlibs
[i
] = new Inflator();
416 _print_stats: function () {
417 var stats
= this._encStats
;
419 Log
.Info("Encoding stats for this connection:");
420 Object
.keys(stats
).forEach(function (key
) {
422 if (s
[0] + s
[1] > 0) {
423 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
427 Log
.Info("Encoding stats since page load:");
428 Object
.keys(stats
).forEach(function (key
) {
430 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
434 _cleanup: function () {
435 if (!this._view_only
) { this._keyboard
.ungrab(); }
436 if (!this._view_only
) { this._mouse
.ungrab(); }
437 this._display
.defaultCursor();
438 if (Log
.get_logging() !== 'debug') {
439 // Show noVNC logo on load and when disconnected, unless in
441 this._display
.clear();
450 * disconnected - permanent state
452 _updateConnectionState: function (state
) {
453 var oldstate
= this._rfb_connection_state
;
455 if (state
=== oldstate
) {
456 Log
.Debug("Already in state '" + state
+ "', ignoring");
460 // The 'disconnected' state is permanent for each RFB object
461 if (oldstate
=== 'disconnected') {
462 Log
.Error("Tried changing state of a disconnected RFB object");
466 // Ensure proper transitions before doing anything
469 if (oldstate
!== 'connecting') {
470 Log
.Error("Bad transition to connected state, " +
471 "previous connection state: " + oldstate
);
477 if (oldstate
!== 'disconnecting') {
478 Log
.Error("Bad transition to disconnected state, " +
479 "previous connection state: " + oldstate
);
485 if (oldstate
!== '') {
486 Log
.Error("Bad transition to connecting state, " +
487 "previous connection state: " + oldstate
);
492 case 'disconnecting':
493 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
494 Log
.Error("Bad transition to disconnecting state, " +
495 "previous connection state: " + oldstate
);
501 Log
.Error("Unknown connection state: " + state
);
505 // State change actions
507 this._rfb_connection_state
= state
;
508 this._onUpdateState(this, state
, oldstate
);
510 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
513 if (this._disconnTimer
&& state
!== 'disconnecting') {
514 Log
.Debug("Clearing disconnect timer");
515 clearTimeout(this._disconnTimer
);
516 this._disconnTimer
= null;
518 // make sure we don't get a double event
519 this._sock
.off('close');
524 // Call onDisconnected callback after onUpdateState since
525 // we don't know if the UI only displays the latest message
526 if (this._rfb_disconnect_reason
!== "") {
527 this._onDisconnected(this, this._rfb_disconnect_reason
);
529 // No reason means clean disconnect
530 this._onDisconnected(this);
538 case 'disconnecting':
541 this._disconnTimer
= setTimeout(function () {
542 this._rfb_disconnect_reason
= _("Disconnect timeout");
543 this._updateConnectionState('disconnected');
544 }.bind(this), this._disconnectTimeout
* 1000);
549 /* Print errors and disconnect
551 * The optional parameter 'details' is used for information that
552 * should be logged but not sent to the user interface.
554 _fail: function (msg
, details
) {
556 if (typeof details
!== 'undefined') {
557 fullmsg
= msg
+ " (" + details
+ ")";
559 switch (this._rfb_connection_state
) {
560 case 'disconnecting':
561 Log
.Error("Failed when disconnecting: " + fullmsg
);
564 Log
.Error("Failed while connected: " + fullmsg
);
567 Log
.Error("Failed when connecting: " + fullmsg
);
570 Log
.Error("RFB failure: " + fullmsg
);
573 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
575 // Transition to disconnected without waiting for socket to close
576 this._updateConnectionState('disconnecting');
577 this._updateConnectionState('disconnected');
583 * Send a notification to the UI. Valid levels are:
584 * 'normal'|'warn'|'error'
586 * NOTE: Options could be added in the future.
587 * NOTE: If this function is called multiple times, remember that the
588 * interface could be only showing the latest notification.
590 _notification: function(msg
, level
, options
) {
595 Log
.Debug("Notification[" + level
+ "]:" + msg
);
598 Log
.Error("Invalid notification level: " + level
);
603 this._onNotification(this, msg
, level
, options
);
605 this._onNotification(this, msg
, level
);
609 _handle_message: function () {
610 if (this._sock
.rQlen() === 0) {
611 Log
.Warn("handle_message called on an empty receive queue");
615 switch (this._rfb_connection_state
) {
617 Log
.Error("Got data while disconnected");
621 if (this._flushing
) {
624 if (!this._normal_msg()) {
627 if (this._sock
.rQlen() === 0) {
638 _handleKeyEvent: function (keysym
, code
, down
) {
639 this.sendKey(keysym
, code
, down
);
642 _handleMouseButton: function (x
, y
, down
, bmask
) {
644 this._mouse_buttonMask
|= bmask
;
646 this._mouse_buttonMask
&= ~bmask
;
649 if (this._viewportDrag
) {
650 if (down
&& !this._viewportDragging
) {
651 this._viewportDragging
= true;
652 this._viewportDragPos
= {'x': x
, 'y': y
};
654 // Skip sending mouse events
657 this._viewportDragging
= false;
659 // If the viewport didn't actually move, then treat as a mouse click event
660 // Send the button down event here, as the button up event is sent at the end of this function
661 if (!this._viewportHasMoved
&& !this._view_only
) {
662 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
664 this._viewportHasMoved
= false;
668 if (this._view_only
) { return; } // View only, skip mouse events
670 if (this._rfb_connection_state
!== 'connected') { return; }
671 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
674 _handleMouseMove: function (x
, y
) {
675 if (this._viewportDragging
) {
676 var deltaX
= this._viewportDragPos
.x
- x
;
677 var deltaY
= this._viewportDragPos
.y
- y
;
679 // The goal is to trigger on a certain physical width, the
680 // devicePixelRatio brings us a bit closer but is not optimal.
681 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
683 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
684 Math
.abs(deltaY
) > dragThreshold
)) {
685 this._viewportHasMoved
= true;
687 this._viewportDragPos
= {'x': x
, 'y': y
};
688 this._display
.viewportChangePos(deltaX
, deltaY
);
691 // Skip sending mouse events
695 if (this._view_only
) { return; } // View only, skip mouse events
697 if (this._rfb_connection_state
!== 'connected') { return; }
698 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
703 _negotiate_protocol_version: function () {
704 if (this._sock
.rQlen() < 12) {
705 return this._fail("Error while negotiating with server",
706 "Incomplete protocol version");
709 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
710 Log
.Info("Server ProtocolVersion: " + sversion
);
713 case "000.000": // UltraVNC repeater
717 case "003.006": // UltraVNC
718 case "003.889": // Apple Remote Desktop
719 this._rfb_version
= 3.3;
722 this._rfb_version
= 3.7;
725 case "004.000": // Intel AMT KVM
726 case "004.001": // RealVNC 4.6
727 case "005.000": // RealVNC 5.3
728 this._rfb_version
= 3.8;
731 return this._fail("Unsupported server",
732 "Invalid server version: " + sversion
);
736 var repeaterID
= this._repeaterID
;
737 while (repeaterID
.length
< 250) {
740 this._sock
.send_string(repeaterID
);
744 if (this._rfb_version
> this._rfb_max_version
) {
745 this._rfb_version
= this._rfb_max_version
;
748 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
749 ".00" + ((this._rfb_version
* 10) % 10);
750 this._sock
.send_string("RFB " + cversion
+ "\n");
751 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
753 this._rfb_init_state
= 'Security';
756 _negotiate_security: function () {
757 // Polyfill since IE and PhantomJS doesn't have
758 // TypedArray.includes()
759 function includes(item
, array
) {
760 for (var i
= 0; i
< array
.length
; i
++) {
761 if (array
[i
] === item
) {
768 if (this._rfb_version
>= 3.7) {
769 // Server sends supported list, client decides
770 var num_types
= this._sock
.rQshift8();
771 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
773 if (num_types
=== 0) {
774 var strlen
= this._sock
.rQshift32();
775 var reason
= this._sock
.rQshiftStr(strlen
);
776 return this._fail("Error while negotiating with server",
777 "Security failure: " + reason
);
780 var types
= this._sock
.rQshiftBytes(num_types
);
781 Log
.Debug("Server security types: " + types
);
783 // Look for each auth in preferred order
784 this._rfb_auth_scheme
= 0;
785 if (includes(1, types
)) {
786 this._rfb_auth_scheme
= 1; // None
787 } else if (includes(22, types
)) {
788 this._rfb_auth_scheme
= 22; // XVP
789 } else if (includes(16, types
)) {
790 this._rfb_auth_scheme
= 16; // Tight
791 } else if (includes(2, types
)) {
792 this._rfb_auth_scheme
= 2; // VNC Auth
794 return this._fail("Unsupported server",
795 "Unsupported security types: " + types
);
798 this._sock
.send([this._rfb_auth_scheme
]);
801 if (this._sock
.rQwait("security scheme", 4)) { return false; }
802 this._rfb_auth_scheme
= this._sock
.rQshift32();
805 this._rfb_init_state
= 'Authentication';
806 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
808 return this._init_msg(); // jump to authentication
812 _negotiate_xvp_auth: function () {
813 var xvp_sep
= this._xvp_password_sep
;
814 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
815 if (xvp_auth
.length
< 3) {
816 var msg
= 'XVP credentials required (user' + xvp_sep
+
817 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
818 this._onPasswordRequired(this, msg
);
822 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
823 String
.fromCharCode(xvp_auth
[1].length
) +
826 this._sock
.send_string(xvp_auth_str
);
827 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
828 this._rfb_auth_scheme
= 2;
829 return this._negotiate_authentication();
832 _negotiate_std_vnc_auth: function () {
833 if (this._rfb_password
.length
=== 0) {
834 this._onPasswordRequired(this);
838 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
840 // TODO(directxman12): make genDES not require an Array
841 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
842 var response
= RFB
.genDES(this._rfb_password
, challenge
);
843 this._sock
.send(response
);
844 this._rfb_init_state
= "SecurityResult";
848 _negotiate_tight_tunnels: function (numTunnels
) {
849 var clientSupportedTunnelTypes
= {
850 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
852 var serverSupportedTunnelTypes
= {};
853 // receive tunnel capabilities
854 for (var i
= 0; i
< numTunnels
; i
++) {
855 var cap_code
= this._sock
.rQshift32();
856 var cap_vendor
= this._sock
.rQshiftStr(4);
857 var cap_signature
= this._sock
.rQshiftStr(8);
858 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
861 // choose the notunnel type
862 if (serverSupportedTunnelTypes
[0]) {
863 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
864 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
865 return this._fail("Unsupported server",
866 "Client's tunnel type had the incorrect " +
867 "vendor or signature");
869 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
870 return false; // wait until we receive the sub auth count to continue
872 return this._fail("Unsupported server",
873 "Server wanted tunnels, but doesn't support " +
874 "the notunnel type");
878 _negotiate_tight_auth: function () {
879 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
880 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
881 var numTunnels
= this._sock
.rQshift32();
882 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
884 this._rfb_tightvnc
= true;
886 if (numTunnels
> 0) {
887 this._negotiate_tight_tunnels(numTunnels
);
888 return false; // wait until we receive the sub auth to continue
892 // second pass, do the sub-auth negotiation
893 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
894 var subAuthCount
= this._sock
.rQshift32();
895 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
896 this._rfb_init_state
= 'SecurityResult';
900 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
902 var clientSupportedTypes
= {
907 var serverSupportedTypes
= [];
909 for (var i
= 0; i
< subAuthCount
; i
++) {
910 var capNum
= this._sock
.rQshift32();
911 var capabilities
= this._sock
.rQshiftStr(12);
912 serverSupportedTypes
.push(capabilities
);
915 for (var authType
in clientSupportedTypes
) {
916 if (serverSupportedTypes
.indexOf(authType
) != -1) {
917 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
920 case 'STDVNOAUTH__': // no auth
921 this._rfb_init_state
= 'SecurityResult';
923 case 'STDVVNCAUTH_': // VNC auth
924 this._rfb_auth_scheme
= 2;
925 return this._init_msg();
927 return this._fail("Unsupported server",
928 "Unsupported tiny auth scheme: " +
934 return this._fail("Unsupported server",
935 "No supported sub-auth types!");
938 _negotiate_authentication: function () {
939 switch (this._rfb_auth_scheme
) {
940 case 0: // connection failed
941 if (this._sock
.rQwait("auth reason", 4)) { return false; }
942 var strlen
= this._sock
.rQshift32();
943 var reason
= this._sock
.rQshiftStr(strlen
);
944 return this._fail("Authentication failure", reason
);
947 if (this._rfb_version
>= 3.8) {
948 this._rfb_init_state
= 'SecurityResult';
951 this._rfb_init_state
= 'ClientInitialisation';
952 return this._init_msg();
955 return this._negotiate_xvp_auth();
957 case 2: // VNC authentication
958 return this._negotiate_std_vnc_auth();
960 case 16: // TightVNC Security Type
961 return this._negotiate_tight_auth();
964 return this._fail("Unsupported server",
965 "Unsupported auth scheme: " +
966 this._rfb_auth_scheme
);
970 _handle_security_result: function () {
971 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
972 switch (this._sock
.rQshift32()) {
974 this._rfb_init_state
= 'ClientInitialisation';
975 Log
.Debug('Authentication OK');
976 return this._init_msg();
978 if (this._rfb_version
>= 3.8) {
979 var length
= this._sock
.rQshift32();
980 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
981 var reason
= this._sock
.rQshiftStr(length
);
982 return this._fail("Authentication failure", reason
);
984 return this._fail("Authentication failure");
987 return this._fail("Too many authentication attempts");
989 return this._fail("Unsupported server",
990 "Unknown SecurityResult");
994 _negotiate_server_init: function () {
995 if (this._sock
.rQwait("server initialization", 24)) { return false; }
998 var width
= this._sock
.rQshift16();
999 var height
= this._sock
.rQshift16();
1002 var bpp
= this._sock
.rQshift8();
1003 var depth
= this._sock
.rQshift8();
1004 var big_endian
= this._sock
.rQshift8();
1005 var true_color
= this._sock
.rQshift8();
1007 var red_max
= this._sock
.rQshift16();
1008 var green_max
= this._sock
.rQshift16();
1009 var blue_max
= this._sock
.rQshift16();
1010 var red_shift
= this._sock
.rQshift8();
1011 var green_shift
= this._sock
.rQshift8();
1012 var blue_shift
= this._sock
.rQshift8();
1013 this._sock
.rQskipBytes(3); // padding
1015 // NB(directxman12): we don't want to call any callbacks or print messages until
1016 // *after* we're past the point where we could backtrack
1018 /* Connection name/title */
1019 var name_length = this._sock.rQshift32();
1020 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1021 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1023 if (this._rfb_tightvnc) {
1024 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1025 // In TightVNC mode, ServerInit message is extended
1026 var numServerMessages = this._sock.rQshift16();
1027 var numClientMessages = this._sock.rQshift16();
1028 var numEncodings = this._sock.rQshift16();
1029 this._sock.rQskipBytes(2); // padding
1031 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1032 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1034 // we don't actually do anything with the capability information that TIGHT sends,
1035 // so we just skip the all of this.
1037 // TIGHT server message capabilities
1038 this._sock.rQskipBytes(16 * numServerMessages);
1040 // TIGHT client message capabilities
1041 this._sock.rQskipBytes(16 * numClientMessages);
1043 // TIGHT encoding capabilities
1044 this._sock.rQskipBytes(16 * numEncodings);
1047 // NB(directxman12): these are down here so that we don't run them multiple times
1049 Log.Info("Screen: " + width + "x" + height +
1050 ", bpp: " + bpp + ", depth: " + depth +
1051 ", big_endian: " + big_endian +
1052 ", true_color: " + true_color +
1053 ", red_max: " + red_max +
1054 ", green_max: " + green_max +
1055 ", blue_max: " + blue_max +
1056 ", red_shift: " + red_shift +
1057 ", green_shift: " + green_shift +
1058 ", blue_shift: " + blue_shift);
1060 if (big_endian !== 0) {
1061 Log.Warn("Server native endian is not little endian");
1064 if (red_shift !== 16) {
1065 Log.Warn("Server native red-shift is not 16");
1068 if (blue_shift !== 0) {
1069 Log.Warn("Server native blue-shift is not 0");
1072 // we're past the point where we could backtrack, so it's safe to call this
1073 this._onDesktopName(this, this._fb_name);
1075 this._resize(width, height);
1077 if (!this._view_only) { this._keyboard.grab(); }
1078 if (!this._view_only) { this._mouse.grab(); }
1080 this._fb_depth = 24;
1082 if (this._fb_name === "Intel(r) AMT KVM") {
1083 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1087 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1088 this._sendEncodings();
1089 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1091 this._timing.fbu_rt_start = (new Date()).getTime();
1092 this._timing.pixels = 0;
1094 // Cursor will be server side until the server decides to honor
1095 // our request and send over the cursor image
1096 this._display.disableLocalCursor();
1098 this._updateConnectionState('connected');
1102 _sendEncodings: function () {
1105 // In preference order
1106 encs.push(encodings.encodingCopyRect);
1107 // Only supported with full depth support
1108 if (this._fb_depth == 24) {
1109 encs.push(encodings.encodingTight);
1110 encs.push(encodings.encodingHextile);
1111 encs.push(encodings.encodingRRE);
1113 encs.push(encodings.encodingRaw);
1115 // Psuedo-encoding settings
1116 encs.push(encodings.pseudoEncodingTightPNG);
1117 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1118 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1120 encs.push(encodings.pseudoEncodingDesktopSize);
1121 encs.push(encodings.pseudoEncodingLastRect);
1122 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1123 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1124 encs.push(encodings.pseudoEncodingXvp);
1125 encs.push(encodings.pseudoEncodingFence);
1126 encs.push(encodings.pseudoEncodingContinuousUpdates);
1128 if (this._local_cursor && this._fb_depth == 24) {
1129 encs.push(encodings.pseudoEncodingCursor);
1132 RFB.messages.clientEncodings(this._sock, encs);
1135 /* RFB protocol initialization states:
1140 * ClientInitialization - not triggered by server message
1141 * ServerInitialization
1143 _init_msg: function () {
1144 switch (this._rfb_init_state
) {
1145 case 'ProtocolVersion':
1146 return this._negotiate_protocol_version();
1149 return this._negotiate_security();
1151 case 'Authentication':
1152 return this._negotiate_authentication();
1154 case 'SecurityResult':
1155 return this._handle_security_result();
1157 case 'ClientInitialisation':
1158 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1159 this._rfb_init_state
= 'ServerInitialisation';
1162 case 'ServerInitialisation':
1163 return this._negotiate_server_init();
1166 return this._fail("Internal error", "Unknown init state: " +
1167 this._rfb_init_state
);
1171 _handle_set_colour_map_msg: function () {
1172 Log
.Debug("SetColorMapEntries");
1174 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1177 _handle_server_cut_text: function () {
1178 Log
.Debug("ServerCutText");
1180 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1181 this._sock
.rQskipBytes(3); // Padding
1182 var length
= this._sock
.rQshift32();
1183 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1185 var text
= this._sock
.rQshiftStr(length
);
1187 if (this._view_only
) { return true; }
1189 this._onClipboard(this, text
);
1194 _handle_server_fence_msg: function() {
1195 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1196 this._sock
.rQskipBytes(3); // Padding
1197 var flags
= this._sock
.rQshift32();
1198 var length
= this._sock
.rQshift8();
1200 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1203 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1207 var payload
= this._sock
.rQshiftStr(length
);
1209 this._supportsFence
= true;
1214 * (1<<0) - BlockBefore
1215 * (1<<1) - BlockAfter
1220 if (!(flags
& (1<<31))) {
1221 return this._fail("Internal error",
1222 "Unexpected fence response");
1225 // Filter out unsupported flags
1226 // FIXME: support syncNext
1227 flags
&= (1<<0) | (1<<1);
1229 // BlockBefore and BlockAfter are automatically handled by
1230 // the fact that we process each incoming message
1232 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1237 _handle_xvp_msg: function () {
1238 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1239 this._sock
.rQskip8(); // Padding
1240 var xvp_ver
= this._sock
.rQshift8();
1241 var xvp_msg
= this._sock
.rQshift8();
1245 Log
.Error("Operation Failed");
1246 this._notification("XVP Operation Failed", 'error');
1249 this._rfb_xvp_ver
= xvp_ver
;
1250 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1251 this._onXvpInit(this._rfb_xvp_ver
);
1254 this._fail("Unexpected server message",
1255 "Illegal server XVP message " + xvp_msg
);
1262 _normal_msg: function () {
1265 if (this._FBU
.rects
> 0) {
1268 msg_type
= this._sock
.rQshift8();
1272 case 0: // FramebufferUpdate
1273 var ret
= this._framebufferUpdate();
1274 if (ret
&& !this._enabledContinuousUpdates
) {
1275 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1276 this._fb_width
, this._fb_height
);
1280 case 1: // SetColorMapEntries
1281 return this._handle_set_colour_map_msg();
1288 case 3: // ServerCutText
1289 return this._handle_server_cut_text();
1291 case 150: // EndOfContinuousUpdates
1292 var first
= !(this._supportsContinuousUpdates
);
1293 this._supportsContinuousUpdates
= true;
1294 this._enabledContinuousUpdates
= false;
1296 this._enabledContinuousUpdates
= true;
1297 this._updateContinuousUpdates();
1298 Log
.Info("Enabling continuous updates.");
1300 // FIXME: We need to send a framebufferupdaterequest here
1301 // if we add support for turning off continuous updates
1305 case 248: // ServerFence
1306 return this._handle_server_fence_msg();
1309 return this._handle_xvp_msg();
1312 this._fail("Unexpected server message", "Type:" + msg_type
);
1313 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1318 _onFlush: function() {
1319 this._flushing
= false;
1320 // Resume processing
1321 if (this._sock
.rQlen() > 0) {
1322 this._handle_message();
1326 _framebufferUpdate: function () {
1330 if (this._FBU
.rects
=== 0) {
1331 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1332 this._sock
.rQskip8(); // Padding
1333 this._FBU
.rects
= this._sock
.rQshift16();
1334 this._FBU
.bytes
= 0;
1335 this._timing
.cur_fbu
= 0;
1336 if (this._timing
.fbu_rt_start
> 0) {
1337 now
= (new Date()).getTime();
1338 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1341 // Make sure the previous frame is fully rendered first
1342 // to avoid building up an excessive queue
1343 if (this._display
.pending()) {
1344 this._flushing
= true;
1345 this._display
.flush();
1350 while (this._FBU
.rects
> 0) {
1351 if (this._rfb_connection_state
!== 'connected') { return false; }
1353 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1354 if (this._FBU
.bytes
=== 0) {
1355 if (this._sock
.rQwait("rect header", 12)) { return false; }
1356 /* New FramebufferUpdate */
1358 var hdr
= this._sock
.rQshiftBytes(12);
1359 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1360 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1361 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1362 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1363 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1364 (hdr
[10] << 8) + hdr
[11], 10);
1366 this._onFBUReceive(this,
1367 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1368 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1369 'encoding': this._FBU
.encoding
,
1370 'encodingName': encodingName(this._FBU
.encoding
)});
1372 if (!this._encHandlers
[this._FBU
.encoding
]) {
1373 this._fail("Unexpected server message",
1374 "Unsupported encoding " +
1375 this._FBU
.encoding
);
1380 this._timing
.last_fbu
= (new Date()).getTime();
1382 ret
= this._encHandlers
[this._FBU
.encoding
]();
1384 now
= (new Date()).getTime();
1385 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1388 if (!(this._FBU
.encoding
in this._encStats
)) {
1389 this._encStats
[this._FBU
.encoding
] = [0, 0];
1391 this._encStats
[this._FBU
.encoding
][0]++;
1392 this._encStats
[this._FBU
.encoding
][1]++;
1393 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1396 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1397 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1398 this._timing
.fbu_rt_start
> 0) {
1399 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1400 this._timing
.full_fbu_cnt
++;
1401 Log
.Info("Timing of full FBU, curr: " +
1402 this._timing
.cur_fbu
+ ", total: " +
1403 this._timing
.full_fbu_total
+ ", cnt: " +
1404 this._timing
.full_fbu_cnt
+ ", avg: " +
1405 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1408 if (this._timing
.fbu_rt_start
> 0) {
1409 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1410 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1411 this._timing
.fbu_rt_cnt
++;
1412 Log
.Info("full FBU round-trip, cur: " +
1413 fbu_rt_diff
+ ", total: " +
1414 this._timing
.fbu_rt_total
+ ", cnt: " +
1415 this._timing
.fbu_rt_cnt
+ ", avg: " +
1416 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1417 this._timing
.fbu_rt_start
= 0;
1421 if (!ret
) { return ret
; } // need more data
1424 this._display
.flip();
1426 this._onFBUComplete(this);
1428 return true; // We finished this FBU
1431 _updateContinuousUpdates: function() {
1432 if (!this._enabledContinuousUpdates
) { return; }
1434 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1435 this._fb_width
, this._fb_height
);
1438 _resize: function(width
, height
) {
1439 this._fb_width
= width
;
1440 this._fb_height
= height
;
1442 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1444 this._display
.resize(this._fb_width
, this._fb_height
);
1445 this._onFBResize(this, this._fb_width
, this._fb_height
);
1447 this._timing
.fbu_rt_start
= (new Date()).getTime();
1448 this._updateContinuousUpdates();
1452 make_properties(RFB
, [
1453 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1454 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1455 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1456 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1457 ['shared', 'rw', 'bool'], // Request shared mode
1458 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1459 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1460 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1461 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1462 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1463 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1465 // Callback functions
1466 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1467 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1468 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1469 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1470 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1471 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1472 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1473 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1474 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1475 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1476 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1479 RFB
.prototype.set_local_cursor = function (cursor
) {
1480 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1481 this._local_cursor
= false;
1482 this._display
.disableLocalCursor(); //Only show server-side cursor
1484 if (this._display
.get_cursor_uri()) {
1485 this._local_cursor
= true;
1487 Log
.Warn("Browser does not support local cursor");
1488 this._display
.disableLocalCursor();
1492 // Need to send an updated list of encodings if we are connected
1493 if (this._rfb_connection_state
=== "connected") {
1494 this._sendEncodings();
1498 RFB
.prototype.set_view_only = function (view_only
) {
1499 this._view_only
= view_only
;
1501 if (this._rfb_connection_state
=== "connecting" ||
1502 this._rfb_connection_state
=== "connected") {
1504 this._keyboard
.ungrab();
1505 this._mouse
.ungrab();
1507 this._keyboard
.grab();
1513 RFB
.prototype.get_display = function () { return this._display
; };
1514 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1515 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1519 keyEvent: function (sock
, keysym
, down
) {
1520 var buff
= sock
._sQ
;
1521 var offset
= sock
._sQlen
;
1523 buff
[offset
] = 4; // msg-type
1524 buff
[offset
+ 1] = down
;
1526 buff
[offset
+ 2] = 0;
1527 buff
[offset
+ 3] = 0;
1529 buff
[offset
+ 4] = (keysym
>> 24);
1530 buff
[offset
+ 5] = (keysym
>> 16);
1531 buff
[offset
+ 6] = (keysym
>> 8);
1532 buff
[offset
+ 7] = keysym
;
1538 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1539 function getRFBkeycode(xt_scancode
) {
1540 var upperByte
= (keycode
>> 8);
1541 var lowerByte
= (keycode
& 0x00ff);
1542 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1543 lowerByte
= lowerByte
| 0x80;
1549 var buff
= sock
._sQ
;
1550 var offset
= sock
._sQlen
;
1552 buff
[offset
] = 255; // msg-type
1553 buff
[offset
+ 1] = 0; // sub msg-type
1555 buff
[offset
+ 2] = (down
>> 8);
1556 buff
[offset
+ 3] = down
;
1558 buff
[offset
+ 4] = (keysym
>> 24);
1559 buff
[offset
+ 5] = (keysym
>> 16);
1560 buff
[offset
+ 6] = (keysym
>> 8);
1561 buff
[offset
+ 7] = keysym
;
1563 var RFBkeycode
= getRFBkeycode(keycode
);
1565 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1566 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1567 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1568 buff
[offset
+ 11] = RFBkeycode
;
1574 pointerEvent: function (sock
, x
, y
, mask
) {
1575 var buff
= sock
._sQ
;
1576 var offset
= sock
._sQlen
;
1578 buff
[offset
] = 5; // msg-type
1580 buff
[offset
+ 1] = mask
;
1582 buff
[offset
+ 2] = x
>> 8;
1583 buff
[offset
+ 3] = x
;
1585 buff
[offset
+ 4] = y
>> 8;
1586 buff
[offset
+ 5] = y
;
1592 // TODO(directxman12): make this unicode compatible?
1593 clientCutText: function (sock
, text
) {
1594 var buff
= sock
._sQ
;
1595 var offset
= sock
._sQlen
;
1597 buff
[offset
] = 6; // msg-type
1599 buff
[offset
+ 1] = 0; // padding
1600 buff
[offset
+ 2] = 0; // padding
1601 buff
[offset
+ 3] = 0; // padding
1603 var n
= text
.length
;
1605 buff
[offset
+ 4] = n
>> 24;
1606 buff
[offset
+ 5] = n
>> 16;
1607 buff
[offset
+ 6] = n
>> 8;
1608 buff
[offset
+ 7] = n
;
1610 for (var i
= 0; i
< n
; i
++) {
1611 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1614 sock
._sQlen
+= 8 + n
;
1618 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1619 var buff
= sock
._sQ
;
1620 var offset
= sock
._sQlen
;
1622 buff
[offset
] = 251; // msg-type
1623 buff
[offset
+ 1] = 0; // padding
1624 buff
[offset
+ 2] = width
>> 8; // width
1625 buff
[offset
+ 3] = width
;
1626 buff
[offset
+ 4] = height
>> 8; // height
1627 buff
[offset
+ 5] = height
;
1629 buff
[offset
+ 6] = 1; // number-of-screens
1630 buff
[offset
+ 7] = 0; // padding
1633 buff
[offset
+ 8] = id
>> 24; // id
1634 buff
[offset
+ 9] = id
>> 16;
1635 buff
[offset
+ 10] = id
>> 8;
1636 buff
[offset
+ 11] = id
;
1637 buff
[offset
+ 12] = 0; // x-position
1638 buff
[offset
+ 13] = 0;
1639 buff
[offset
+ 14] = 0; // y-position
1640 buff
[offset
+ 15] = 0;
1641 buff
[offset
+ 16] = width
>> 8; // width
1642 buff
[offset
+ 17] = width
;
1643 buff
[offset
+ 18] = height
>> 8; // height
1644 buff
[offset
+ 19] = height
;
1645 buff
[offset
+ 20] = flags
>> 24; // flags
1646 buff
[offset
+ 21] = flags
>> 16;
1647 buff
[offset
+ 22] = flags
>> 8;
1648 buff
[offset
+ 23] = flags
;
1654 clientFence: function (sock
, flags
, payload
) {
1655 var buff
= sock
._sQ
;
1656 var offset
= sock
._sQlen
;
1658 buff
[offset
] = 248; // msg-type
1660 buff
[offset
+ 1] = 0; // padding
1661 buff
[offset
+ 2] = 0; // padding
1662 buff
[offset
+ 3] = 0; // padding
1664 buff
[offset
+ 4] = flags
>> 24; // flags
1665 buff
[offset
+ 5] = flags
>> 16;
1666 buff
[offset
+ 6] = flags
>> 8;
1667 buff
[offset
+ 7] = flags
;
1669 var n
= payload
.length
;
1671 buff
[offset
+ 8] = n
; // length
1673 for (var i
= 0; i
< n
; i
++) {
1674 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1677 sock
._sQlen
+= 9 + n
;
1681 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1682 var buff
= sock
._sQ
;
1683 var offset
= sock
._sQlen
;
1685 buff
[offset
] = 150; // msg-type
1686 buff
[offset
+ 1] = enable
; // enable-flag
1688 buff
[offset
+ 2] = x
>> 8; // x
1689 buff
[offset
+ 3] = x
;
1690 buff
[offset
+ 4] = y
>> 8; // y
1691 buff
[offset
+ 5] = y
;
1692 buff
[offset
+ 6] = width
>> 8; // width
1693 buff
[offset
+ 7] = width
;
1694 buff
[offset
+ 8] = height
>> 8; // height
1695 buff
[offset
+ 9] = height
;
1701 pixelFormat: function (sock
, depth
, true_color
) {
1702 var buff
= sock
._sQ
;
1703 var offset
= sock
._sQlen
;
1709 } else if (depth
> 8) {
1715 bits
= Math
.floor(depth
/3);
1717 buff
[offset
] = 0; // msg-type
1719 buff
[offset
+ 1] = 0; // padding
1720 buff
[offset
+ 2] = 0; // padding
1721 buff
[offset
+ 3] = 0; // padding
1723 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1724 buff
[offset
+ 5] = depth
; // depth
1725 buff
[offset
+ 6] = 0; // little-endian
1726 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1728 buff
[offset
+ 8] = 0; // red-max
1729 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1731 buff
[offset
+ 10] = 0; // green-max
1732 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1734 buff
[offset
+ 12] = 0; // blue-max
1735 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1737 buff
[offset
+ 14] = bits
* 2; // red-shift
1738 buff
[offset
+ 15] = bits
* 1; // green-shift
1739 buff
[offset
+ 16] = bits
* 0; // blue-shift
1741 buff
[offset
+ 17] = 0; // padding
1742 buff
[offset
+ 18] = 0; // padding
1743 buff
[offset
+ 19] = 0; // padding
1749 clientEncodings: function (sock
, encodings
) {
1750 var buff
= sock
._sQ
;
1751 var offset
= sock
._sQlen
;
1753 buff
[offset
] = 2; // msg-type
1754 buff
[offset
+ 1] = 0; // padding
1756 buff
[offset
+ 2] = encodings
.length
>> 8;
1757 buff
[offset
+ 3] = encodings
.length
;
1759 var i
, j
= offset
+ 4;
1760 for (i
= 0; i
< encodings
.length
; i
++) {
1761 var enc
= encodings
[i
];
1762 buff
[j
] = enc
>> 24;
1763 buff
[j
+ 1] = enc
>> 16;
1764 buff
[j
+ 2] = enc
>> 8;
1770 sock
._sQlen
+= j
- offset
;
1774 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1775 var buff
= sock
._sQ
;
1776 var offset
= sock
._sQlen
;
1778 if (typeof(x
) === "undefined") { x
= 0; }
1779 if (typeof(y
) === "undefined") { y
= 0; }
1781 buff
[offset
] = 3; // msg-type
1782 buff
[offset
+ 1] = incremental
? 1 : 0;
1784 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1785 buff
[offset
+ 3] = x
& 0xFF;
1787 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1788 buff
[offset
+ 5] = y
& 0xFF;
1790 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1791 buff
[offset
+ 7] = w
& 0xFF;
1793 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1794 buff
[offset
+ 9] = h
& 0xFF;
1801 RFB
.genDES = function (password
, challenge
) {
1803 for (var i
= 0; i
< password
.length
; i
++) {
1804 passwd
.push(password
.charCodeAt(i
));
1806 return (new DES(passwd
)).encrypt(challenge
);
1809 RFB
.encodingHandlers
= {
1811 if (this._FBU
.lines
=== 0) {
1812 this._FBU
.lines
= this._FBU
.height
;
1815 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1816 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1817 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1818 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1819 var curr_height
= Math
.min(this._FBU
.lines
,
1820 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1821 var data
= this._sock
.get_rQ();
1822 var index
= this._sock
.get_rQi();
1823 if (this._fb_depth
== 8) {
1824 var pixels
= this._FBU
.width
* curr_height
1825 var newdata
= new Uint8Array(pixels
* 4);
1827 for (i
= 0;i
< pixels
;i
++) {
1828 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1829 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1830 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1831 newdata
[i
* 4 + 4] = 0;
1836 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1837 curr_height
, data
, index
);
1838 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1839 this._FBU
.lines
-= curr_height
;
1841 if (this._FBU
.lines
> 0) {
1842 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1845 this._FBU
.bytes
= 0;
1851 COPYRECT: function () {
1852 this._FBU
.bytes
= 4;
1853 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1854 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1855 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1859 this._FBU
.bytes
= 0;
1865 if (this._FBU
.subrects
=== 0) {
1866 this._FBU
.bytes
= 4 + 4;
1867 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1868 this._FBU
.subrects
= this._sock
.rQshift32();
1869 color
= this._sock
.rQshiftBytes(4); // Background
1870 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1873 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1874 color
= this._sock
.rQshiftBytes(4);
1875 var x
= this._sock
.rQshift16();
1876 var y
= this._sock
.rQshift16();
1877 var width
= this._sock
.rQshift16();
1878 var height
= this._sock
.rQshift16();
1879 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1880 this._FBU
.subrects
--;
1883 if (this._FBU
.subrects
> 0) {
1884 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1885 this._FBU
.bytes
= (4 + 8) * chunk
;
1888 this._FBU
.bytes
= 0;
1894 HEXTILE: function () {
1895 var rQ
= this._sock
.get_rQ();
1896 var rQi
= this._sock
.get_rQi();
1898 if (this._FBU
.tiles
=== 0) {
1899 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1900 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1901 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1902 this._FBU
.tiles
= this._FBU
.total_tiles
;
1905 while (this._FBU
.tiles
> 0) {
1906 this._FBU
.bytes
= 1;
1907 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1908 var subencoding
= rQ
[rQi
]; // Peek
1909 if (subencoding
> 30) { // Raw
1910 this._fail("Unexpected server message",
1911 "Illegal hextile subencoding: " + subencoding
);
1916 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1917 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1918 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1919 var x
= this._FBU
.x
+ tile_x
* 16;
1920 var y
= this._FBU
.y
+ tile_y
* 16;
1921 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1922 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1924 // Figure out how much we are expecting
1925 if (subencoding
& 0x01) { // Raw
1926 this._FBU
.bytes
+= w
* h
* 4;
1928 if (subencoding
& 0x02) { // Background
1929 this._FBU
.bytes
+= 4;
1931 if (subencoding
& 0x04) { // Foreground
1932 this._FBU
.bytes
+= 4;
1934 if (subencoding
& 0x08) { // AnySubrects
1935 this._FBU
.bytes
++; // Since we aren't shifting it off
1936 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1937 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1938 if (subencoding
& 0x10) { // SubrectsColoured
1939 this._FBU
.bytes
+= subrects
* (4 + 2);
1941 this._FBU
.bytes
+= subrects
* 2;
1946 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1948 // We know the encoding and have a whole tile
1949 this._FBU
.subencoding
= rQ
[rQi
];
1951 if (this._FBU
.subencoding
=== 0) {
1952 if (this._FBU
.lastsubencoding
& 0x01) {
1953 // Weird: ignore blanks are RAW
1954 Log
.Debug(" Ignoring blank after RAW");
1956 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1958 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1959 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1960 rQi
+= this._FBU
.bytes
- 1;
1962 if (this._FBU
.subencoding
& 0x02) { // Background
1963 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1966 if (this._FBU
.subencoding
& 0x04) { // Foreground
1967 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1971 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1972 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1976 for (var s
= 0; s
< subrects
; s
++) {
1978 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1979 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1982 color
= this._FBU
.foreground
;
1987 var sy
= (xy
& 0x0f);
1991 var sw
= (wh
>> 4) + 1;
1992 var sh
= (wh
& 0x0f) + 1;
1994 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1997 this._display
.finishTile();
1999 this._sock
.set_rQi(rQi
);
2000 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2001 this._FBU
.bytes
= 0;
2005 if (this._FBU
.tiles
=== 0) {
2012 TIGHT: function () {
2013 this._FBU
.bytes
= 1; // compression-control byte
2014 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2016 var checksum = function (data
) {
2018 for (var i
= 0; i
< data
.length
; i
++) {
2020 if (sum
> 65536) sum
-= 65536;
2025 var resetStreams
= 0;
2027 var decompress = function (data
, expected
) {
2028 for (var i
= 0; i
< 4; i
++) {
2029 if ((resetStreams
>> i
) & 1) {
2030 this._FBU
.zlibs
[i
].reset();
2031 Log
.Info("Reset zlib stream " + i
);
2035 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2036 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2037 /*if (uncompressed.status !== 0) {
2038 Log.Error("Invalid data in zlib stream");
2041 //return uncompressed.data;
2042 return uncompressed
;
2045 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2046 // Convert indexed (palette based) image data to RGB
2047 // TODO: reduce number of calculations inside loop
2048 var dest
= this._destBuff
;
2049 var w
= Math
.floor((width
+ 7) / 8);
2050 var w1
= Math
.floor(width
/ 8);
2052 /*for (var y = 0; y < height; y++) {
2054 var yoffset = y * width;
2055 var ybitoffset = y * w;
2056 var xoffset, targetbyte;
2057 for (x = 0; x < w1; x++) {
2058 xoffset = yoffset + x * 8;
2059 targetbyte = data[ybitoffset + x];
2060 for (b = 7; b >= 0; b--) {
2061 dp = (xoffset + 7 - b) * 3;
2062 sp = (targetbyte >> b & 1) * 3;
2063 dest[dp] = palette[sp];
2064 dest[dp + 1] = palette[sp + 1];
2065 dest[dp + 2] = palette[sp + 2];
2069 xoffset = yoffset + x * 8;
2070 targetbyte = data[ybitoffset + x];
2071 for (b = 7; b >= 8 - width % 8; b--) {
2072 dp = (xoffset + 7 - b) * 3;
2073 sp = (targetbyte >> b & 1) * 3;
2074 dest[dp] = palette[sp];
2075 dest[dp + 1] = palette[sp + 1];
2076 dest[dp + 2] = palette[sp + 2];
2080 for (var y
= 0; y
< height
; y
++) {
2082 for (x
= 0; x
< w1
; x
++) {
2083 for (b
= 7; b
>= 0; b
--) {
2084 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2085 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2086 dest
[dp
] = palette
[sp
];
2087 dest
[dp
+ 1] = palette
[sp
+ 1];
2088 dest
[dp
+ 2] = palette
[sp
+ 2];
2093 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2094 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2095 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2096 dest
[dp
] = palette
[sp
];
2097 dest
[dp
+ 1] = palette
[sp
+ 1];
2098 dest
[dp
+ 2] = palette
[sp
+ 2];
2106 var indexedToRGBX = function (data
, palette
, width
, height
) {
2107 // Convert indexed (palette based) image data to RGB
2108 var dest
= this._destBuff
;
2109 var total
= width
* height
* 4;
2110 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2111 var sp
= data
[j
] * 3;
2112 dest
[i
] = palette
[sp
];
2113 dest
[i
+ 1] = palette
[sp
+ 1];
2114 dest
[i
+ 2] = palette
[sp
+ 2];
2121 var rQi
= this._sock
.get_rQi();
2122 var rQ
= this._sock
.rQwhole();
2124 var cl_header
, cl_data
;
2126 var handlePalette = function () {
2127 var numColors
= rQ
[rQi
+ 2] + 1;
2128 var paletteSize
= numColors
* 3;
2129 this._FBU
.bytes
+= paletteSize
;
2130 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2132 var bpp
= (numColors
<= 2) ? 1 : 8;
2133 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2135 if (rowSize
* this._FBU
.height
< 12) {
2138 cl_data
= rowSize
* this._FBU
.height
;
2139 //clength = [0, rowSize * this._FBU.height];
2141 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2142 var cl_offset
= rQi
+ 3 + paletteSize
;
2145 cl_data
+= rQ
[cl_offset
] & 0x7f;
2146 if (rQ
[cl_offset
] & 0x80) {
2148 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2149 if (rQ
[cl_offset
+ 1] & 0x80) {
2151 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2154 // end inline getTightCLength
2157 this._FBU
.bytes
+= cl_header
+ cl_data
;
2158 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2160 // Shift ctl, filter id, num colors, palette entries, and clength off
2161 this._sock
.rQskipBytes(3);
2162 //var palette = this._sock.rQshiftBytes(paletteSize);
2163 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2164 this._sock
.rQskipBytes(cl_header
);
2167 data
= this._sock
.rQshiftBytes(cl_data
);
2169 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2172 // Convert indexed (palette based) image data to RGB
2174 if (numColors
== 2) {
2175 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2176 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2178 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2179 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2186 var handleCopy = function () {
2188 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2189 if (uncompressedSize
< 12) {
2192 cl_data
= uncompressedSize
;
2194 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2195 var cl_offset
= rQi
+ 1;
2198 cl_data
+= rQ
[cl_offset
] & 0x7f;
2199 if (rQ
[cl_offset
] & 0x80) {
2201 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2202 if (rQ
[cl_offset
+ 1] & 0x80) {
2204 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2207 // end inline getTightCLength
2209 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2210 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2212 // Shift ctl, clength off
2213 this._sock
.rQshiftBytes(1 + cl_header
);
2216 data
= this._sock
.rQshiftBytes(cl_data
);
2218 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2221 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2226 var ctl
= this._sock
.rQpeek8();
2228 // Keep tight reset bits
2229 resetStreams
= ctl
& 0xF;
2231 // Figure out filter
2233 streamId
= ctl
& 0x3;
2235 if (ctl
=== 0x08) cmode
= "fill";
2236 else if (ctl
=== 0x09) cmode
= "jpeg";
2237 else if (ctl
=== 0x0A) cmode
= "png";
2238 else if (ctl
& 0x04) cmode
= "filter";
2239 else if (ctl
< 0x04) cmode
= "copy";
2240 else return this._fail("Unexpected server message",
2241 "Illegal tight compression received, " +
2245 // fill use depth because TPIXELs drop the padding byte
2246 case "fill": // TPIXEL
2247 this._FBU
.bytes
+= 3;
2249 case "jpeg": // max clength
2250 this._FBU
.bytes
+= 3;
2252 case "png": // max clength
2253 this._FBU
.bytes
+= 3;
2255 case "filter": // filter id + num colors if palette
2256 this._FBU
.bytes
+= 2;
2262 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2264 // Determine FBU.bytes
2268 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);
2269 this._sock
.rQskipBytes(4);
2273 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2274 var cl_offset
= rQi
+ 1;
2277 cl_data
+= rQ
[cl_offset
] & 0x7f;
2278 if (rQ
[cl_offset
] & 0x80) {
2280 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2281 if (rQ
[cl_offset
+ 1] & 0x80) {
2283 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2286 // end inline getTightCLength
2287 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2288 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2290 // We have everything, render it
2291 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2292 data
= this._sock
.rQshiftBytes(cl_data
);
2293 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2296 var filterId
= rQ
[rQi
+ 1];
2297 if (filterId
=== 1) {
2298 if (!handlePalette()) { return false; }
2300 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2301 // Filter 2, Gradient is valid but not use if jpeg is enabled
2302 this._fail("Unexpected server message",
2303 "Unsupported tight subencoding received, " +
2304 "filter: " + filterId
);
2308 if (!handleCopy()) { return false; }
2313 this._FBU
.bytes
= 0;
2319 last_rect: function () {
2320 this._FBU
.rects
= 0;
2324 ExtendedDesktopSize: function () {
2325 this._FBU
.bytes
= 1;
2326 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2328 this._supportsSetDesktopSize
= true;
2329 var number_of_screens
= this._sock
.rQpeek8();
2331 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2332 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2334 this._sock
.rQskipBytes(1); // number-of-screens
2335 this._sock
.rQskipBytes(3); // padding
2337 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2338 // Save the id and flags of the first screen
2340 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2341 this._sock
.rQskipBytes(2); // x-position
2342 this._sock
.rQskipBytes(2); // y-position
2343 this._sock
.rQskipBytes(2); // width
2344 this._sock
.rQskipBytes(2); // height
2345 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2347 this._sock
.rQskipBytes(16);
2352 * The x-position indicates the reason for the change:
2354 * 0 - server resized on its own
2355 * 1 - this client requested the resize
2356 * 2 - another client requested the resize
2359 // We need to handle errors when we requested the resize.
2360 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2362 // The y-position indicates the status code from the server
2363 switch (this._FBU
.y
) {
2365 msg
= "Resize is administratively prohibited";
2368 msg
= "Out of resources";
2371 msg
= "Invalid screen layout";
2374 msg
= "Unknown reason";
2377 this._notification("Server did not accept the resize request: "
2380 this._resize(this._FBU
.width
, this._FBU
.height
);
2383 this._FBU
.bytes
= 0;
2384 this._FBU
.rects
-= 1;
2388 DesktopSize: function () {
2389 this._resize(this._FBU
.width
, this._FBU
.height
);
2390 this._FBU
.bytes
= 0;
2391 this._FBU
.rects
-= 1;
2395 Cursor: function () {
2396 Log
.Debug(">> set_cursor");
2397 var x
= this._FBU
.x
; // hotspot-x
2398 var y
= this._FBU
.y
; // hotspot-y
2399 var w
= this._FBU
.width
;
2400 var h
= this._FBU
.height
;
2402 var pixelslength
= w
* h
* 4;
2403 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2405 this._FBU
.bytes
= pixelslength
+ masklength
;
2406 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2408 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2409 this._sock
.rQshiftBytes(masklength
),
2412 this._FBU
.bytes
= 0;
2415 Log
.Debug("<< set_cursor");
2419 QEMUExtendedKeyEvent: function () {
2422 // Old Safari doesn't support creating keyboard events
2424 var keyboardEvent
= document
.createEvent("keyboardEvent");
2425 if (keyboardEvent
.code
!== undefined) {
2426 this._qemuExtKeyEventSupported
= true;