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";
26 /*jslint white: false, browser: true */
27 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
29 export default function RFB(defaults
) {
36 this._rfb_port
= 5900;
37 this._rfb_password
= '';
40 this._rfb_connection_state
= '';
41 this._rfb_init_state
= '';
42 this._rfb_version
= 0;
43 this._rfb_max_version
= 3.8;
44 this._rfb_auth_scheme
= '';
45 this._rfb_disconnect_reason
= "";
47 this._rfb_tightvnc
= false;
48 this._rfb_xvp_ver
= 0;
50 // In preference order
59 // Psuedo-encoding settings
61 //['JPEG_quality_lo', -32 ],
62 ['JPEG_quality_med', -26 ],
63 //['JPEG_quality_hi', -23 ],
64 //['compress_lo', -255 ],
65 ['compress_hi', -254 ],
66 //['compress_max', -247 ],
68 ['DesktopSize', -223 ],
71 ['QEMUExtendedKeyEvent', -258 ],
72 ['ExtendedDesktopSize', -308 ],
75 ['ContinuousUpdates', -313 ]
78 this._encHandlers
= {};
82 this._sock
= null; // Websock object
83 this._display
= null; // Display object
84 this._flushing
= false; // Display flushing state
85 this._keyboard
= null; // Keyboard input handler object
86 this._mouse
= null; // Mouse input handler object
87 this._disconnTimer
= null; // disconnection timer
89 this._supportsFence
= false;
91 this._supportsContinuousUpdates
= false;
92 this._enabledContinuousUpdates
= false;
94 // Frame buffer update state
108 zlib
: [] // TIGHT zlib streams
117 this._destBuff
= null;
118 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
120 this._rre_chunk_sz
= 100;
135 this._supportsSetDesktopSize
= false;
137 this._screen_flags
= 0;
140 this._mouse_buttonMask
= 0;
141 this._mouse_arr
= [];
142 this._viewportDragging
= false;
143 this._viewportDragPos
= {};
144 this._viewportHasMoved
= false;
146 // QEMU Extended Key Event support - default to false
147 this._qemuExtKeyEventSupported
= false;
149 // set the default value on user-facing properties
150 set_defaults(this, defaults
, {
151 'target': 'null', // VNC display rendering Canvas object
152 'focusContainer': document
, // DOM element that captures keyboard input
153 'encrypt': false, // Use TLS/SSL/wss encryption
154 'true_color': true, // Request true color pixel data
155 'local_cursor': false, // Request locally rendered cursor
156 'shared': true, // Request shared mode
157 'view_only': false, // Disable client mouse/keyboard
158 'xvp_password_sep': '@', // Separator for XVP password fields
159 'disconnectTimeout': 3, // Time (s) to wait for disconnection
160 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
161 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
162 'viewportDrag': false, // Move the viewport on mouse drags
164 // Callback functions
165 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
166 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
167 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
168 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
169 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
170 'onBell': function () { }, // onBell(rfb): RFB Bell message received
171 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
172 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
173 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
174 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
175 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
179 Log
.Debug(">> RFB.constructor");
181 // populate encHandlers with bound versions
182 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
183 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
186 // Create lookup tables based on encoding number
187 for (var i
= 0; i
< this._encodings
.length
; i
++) {
188 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
189 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
190 this._encStats
[this._encodings
[i
][1]] = [0, 0];
193 // NB: nothing that needs explicit teardown should be done
194 // before this point, since this can throw an exception
196 this._display
= new Display({target
: this._target
,
197 onFlush
: this._onFlush
.bind(this)});
199 Log
.Error("Display exception: " + exc
);
203 this._keyboard
= new Keyboard({target
: this._focusContainer
,
204 onKeyEvent
: this._handleKeyEvent
.bind(this)});
206 this._mouse
= new Mouse({target
: this._target
,
207 onMouseButton
: this._handleMouseButton
.bind(this),
208 onMouseMove
: this._handleMouseMove
.bind(this)});
210 this._sock
= new Websock();
211 this._sock
.on('message', this._handle_message
.bind(this));
212 this._sock
.on('open', function () {
213 if ((this._rfb_connection_state
=== 'connecting') &&
214 (this._rfb_init_state
=== '')) {
215 this._rfb_init_state
= 'ProtocolVersion';
216 Log
.Debug("Starting VNC handshake");
218 this._fail("Unexpected server connection");
221 this._sock
.on('close', function (e
) {
222 Log
.Warn("WebSocket on-close event");
225 msg
= " (code: " + e
.code
;
227 msg
+= ", reason: " + e
.reason
;
231 switch (this._rfb_connection_state
) {
232 case 'disconnecting':
233 this._updateConnectionState('disconnected');
236 this._fail('Failed to connect to server', msg
);
239 // Handle disconnects that were initiated server-side
240 this._updateConnectionState('disconnecting');
241 this._updateConnectionState('disconnected');
244 this._fail("Unexpected server disconnect",
245 "Already disconnected: " + msg
);
248 this._fail("Unexpected server disconnect",
249 "Not in any state yet: " + msg
);
252 this._sock
.off('close');
254 this._sock
.on('error', function (e
) {
255 Log
.Warn("WebSocket on-error event");
261 var rmode
= this._display
.get_render_mode();
262 Log
.Info("Using native WebSockets, render mode: " + rmode
);
264 Log
.Debug("<< RFB.constructor");
269 connect: function (host
, port
, password
, path
) {
270 this._rfb_host
= host
;
271 this._rfb_port
= port
;
272 this._rfb_password
= (password
!== undefined) ? password
: "";
273 this._rfb_path
= (path
!== undefined) ? path
: "";
275 if (!this._rfb_host
|| !this._rfb_port
) {
277 _("Must set host and port"));
280 this._rfb_init_state
= '';
281 this._updateConnectionState('connecting');
285 disconnect: function () {
286 this._updateConnectionState('disconnecting');
287 this._sock
.off('error');
288 this._sock
.off('message');
289 this._sock
.off('open');
292 sendPassword: function (passwd
) {
293 this._rfb_password
= passwd
;
294 setTimeout(this._init_msg
.bind(this), 0);
297 sendCtrlAltDel: function () {
298 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
299 Log
.Info("Sending Ctrl-Alt-Del");
301 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
302 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
303 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
304 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
305 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
306 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
311 xvpOp: function (ver
, op
) {
312 if (this._rfb_xvp_ver
< ver
) { return false; }
313 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
314 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
318 xvpShutdown: function () {
319 return this.xvpOp(1, 2);
322 xvpReboot: function () {
323 return this.xvpOp(1, 3);
326 xvpReset: function () {
327 return this.xvpOp(1, 4);
330 // Send a key press. If 'down' is not specified then send a down key
331 // followed by an up key.
332 sendKey: function (keysym
, code
, down
) {
333 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
335 if (down
=== undefined) {
336 this.sendKey(keysym
, code
, true);
337 this.sendKey(keysym
, code
, false);
341 if (this._qemuExtKeyEventSupported
) {
342 var scancode
= XtScancode
[code
];
344 if (scancode
=== undefined) {
345 Log
.Error('Unable to find a xt scancode for code: ' + code
);
346 // FIXME: not in the spec, but this is what
351 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
353 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
355 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
356 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
362 clipboardPasteFrom: function (text
) {
363 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
364 RFB
.messages
.clientCutText(this._sock
, text
);
367 // Requests a change of remote desktop size. This message is an extension
368 // and may only be sent if we have received an ExtendedDesktopSize message
369 requestDesktopSize: function (width
, height
) {
370 if (this._rfb_connection_state
!== 'connected' ||
375 if (this._supportsSetDesktopSize
) {
376 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
377 this._screen_id
, this._screen_flags
);
388 _connect: function () {
389 Log
.Debug(">> RFB.connect");
393 if (typeof UsingSocketIO
!== 'undefined') {
396 uri
= this._encrypt
? 'wss' : 'ws';
399 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
400 Log
.Info("connecting to " + uri
);
403 // WebSocket.onopen transitions to the RFB init states
404 this._sock
.open(uri
, this._wsProtocols
);
406 if (e
.name
=== 'SyntaxError') {
407 this._fail("Invalid host or port value given", e
);
409 this._fail("Error while connecting", e
);
413 Log
.Debug("<< RFB.connect");
416 _disconnect: function () {
417 Log
.Debug(">> RFB.disconnect");
421 Log
.Debug("<< RFB.disconnect");
424 _init_vars: function () {
427 this._FBU
.subrects
= 0; // RRE and HEXTILE
428 this._FBU
.lines
= 0; // RAW
429 this._FBU
.tiles
= 0; // HEXTILE
430 this._FBU
.zlibs
= []; // TIGHT zlib encoders
431 this._mouse_buttonMask
= 0;
432 this._mouse_arr
= [];
433 this._rfb_tightvnc
= false;
435 // Clear the per connection encoding stats
437 for (i
= 0; i
< this._encodings
.length
; i
++) {
438 this._encStats
[this._encodings
[i
][1]][0] = 0;
441 for (i
= 0; i
< 4; i
++) {
442 this._FBU
.zlibs
[i
] = new Inflator();
446 _print_stats: function () {
447 Log
.Info("Encoding stats for this connection:");
449 for (i
= 0; i
< this._encodings
.length
; i
++) {
450 s
= this._encStats
[this._encodings
[i
][1]];
451 if (s
[0] + s
[1] > 0) {
452 Log
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
456 Log
.Info("Encoding stats since page load:");
457 for (i
= 0; i
< this._encodings
.length
; i
++) {
458 s
= this._encStats
[this._encodings
[i
][1]];
459 Log
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
463 _cleanup: function () {
464 if (!this._view_only
) { this._keyboard
.ungrab(); }
465 if (!this._view_only
) { this._mouse
.ungrab(); }
466 this._display
.defaultCursor();
467 if (Log
.get_logging() !== 'debug') {
468 // Show noVNC logo on load and when disconnected, unless in
470 this._display
.clear();
479 * disconnected - permanent state
481 _updateConnectionState: function (state
) {
482 var oldstate
= this._rfb_connection_state
;
484 if (state
=== oldstate
) {
485 Log
.Debug("Already in state '" + state
+ "', ignoring");
489 // The 'disconnected' state is permanent for each RFB object
490 if (oldstate
=== 'disconnected') {
491 Log
.Error("Tried changing state of a disconnected RFB object");
495 // Ensure proper transitions before doing anything
498 if (oldstate
!== 'connecting') {
499 Log
.Error("Bad transition to connected state, " +
500 "previous connection state: " + oldstate
);
506 if (oldstate
!== 'disconnecting') {
507 Log
.Error("Bad transition to disconnected state, " +
508 "previous connection state: " + oldstate
);
514 if (oldstate
!== '') {
515 Log
.Error("Bad transition to connecting state, " +
516 "previous connection state: " + oldstate
);
521 case 'disconnecting':
522 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
523 Log
.Error("Bad transition to disconnecting state, " +
524 "previous connection state: " + oldstate
);
530 Log
.Error("Unknown connection state: " + state
);
534 // State change actions
536 this._rfb_connection_state
= state
;
537 this._onUpdateState(this, state
, oldstate
);
539 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
542 if (this._disconnTimer
&& state
!== 'disconnecting') {
543 Log
.Debug("Clearing disconnect timer");
544 clearTimeout(this._disconnTimer
);
545 this._disconnTimer
= null;
547 // make sure we don't get a double event
548 this._sock
.off('close');
553 // Call onDisconnected callback after onUpdateState since
554 // we don't know if the UI only displays the latest message
555 if (this._rfb_disconnect_reason
!== "") {
556 this._onDisconnected(this, this._rfb_disconnect_reason
);
558 // No reason means clean disconnect
559 this._onDisconnected(this);
567 case 'disconnecting':
570 this._disconnTimer
= setTimeout(function () {
571 this._rfb_disconnect_reason
= _("Disconnect timeout");
572 this._updateConnectionState('disconnected');
573 }.bind(this), this._disconnectTimeout
* 1000);
578 /* Print errors and disconnect
580 * The optional parameter 'details' is used for information that
581 * should be logged but not sent to the user interface.
583 _fail: function (msg
, details
) {
585 if (typeof details
!== 'undefined') {
586 fullmsg
= msg
+ " (" + details
+ ")";
588 switch (this._rfb_connection_state
) {
589 case 'disconnecting':
590 Log
.Error("Failed when disconnecting: " + fullmsg
);
593 Log
.Error("Failed while connected: " + fullmsg
);
596 Log
.Error("Failed when connecting: " + fullmsg
);
599 Log
.Error("RFB failure: " + fullmsg
);
602 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
604 // Transition to disconnected without waiting for socket to close
605 this._updateConnectionState('disconnecting');
606 this._updateConnectionState('disconnected');
612 * Send a notification to the UI. Valid levels are:
613 * 'normal'|'warn'|'error'
615 * NOTE: Options could be added in the future.
616 * NOTE: If this function is called multiple times, remember that the
617 * interface could be only showing the latest notification.
619 _notification: function(msg
, level
, options
) {
624 Log
.Debug("Notification[" + level
+ "]:" + msg
);
627 Log
.Error("Invalid notification level: " + level
);
632 this._onNotification(this, msg
, level
, options
);
634 this._onNotification(this, msg
, level
);
638 _handle_message: function () {
639 if (this._sock
.rQlen() === 0) {
640 Log
.Warn("handle_message called on an empty receive queue");
644 switch (this._rfb_connection_state
) {
646 Log
.Error("Got data while disconnected");
650 if (this._flushing
) {
653 if (!this._normal_msg()) {
656 if (this._sock
.rQlen() === 0) {
667 _handleKeyEvent: function (keysym
, code
, down
) {
668 this.sendKey(keysym
, code
, down
);
671 _handleMouseButton: function (x
, y
, down
, bmask
) {
673 this._mouse_buttonMask
|= bmask
;
675 this._mouse_buttonMask
&= ~bmask
;
678 if (this._viewportDrag
) {
679 if (down
&& !this._viewportDragging
) {
680 this._viewportDragging
= true;
681 this._viewportDragPos
= {'x': x
, 'y': y
};
683 // Skip sending mouse events
686 this._viewportDragging
= false;
688 // If the viewport didn't actually move, then treat as a mouse click event
689 // Send the button down event here, as the button up event is sent at the end of this function
690 if (!this._viewportHasMoved
&& !this._view_only
) {
691 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
693 this._viewportHasMoved
= false;
697 if (this._view_only
) { return; } // View only, skip mouse events
699 if (this._rfb_connection_state
!== 'connected') { return; }
700 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
703 _handleMouseMove: function (x
, y
) {
704 if (this._viewportDragging
) {
705 var deltaX
= this._viewportDragPos
.x
- x
;
706 var deltaY
= this._viewportDragPos
.y
- y
;
708 // The goal is to trigger on a certain physical width, the
709 // devicePixelRatio brings us a bit closer but is not optimal.
710 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
712 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
713 Math
.abs(deltaY
) > dragThreshold
)) {
714 this._viewportHasMoved
= true;
716 this._viewportDragPos
= {'x': x
, 'y': y
};
717 this._display
.viewportChangePos(deltaX
, deltaY
);
720 // Skip sending mouse events
724 if (this._view_only
) { return; } // View only, skip mouse events
726 if (this._rfb_connection_state
!== 'connected') { return; }
727 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
732 _negotiate_protocol_version: function () {
733 if (this._sock
.rQlen() < 12) {
734 return this._fail("Error while negotiating with server",
735 "Incomplete protocol version");
738 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
739 Log
.Info("Server ProtocolVersion: " + sversion
);
742 case "000.000": // UltraVNC repeater
746 case "003.006": // UltraVNC
747 case "003.889": // Apple Remote Desktop
748 this._rfb_version
= 3.3;
751 this._rfb_version
= 3.7;
754 case "004.000": // Intel AMT KVM
755 case "004.001": // RealVNC 4.6
756 case "005.000": // RealVNC 5.3
757 this._rfb_version
= 3.8;
760 return this._fail("Unsupported server",
761 "Invalid server version: " + sversion
);
765 var repeaterID
= this._repeaterID
;
766 while (repeaterID
.length
< 250) {
769 this._sock
.send_string(repeaterID
);
773 if (this._rfb_version
> this._rfb_max_version
) {
774 this._rfb_version
= this._rfb_max_version
;
777 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
778 ".00" + ((this._rfb_version
* 10) % 10);
779 this._sock
.send_string("RFB " + cversion
+ "\n");
780 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
782 this._rfb_init_state
= 'Security';
785 _negotiate_security: function () {
786 // Polyfill since IE and PhantomJS doesn't have
787 // TypedArray.includes()
788 function includes(item
, array
) {
789 for (var i
= 0; i
< array
.length
; i
++) {
790 if (array
[i
] === item
) {
797 if (this._rfb_version
>= 3.7) {
798 // Server sends supported list, client decides
799 var num_types
= this._sock
.rQshift8();
800 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
802 if (num_types
=== 0) {
803 var strlen
= this._sock
.rQshift32();
804 var reason
= this._sock
.rQshiftStr(strlen
);
805 return this._fail("Error while negotiating with server",
806 "Security failure: " + reason
);
809 var types
= this._sock
.rQshiftBytes(num_types
);
810 Log
.Debug("Server security types: " + types
);
812 // Look for each auth in preferred order
813 this._rfb_auth_scheme
= 0;
814 if (includes(1, types
)) {
815 this._rfb_auth_scheme
= 1; // None
816 } else if (includes(22, types
)) {
817 this._rfb_auth_scheme
= 22; // XVP
818 } else if (includes(16, types
)) {
819 this._rfb_auth_scheme
= 16; // Tight
820 } else if (includes(2, types
)) {
821 this._rfb_auth_scheme
= 2; // VNC Auth
823 return this._fail("Unsupported server",
824 "Unsupported security types: " + types
);
827 this._sock
.send([this._rfb_auth_scheme
]);
830 if (this._sock
.rQwait("security scheme", 4)) { return false; }
831 this._rfb_auth_scheme
= this._sock
.rQshift32();
834 this._rfb_init_state
= 'Authentication';
835 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
837 return this._init_msg(); // jump to authentication
841 _negotiate_xvp_auth: function () {
842 var xvp_sep
= this._xvp_password_sep
;
843 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
844 if (xvp_auth
.length
< 3) {
845 var msg
= 'XVP credentials required (user' + xvp_sep
+
846 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
847 this._onPasswordRequired(this, msg
);
851 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
852 String
.fromCharCode(xvp_auth
[1].length
) +
855 this._sock
.send_string(xvp_auth_str
);
856 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
857 this._rfb_auth_scheme
= 2;
858 return this._negotiate_authentication();
861 _negotiate_std_vnc_auth: function () {
862 if (this._rfb_password
.length
=== 0) {
863 this._onPasswordRequired(this);
867 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
869 // TODO(directxman12): make genDES not require an Array
870 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
871 var response
= RFB
.genDES(this._rfb_password
, challenge
);
872 this._sock
.send(response
);
873 this._rfb_init_state
= "SecurityResult";
877 _negotiate_tight_tunnels: function (numTunnels
) {
878 var clientSupportedTunnelTypes
= {
879 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
881 var serverSupportedTunnelTypes
= {};
882 // receive tunnel capabilities
883 for (var i
= 0; i
< numTunnels
; i
++) {
884 var cap_code
= this._sock
.rQshift32();
885 var cap_vendor
= this._sock
.rQshiftStr(4);
886 var cap_signature
= this._sock
.rQshiftStr(8);
887 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
890 // choose the notunnel type
891 if (serverSupportedTunnelTypes
[0]) {
892 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
893 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
894 return this._fail("Unsupported server",
895 "Client's tunnel type had the incorrect " +
896 "vendor or signature");
898 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
899 return false; // wait until we receive the sub auth count to continue
901 return this._fail("Unsupported server",
902 "Server wanted tunnels, but doesn't support " +
903 "the notunnel type");
907 _negotiate_tight_auth: function () {
908 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
909 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
910 var numTunnels
= this._sock
.rQshift32();
911 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
913 this._rfb_tightvnc
= true;
915 if (numTunnels
> 0) {
916 this._negotiate_tight_tunnels(numTunnels
);
917 return false; // wait until we receive the sub auth to continue
921 // second pass, do the sub-auth negotiation
922 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
923 var subAuthCount
= this._sock
.rQshift32();
924 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
925 this._rfb_init_state
= 'SecurityResult';
929 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
931 var clientSupportedTypes
= {
936 var serverSupportedTypes
= [];
938 for (var i
= 0; i
< subAuthCount
; i
++) {
939 var capNum
= this._sock
.rQshift32();
940 var capabilities
= this._sock
.rQshiftStr(12);
941 serverSupportedTypes
.push(capabilities
);
944 for (var authType
in clientSupportedTypes
) {
945 if (serverSupportedTypes
.indexOf(authType
) != -1) {
946 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
949 case 'STDVNOAUTH__': // no auth
950 this._rfb_init_state
= 'SecurityResult';
952 case 'STDVVNCAUTH_': // VNC auth
953 this._rfb_auth_scheme
= 2;
954 return this._init_msg();
956 return this._fail("Unsupported server",
957 "Unsupported tiny auth scheme: " +
963 return this._fail("Unsupported server",
964 "No supported sub-auth types!");
967 _negotiate_authentication: function () {
968 switch (this._rfb_auth_scheme
) {
969 case 0: // connection failed
970 if (this._sock
.rQwait("auth reason", 4)) { return false; }
971 var strlen
= this._sock
.rQshift32();
972 var reason
= this._sock
.rQshiftStr(strlen
);
973 return this._fail("Authentication failure", reason
);
976 if (this._rfb_version
>= 3.8) {
977 this._rfb_init_state
= 'SecurityResult';
980 this._rfb_init_state
= 'ClientInitialisation';
981 return this._init_msg();
984 return this._negotiate_xvp_auth();
986 case 2: // VNC authentication
987 return this._negotiate_std_vnc_auth();
989 case 16: // TightVNC Security Type
990 return this._negotiate_tight_auth();
993 return this._fail("Unsupported server",
994 "Unsupported auth scheme: " +
995 this._rfb_auth_scheme
);
999 _handle_security_result: function () {
1000 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
1001 switch (this._sock
.rQshift32()) {
1003 this._rfb_init_state
= 'ClientInitialisation';
1004 Log
.Debug('Authentication OK');
1005 return this._init_msg();
1007 if (this._rfb_version
>= 3.8) {
1008 var length
= this._sock
.rQshift32();
1009 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
1010 var reason
= this._sock
.rQshiftStr(length
);
1011 return this._fail("Authentication failure", reason
);
1013 return this._fail("Authentication failure");
1017 return this._fail("Too many authentication attempts");
1019 return this._fail("Unsupported server",
1020 "Unknown SecurityResult");
1024 _negotiate_server_init: function () {
1025 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1028 this._fb_width
= this._sock
.rQshift16();
1029 this._fb_height
= this._sock
.rQshift16();
1030 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1033 var bpp
= this._sock
.rQshift8();
1034 var depth
= this._sock
.rQshift8();
1035 var big_endian
= this._sock
.rQshift8();
1036 var true_color
= this._sock
.rQshift8();
1038 var red_max
= this._sock
.rQshift16();
1039 var green_max
= this._sock
.rQshift16();
1040 var blue_max
= this._sock
.rQshift16();
1041 var red_shift
= this._sock
.rQshift8();
1042 var green_shift
= this._sock
.rQshift8();
1043 var blue_shift
= this._sock
.rQshift8();
1044 this._sock
.rQskipBytes(3); // padding
1046 // NB(directxman12): we don't want to call any callbacks or print messages until
1047 // *after* we're past the point where we could backtrack
1049 /* Connection name/title */
1050 var name_length = this._sock.rQshift32();
1051 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1052 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1054 if (this._rfb_tightvnc) {
1055 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1056 // In TightVNC mode, ServerInit message is extended
1057 var numServerMessages = this._sock.rQshift16();
1058 var numClientMessages = this._sock.rQshift16();
1059 var numEncodings = this._sock.rQshift16();
1060 this._sock.rQskipBytes(2); // padding
1062 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1063 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1065 // we don't actually do anything with the capability information that TIGHT sends,
1066 // so we just skip the all of this.
1068 // TIGHT server message capabilities
1069 this._sock.rQskipBytes(16 * numServerMessages);
1071 // TIGHT client message capabilities
1072 this._sock.rQskipBytes(16 * numClientMessages);
1074 // TIGHT encoding capabilities
1075 this._sock.rQskipBytes(16 * numEncodings);
1078 // NB(directxman12): these are down here so that we don't run them multiple times
1080 Log.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1081 ", bpp: " + bpp + ", depth: " + depth +
1082 ", big_endian: " + big_endian +
1083 ", true_color: " + true_color +
1084 ", red_max: " + red_max +
1085 ", green_max: " + green_max +
1086 ", blue_max: " + blue_max +
1087 ", red_shift: " + red_shift +
1088 ", green_shift: " + green_shift +
1089 ", blue_shift: " + blue_shift);
1091 if (big_endian !== 0) {
1092 Log.Warn("Server native endian is not little endian");
1095 if (red_shift !== 16) {
1096 Log.Warn("Server native red-shift is not 16");
1099 if (blue_shift !== 0) {
1100 Log.Warn("Server native blue-shift is not 0");
1103 // we're past the point where we could backtrack, so it's safe to call this
1104 this._onDesktopName(this, this._fb_name);
1106 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1107 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1108 this._true_color = false;
1111 this._display.set_true_color(this._true_color);
1112 this._display.resize(this._fb_width, this._fb_height);
1113 this._onFBResize(this, this._fb_width, this._fb_height);
1115 if (!this._view_only) { this._keyboard.grab(); }
1116 if (!this._view_only) { this._mouse.grab(); }
1118 if (this._true_color) {
1126 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1127 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1128 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1130 this._timing.fbu_rt_start = (new Date()).getTime();
1131 this._timing.pixels = 0;
1133 this._updateConnectionState('connected');
1137 /* RFB protocol initialization states:
1142 * ClientInitialization - not triggered by server message
1143 * ServerInitialization
1145 _init_msg: function () {
1146 switch (this._rfb_init_state
) {
1147 case 'ProtocolVersion':
1148 return this._negotiate_protocol_version();
1151 return this._negotiate_security();
1153 case 'Authentication':
1154 return this._negotiate_authentication();
1156 case 'SecurityResult':
1157 return this._handle_security_result();
1159 case 'ClientInitialisation':
1160 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1161 this._rfb_init_state
= 'ServerInitialisation';
1164 case 'ServerInitialisation':
1165 return this._negotiate_server_init();
1168 return this._fail("Internal error", "Unknown init state: " +
1169 this._rfb_init_state
);
1173 _handle_set_colour_map_msg: function () {
1174 Log
.Debug("SetColorMapEntries");
1175 this._sock
.rQskip8(); // Padding
1177 var first_colour
= this._sock
.rQshift16();
1178 var num_colours
= this._sock
.rQshift16();
1179 if (this._sock
.rQwait('SetColorMapEntries', num_colours
* 6, 6)) { return false; }
1181 for (var c
= 0; c
< num_colours
; c
++) {
1182 var red
= parseInt(this._sock
.rQshift16() / 256, 10);
1183 var green
= parseInt(this._sock
.rQshift16() / 256, 10);
1184 var blue
= parseInt(this._sock
.rQshift16() / 256, 10);
1185 this._display
.set_colourMap([blue
, green
, red
], first_colour
+ c
);
1187 Log
.Debug("colourMap: " + this._display
.get_colourMap());
1188 Log
.Info("Registered " + num_colours
+ " colourMap entries");
1193 _handle_server_cut_text: function () {
1194 Log
.Debug("ServerCutText");
1196 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1197 this._sock
.rQskipBytes(3); // Padding
1198 var length
= this._sock
.rQshift32();
1199 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1201 var text
= this._sock
.rQshiftStr(length
);
1203 if (this._view_only
) { return true; }
1205 this._onClipboard(this, text
);
1210 _handle_server_fence_msg: function() {
1211 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1212 this._sock
.rQskipBytes(3); // Padding
1213 var flags
= this._sock
.rQshift32();
1214 var length
= this._sock
.rQshift8();
1216 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1219 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1223 var payload
= this._sock
.rQshiftStr(length
);
1225 this._supportsFence
= true;
1230 * (1<<0) - BlockBefore
1231 * (1<<1) - BlockAfter
1236 if (!(flags
& (1<<31))) {
1237 return this._fail("Internal error",
1238 "Unexpected fence response");
1241 // Filter out unsupported flags
1242 // FIXME: support syncNext
1243 flags
&= (1<<0) | (1<<1);
1245 // BlockBefore and BlockAfter are automatically handled by
1246 // the fact that we process each incoming message
1248 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1253 _handle_xvp_msg: function () {
1254 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1255 this._sock
.rQskip8(); // Padding
1256 var xvp_ver
= this._sock
.rQshift8();
1257 var xvp_msg
= this._sock
.rQshift8();
1261 Log
.Error("Operation Failed");
1262 this._notification("XVP Operation Failed", 'error');
1265 this._rfb_xvp_ver
= xvp_ver
;
1266 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1267 this._onXvpInit(this._rfb_xvp_ver
);
1270 this._fail("Unexpected server message",
1271 "Illegal server XVP message " + xvp_msg
);
1278 _normal_msg: function () {
1281 if (this._FBU
.rects
> 0) {
1284 msg_type
= this._sock
.rQshift8();
1288 case 0: // FramebufferUpdate
1289 var ret
= this._framebufferUpdate();
1290 if (ret
&& !this._enabledContinuousUpdates
) {
1291 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1292 this._fb_width
, this._fb_height
);
1296 case 1: // SetColorMapEntries
1297 return this._handle_set_colour_map_msg();
1304 case 3: // ServerCutText
1305 return this._handle_server_cut_text();
1307 case 150: // EndOfContinuousUpdates
1308 var first
= !(this._supportsContinuousUpdates
);
1309 this._supportsContinuousUpdates
= true;
1310 this._enabledContinuousUpdates
= false;
1312 this._enabledContinuousUpdates
= true;
1313 this._updateContinuousUpdates();
1314 Log
.Info("Enabling continuous updates.");
1316 // FIXME: We need to send a framebufferupdaterequest here
1317 // if we add support for turning off continuous updates
1321 case 248: // ServerFence
1322 return this._handle_server_fence_msg();
1325 return this._handle_xvp_msg();
1328 this._fail("Unexpected server message", "Type:" + msg_type
);
1329 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1334 _onFlush: function() {
1335 this._flushing
= false;
1336 // Resume processing
1337 if (this._sock
.rQlen() > 0) {
1338 this._handle_message();
1342 _framebufferUpdate: function () {
1346 if (this._FBU
.rects
=== 0) {
1347 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1348 this._sock
.rQskip8(); // Padding
1349 this._FBU
.rects
= this._sock
.rQshift16();
1350 this._FBU
.bytes
= 0;
1351 this._timing
.cur_fbu
= 0;
1352 if (this._timing
.fbu_rt_start
> 0) {
1353 now
= (new Date()).getTime();
1354 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1357 // Make sure the previous frame is fully rendered first
1358 // to avoid building up an excessive queue
1359 if (this._display
.pending()) {
1360 this._flushing
= true;
1361 this._display
.flush();
1366 while (this._FBU
.rects
> 0) {
1367 if (this._rfb_connection_state
!== 'connected') { return false; }
1369 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1370 if (this._FBU
.bytes
=== 0) {
1371 if (this._sock
.rQwait("rect header", 12)) { return false; }
1372 /* New FramebufferUpdate */
1374 var hdr
= this._sock
.rQshiftBytes(12);
1375 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1376 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1377 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1378 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1379 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1380 (hdr
[10] << 8) + hdr
[11], 10);
1382 this._onFBUReceive(this,
1383 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1384 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1385 'encoding': this._FBU
.encoding
,
1386 'encodingName': this._encNames
[this._FBU
.encoding
]});
1388 if (!this._encNames
[this._FBU
.encoding
]) {
1389 this._fail("Unexpected server message",
1390 "Unsupported encoding " +
1391 this._FBU
.encoding
);
1396 this._timing
.last_fbu
= (new Date()).getTime();
1398 ret
= this._encHandlers
[this._FBU
.encoding
]();
1400 now
= (new Date()).getTime();
1401 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1404 this._encStats
[this._FBU
.encoding
][0]++;
1405 this._encStats
[this._FBU
.encoding
][1]++;
1406 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1409 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1410 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1411 this._timing
.fbu_rt_start
> 0) {
1412 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1413 this._timing
.full_fbu_cnt
++;
1414 Log
.Info("Timing of full FBU, curr: " +
1415 this._timing
.cur_fbu
+ ", total: " +
1416 this._timing
.full_fbu_total
+ ", cnt: " +
1417 this._timing
.full_fbu_cnt
+ ", avg: " +
1418 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1421 if (this._timing
.fbu_rt_start
> 0) {
1422 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1423 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1424 this._timing
.fbu_rt_cnt
++;
1425 Log
.Info("full FBU round-trip, cur: " +
1426 fbu_rt_diff
+ ", total: " +
1427 this._timing
.fbu_rt_total
+ ", cnt: " +
1428 this._timing
.fbu_rt_cnt
+ ", avg: " +
1429 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1430 this._timing
.fbu_rt_start
= 0;
1434 if (!ret
) { return ret
; } // need more data
1437 this._display
.flip();
1439 this._onFBUComplete(this,
1440 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1441 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1442 'encoding': this._FBU
.encoding
,
1443 'encodingName': this._encNames
[this._FBU
.encoding
]});
1445 return true; // We finished this FBU
1448 _updateContinuousUpdates: function() {
1449 if (!this._enabledContinuousUpdates
) { return; }
1451 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1452 this._fb_width
, this._fb_height
);
1456 make_properties(RFB
, [
1457 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1458 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1459 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1460 ['true_color', 'rw', 'bool'], // Request true color pixel data
1461 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1462 ['shared', 'rw', 'bool'], // Request shared mode
1463 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1464 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1465 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1466 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1467 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1468 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1470 // Callback functions
1471 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1472 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1473 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1474 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1475 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1476 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1477 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1478 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1479 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1480 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1481 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1484 RFB
.prototype.set_local_cursor = function (cursor
) {
1485 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1486 this._local_cursor
= false;
1487 this._display
.disableLocalCursor(); //Only show server-side cursor
1489 if (this._display
.get_cursor_uri()) {
1490 this._local_cursor
= true;
1492 Log
.Warn("Browser does not support local cursor");
1493 this._display
.disableLocalCursor();
1497 // Need to send an updated list of encodings if we are connected
1498 if (this._rfb_connection_state
=== "connected") {
1499 RFB
.messages
.clientEncodings(this._sock
, this._encodings
, cursor
,
1504 RFB
.prototype.set_view_only = function (view_only
) {
1505 this._view_only
= view_only
;
1507 if (this._rfb_connection_state
=== "connecting" ||
1508 this._rfb_connection_state
=== "connected") {
1510 this._keyboard
.ungrab();
1511 this._mouse
.ungrab();
1513 this._keyboard
.grab();
1519 RFB
.prototype.get_display = function () { return this._display
; };
1520 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1521 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1525 keyEvent: function (sock
, keysym
, down
) {
1526 var buff
= sock
._sQ
;
1527 var offset
= sock
._sQlen
;
1529 buff
[offset
] = 4; // msg-type
1530 buff
[offset
+ 1] = down
;
1532 buff
[offset
+ 2] = 0;
1533 buff
[offset
+ 3] = 0;
1535 buff
[offset
+ 4] = (keysym
>> 24);
1536 buff
[offset
+ 5] = (keysym
>> 16);
1537 buff
[offset
+ 6] = (keysym
>> 8);
1538 buff
[offset
+ 7] = keysym
;
1544 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1545 function getRFBkeycode(xt_scancode
) {
1546 var upperByte
= (keycode
>> 8);
1547 var lowerByte
= (keycode
& 0x00ff);
1548 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1549 lowerByte
= lowerByte
| 0x80;
1555 var buff
= sock
._sQ
;
1556 var offset
= sock
._sQlen
;
1558 buff
[offset
] = 255; // msg-type
1559 buff
[offset
+ 1] = 0; // sub msg-type
1561 buff
[offset
+ 2] = (down
>> 8);
1562 buff
[offset
+ 3] = down
;
1564 buff
[offset
+ 4] = (keysym
>> 24);
1565 buff
[offset
+ 5] = (keysym
>> 16);
1566 buff
[offset
+ 6] = (keysym
>> 8);
1567 buff
[offset
+ 7] = keysym
;
1569 var RFBkeycode
= getRFBkeycode(keycode
);
1571 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1572 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1573 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1574 buff
[offset
+ 11] = RFBkeycode
;
1580 pointerEvent: function (sock
, x
, y
, mask
) {
1581 var buff
= sock
._sQ
;
1582 var offset
= sock
._sQlen
;
1584 buff
[offset
] = 5; // msg-type
1586 buff
[offset
+ 1] = mask
;
1588 buff
[offset
+ 2] = x
>> 8;
1589 buff
[offset
+ 3] = x
;
1591 buff
[offset
+ 4] = y
>> 8;
1592 buff
[offset
+ 5] = y
;
1598 // TODO(directxman12): make this unicode compatible?
1599 clientCutText: function (sock
, text
) {
1600 var buff
= sock
._sQ
;
1601 var offset
= sock
._sQlen
;
1603 buff
[offset
] = 6; // msg-type
1605 buff
[offset
+ 1] = 0; // padding
1606 buff
[offset
+ 2] = 0; // padding
1607 buff
[offset
+ 3] = 0; // padding
1609 var n
= text
.length
;
1611 buff
[offset
+ 4] = n
>> 24;
1612 buff
[offset
+ 5] = n
>> 16;
1613 buff
[offset
+ 6] = n
>> 8;
1614 buff
[offset
+ 7] = n
;
1616 for (var i
= 0; i
< n
; i
++) {
1617 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1620 sock
._sQlen
+= 8 + n
;
1624 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1625 var buff
= sock
._sQ
;
1626 var offset
= sock
._sQlen
;
1628 buff
[offset
] = 251; // msg-type
1629 buff
[offset
+ 1] = 0; // padding
1630 buff
[offset
+ 2] = width
>> 8; // width
1631 buff
[offset
+ 3] = width
;
1632 buff
[offset
+ 4] = height
>> 8; // height
1633 buff
[offset
+ 5] = height
;
1635 buff
[offset
+ 6] = 1; // number-of-screens
1636 buff
[offset
+ 7] = 0; // padding
1639 buff
[offset
+ 8] = id
>> 24; // id
1640 buff
[offset
+ 9] = id
>> 16;
1641 buff
[offset
+ 10] = id
>> 8;
1642 buff
[offset
+ 11] = id
;
1643 buff
[offset
+ 12] = 0; // x-position
1644 buff
[offset
+ 13] = 0;
1645 buff
[offset
+ 14] = 0; // y-position
1646 buff
[offset
+ 15] = 0;
1647 buff
[offset
+ 16] = width
>> 8; // width
1648 buff
[offset
+ 17] = width
;
1649 buff
[offset
+ 18] = height
>> 8; // height
1650 buff
[offset
+ 19] = height
;
1651 buff
[offset
+ 20] = flags
>> 24; // flags
1652 buff
[offset
+ 21] = flags
>> 16;
1653 buff
[offset
+ 22] = flags
>> 8;
1654 buff
[offset
+ 23] = flags
;
1660 clientFence: function (sock
, flags
, payload
) {
1661 var buff
= sock
._sQ
;
1662 var offset
= sock
._sQlen
;
1664 buff
[offset
] = 248; // msg-type
1666 buff
[offset
+ 1] = 0; // padding
1667 buff
[offset
+ 2] = 0; // padding
1668 buff
[offset
+ 3] = 0; // padding
1670 buff
[offset
+ 4] = flags
>> 24; // flags
1671 buff
[offset
+ 5] = flags
>> 16;
1672 buff
[offset
+ 6] = flags
>> 8;
1673 buff
[offset
+ 7] = flags
;
1675 var n
= payload
.length
;
1677 buff
[offset
+ 8] = n
; // length
1679 for (var i
= 0; i
< n
; i
++) {
1680 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1683 sock
._sQlen
+= 9 + n
;
1687 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1688 var buff
= sock
._sQ
;
1689 var offset
= sock
._sQlen
;
1691 buff
[offset
] = 150; // msg-type
1692 buff
[offset
+ 1] = enable
; // enable-flag
1694 buff
[offset
+ 2] = x
>> 8; // x
1695 buff
[offset
+ 3] = x
;
1696 buff
[offset
+ 4] = y
>> 8; // y
1697 buff
[offset
+ 5] = y
;
1698 buff
[offset
+ 6] = width
>> 8; // width
1699 buff
[offset
+ 7] = width
;
1700 buff
[offset
+ 8] = height
>> 8; // height
1701 buff
[offset
+ 9] = height
;
1707 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1708 var buff
= sock
._sQ
;
1709 var offset
= sock
._sQlen
;
1711 buff
[offset
] = 0; // msg-type
1713 buff
[offset
+ 1] = 0; // padding
1714 buff
[offset
+ 2] = 0; // padding
1715 buff
[offset
+ 3] = 0; // padding
1717 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1718 buff
[offset
+ 5] = depth
* 8; // depth
1719 buff
[offset
+ 6] = 0; // little-endian
1720 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1722 buff
[offset
+ 8] = 0; // red-max
1723 buff
[offset
+ 9] = 255; // red-max
1725 buff
[offset
+ 10] = 0; // green-max
1726 buff
[offset
+ 11] = 255; // green-max
1728 buff
[offset
+ 12] = 0; // blue-max
1729 buff
[offset
+ 13] = 255; // blue-max
1731 buff
[offset
+ 14] = 16; // red-shift
1732 buff
[offset
+ 15] = 8; // green-shift
1733 buff
[offset
+ 16] = 0; // blue-shift
1735 buff
[offset
+ 17] = 0; // padding
1736 buff
[offset
+ 18] = 0; // padding
1737 buff
[offset
+ 19] = 0; // padding
1743 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1744 var buff
= sock
._sQ
;
1745 var offset
= sock
._sQlen
;
1747 buff
[offset
] = 2; // msg-type
1748 buff
[offset
+ 1] = 0; // padding
1750 // offset + 2 and offset + 3 are encoding count
1752 var i
, j
= offset
+ 4, cnt
= 0;
1753 for (i
= 0; i
< encodings
.length
; i
++) {
1754 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1755 Log
.Debug("Skipping Cursor pseudo-encoding");
1756 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1757 // TODO: remove this when we have tight+non-true-color
1758 Log
.Warn("Skipping tight as it is only supported with true color");
1760 var enc
= encodings
[i
][1];
1761 buff
[j
] = enc
>> 24;
1762 buff
[j
+ 1] = enc
>> 16;
1763 buff
[j
+ 2] = enc
>> 8;
1771 buff
[offset
+ 2] = cnt
>> 8;
1772 buff
[offset
+ 3] = cnt
;
1774 sock
._sQlen
+= j
- offset
;
1778 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1779 var buff
= sock
._sQ
;
1780 var offset
= sock
._sQlen
;
1782 if (typeof(x
) === "undefined") { x
= 0; }
1783 if (typeof(y
) === "undefined") { y
= 0; }
1785 buff
[offset
] = 3; // msg-type
1786 buff
[offset
+ 1] = incremental
? 1 : 0;
1788 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1789 buff
[offset
+ 3] = x
& 0xFF;
1791 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1792 buff
[offset
+ 5] = y
& 0xFF;
1794 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1795 buff
[offset
+ 7] = w
& 0xFF;
1797 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1798 buff
[offset
+ 9] = h
& 0xFF;
1805 RFB
.genDES = function (password
, challenge
) {
1807 for (var i
= 0; i
< password
.length
; i
++) {
1808 passwd
.push(password
.charCodeAt(i
));
1810 return (new DES(passwd
)).encrypt(challenge
);
1813 RFB
.encodingHandlers
= {
1815 if (this._FBU
.lines
=== 0) {
1816 this._FBU
.lines
= this._FBU
.height
;
1819 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1820 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1821 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1822 var curr_height
= Math
.min(this._FBU
.lines
,
1823 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1824 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1825 curr_height
, this._sock
.get_rQ(),
1826 this._sock
.get_rQi());
1827 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1828 this._FBU
.lines
-= curr_height
;
1830 if (this._FBU
.lines
> 0) {
1831 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1834 this._FBU
.bytes
= 0;
1840 COPYRECT: function () {
1841 this._FBU
.bytes
= 4;
1842 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1843 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1844 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1848 this._FBU
.bytes
= 0;
1854 if (this._FBU
.subrects
=== 0) {
1855 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1856 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1857 this._FBU
.subrects
= this._sock
.rQshift32();
1858 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1859 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1862 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1863 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1864 var x
= this._sock
.rQshift16();
1865 var y
= this._sock
.rQshift16();
1866 var width
= this._sock
.rQshift16();
1867 var height
= this._sock
.rQshift16();
1868 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1869 this._FBU
.subrects
--;
1872 if (this._FBU
.subrects
> 0) {
1873 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1874 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1877 this._FBU
.bytes
= 0;
1883 HEXTILE: function () {
1884 var rQ
= this._sock
.get_rQ();
1885 var rQi
= this._sock
.get_rQi();
1887 if (this._FBU
.tiles
=== 0) {
1888 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1889 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1890 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1891 this._FBU
.tiles
= this._FBU
.total_tiles
;
1894 while (this._FBU
.tiles
> 0) {
1895 this._FBU
.bytes
= 1;
1896 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1897 var subencoding
= rQ
[rQi
]; // Peek
1898 if (subencoding
> 30) { // Raw
1899 this._fail("Unexpected server message",
1900 "Illegal hextile subencoding: " + subencoding
);
1905 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1906 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1907 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1908 var x
= this._FBU
.x
+ tile_x
* 16;
1909 var y
= this._FBU
.y
+ tile_y
* 16;
1910 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1911 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1913 // Figure out how much we are expecting
1914 if (subencoding
& 0x01) { // Raw
1915 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1917 if (subencoding
& 0x02) { // Background
1918 this._FBU
.bytes
+= this._fb_Bpp
;
1920 if (subencoding
& 0x04) { // Foreground
1921 this._FBU
.bytes
+= this._fb_Bpp
;
1923 if (subencoding
& 0x08) { // AnySubrects
1924 this._FBU
.bytes
++; // Since we aren't shifting it off
1925 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1926 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1927 if (subencoding
& 0x10) { // SubrectsColoured
1928 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1930 this._FBU
.bytes
+= subrects
* 2;
1935 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1937 // We know the encoding and have a whole tile
1938 this._FBU
.subencoding
= rQ
[rQi
];
1940 if (this._FBU
.subencoding
=== 0) {
1941 if (this._FBU
.lastsubencoding
& 0x01) {
1942 // Weird: ignore blanks are RAW
1943 Log
.Debug(" Ignoring blank after RAW");
1945 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1947 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1948 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1949 rQi
+= this._FBU
.bytes
- 1;
1951 if (this._FBU
.subencoding
& 0x02) { // Background
1952 if (this._fb_Bpp
== 1) {
1953 this._FBU
.background
= rQ
[rQi
];
1956 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1958 rQi
+= this._fb_Bpp
;
1960 if (this._FBU
.subencoding
& 0x04) { // Foreground
1961 if (this._fb_Bpp
== 1) {
1962 this._FBU
.foreground
= rQ
[rQi
];
1964 // this._fb_Bpp is 4
1965 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1967 rQi
+= this._fb_Bpp
;
1970 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1971 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1975 for (var s
= 0; s
< subrects
; s
++) {
1977 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1978 if (this._fb_Bpp
=== 1) {
1982 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1984 rQi
+= this._fb_Bpp
;
1986 color
= this._FBU
.foreground
;
1991 var sy
= (xy
& 0x0f);
1995 var sw
= (wh
>> 4) + 1;
1996 var sh
= (wh
& 0x0f) + 1;
1998 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2001 this._display
.finishTile();
2003 this._sock
.set_rQi(rQi
);
2004 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2005 this._FBU
.bytes
= 0;
2009 if (this._FBU
.tiles
=== 0) {
2016 getTightCLength: function (arr
) {
2017 var header
= 1, data
= 0;
2018 data
+= arr
[0] & 0x7f;
2019 if (arr
[0] & 0x80) {
2021 data
+= (arr
[1] & 0x7f) << 7;
2022 if (arr
[1] & 0x80) {
2024 data
+= arr
[2] << 14;
2027 return [header
, data
];
2030 display_tight: function (isTightPNG
) {
2031 if (this._fb_depth
=== 1) {
2032 this._fail("Internal error",
2033 "Tight protocol handler only implements " +
2037 this._FBU
.bytes
= 1; // compression-control byte
2038 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2040 var checksum = function (data
) {
2042 for (var i
= 0; i
< data
.length
; i
++) {
2044 if (sum
> 65536) sum
-= 65536;
2049 var resetStreams
= 0;
2051 var decompress = function (data
, expected
) {
2052 for (var i
= 0; i
< 4; i
++) {
2053 if ((resetStreams
>> i
) & 1) {
2054 this._FBU
.zlibs
[i
].reset();
2055 Log
.Info("Reset zlib stream " + i
);
2059 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2060 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2061 /*if (uncompressed.status !== 0) {
2062 Log.Error("Invalid data in zlib stream");
2065 //return uncompressed.data;
2066 return uncompressed
;
2069 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2070 // Convert indexed (palette based) image data to RGB
2071 // TODO: reduce number of calculations inside loop
2072 var dest
= this._destBuff
;
2073 var w
= Math
.floor((width
+ 7) / 8);
2074 var w1
= Math
.floor(width
/ 8);
2076 /*for (var y = 0; y < height; y++) {
2078 var yoffset = y * width;
2079 var ybitoffset = y * w;
2080 var xoffset, targetbyte;
2081 for (x = 0; x < w1; x++) {
2082 xoffset = yoffset + x * 8;
2083 targetbyte = data[ybitoffset + x];
2084 for (b = 7; b >= 0; b--) {
2085 dp = (xoffset + 7 - b) * 3;
2086 sp = (targetbyte >> b & 1) * 3;
2087 dest[dp] = palette[sp];
2088 dest[dp + 1] = palette[sp + 1];
2089 dest[dp + 2] = palette[sp + 2];
2093 xoffset = yoffset + x * 8;
2094 targetbyte = data[ybitoffset + x];
2095 for (b = 7; b >= 8 - width % 8; 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 for (var y
= 0; y
< height
; y
++) {
2106 for (x
= 0; x
< w1
; x
++) {
2107 for (b
= 7; b
>= 0; b
--) {
2108 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2109 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2110 dest
[dp
] = palette
[sp
];
2111 dest
[dp
+ 1] = palette
[sp
+ 1];
2112 dest
[dp
+ 2] = palette
[sp
+ 2];
2117 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2118 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2119 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2120 dest
[dp
] = palette
[sp
];
2121 dest
[dp
+ 1] = palette
[sp
+ 1];
2122 dest
[dp
+ 2] = palette
[sp
+ 2];
2130 var indexedToRGBX = function (data
, palette
, width
, height
) {
2131 // Convert indexed (palette based) image data to RGB
2132 var dest
= this._destBuff
;
2133 var total
= width
* height
* 4;
2134 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2135 var sp
= data
[j
] * 3;
2136 dest
[i
] = palette
[sp
];
2137 dest
[i
+ 1] = palette
[sp
+ 1];
2138 dest
[i
+ 2] = palette
[sp
+ 2];
2145 var rQi
= this._sock
.get_rQi();
2146 var rQ
= this._sock
.rQwhole();
2148 var cl_header
, cl_data
;
2150 var handlePalette = function () {
2151 var numColors
= rQ
[rQi
+ 2] + 1;
2152 var paletteSize
= numColors
* this._fb_depth
;
2153 this._FBU
.bytes
+= paletteSize
;
2154 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2156 var bpp
= (numColors
<= 2) ? 1 : 8;
2157 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2159 if (rowSize
* this._FBU
.height
< 12) {
2162 cl_data
= rowSize
* this._FBU
.height
;
2163 //clength = [0, rowSize * this._FBU.height];
2165 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2166 var cl_offset
= rQi
+ 3 + paletteSize
;
2169 cl_data
+= rQ
[cl_offset
] & 0x7f;
2170 if (rQ
[cl_offset
] & 0x80) {
2172 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2173 if (rQ
[cl_offset
+ 1] & 0x80) {
2175 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2178 // end inline getTightCLength
2181 this._FBU
.bytes
+= cl_header
+ cl_data
;
2182 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2184 // Shift ctl, filter id, num colors, palette entries, and clength off
2185 this._sock
.rQskipBytes(3);
2186 //var palette = this._sock.rQshiftBytes(paletteSize);
2187 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2188 this._sock
.rQskipBytes(cl_header
);
2191 data
= this._sock
.rQshiftBytes(cl_data
);
2193 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2196 // Convert indexed (palette based) image data to RGB
2198 if (numColors
== 2) {
2199 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2200 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2202 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2203 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2210 var handleCopy = function () {
2212 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2213 if (uncompressedSize
< 12) {
2216 cl_data
= uncompressedSize
;
2218 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2219 var cl_offset
= rQi
+ 1;
2222 cl_data
+= rQ
[cl_offset
] & 0x7f;
2223 if (rQ
[cl_offset
] & 0x80) {
2225 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2226 if (rQ
[cl_offset
+ 1] & 0x80) {
2228 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2231 // end inline getTightCLength
2233 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2234 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2236 // Shift ctl, clength off
2237 this._sock
.rQshiftBytes(1 + cl_header
);
2240 data
= this._sock
.rQshiftBytes(cl_data
);
2242 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2245 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2250 var ctl
= this._sock
.rQpeek8();
2252 // Keep tight reset bits
2253 resetStreams
= ctl
& 0xF;
2255 // Figure out filter
2257 streamId
= ctl
& 0x3;
2259 if (ctl
=== 0x08) cmode
= "fill";
2260 else if (ctl
=== 0x09) cmode
= "jpeg";
2261 else if (ctl
=== 0x0A) cmode
= "png";
2262 else if (ctl
& 0x04) cmode
= "filter";
2263 else if (ctl
< 0x04) cmode
= "copy";
2264 else return this._fail("Unexpected server message",
2265 "Illegal tight compression received, " +
2268 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2269 return this._fail("Unexpected server message",
2270 "filter/copy received in tightPNG mode");
2274 // fill use fb_depth because TPIXELs drop the padding byte
2275 case "fill": // TPIXEL
2276 this._FBU
.bytes
+= this._fb_depth
;
2278 case "jpeg": // max clength
2279 this._FBU
.bytes
+= 3;
2281 case "png": // max clength
2282 this._FBU
.bytes
+= 3;
2284 case "filter": // filter id + num colors if palette
2285 this._FBU
.bytes
+= 2;
2291 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2293 // Determine FBU.bytes
2297 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);
2298 this._sock
.rQskipBytes(4);
2302 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2303 var cl_offset
= rQi
+ 1;
2306 cl_data
+= rQ
[cl_offset
] & 0x7f;
2307 if (rQ
[cl_offset
] & 0x80) {
2309 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2310 if (rQ
[cl_offset
+ 1] & 0x80) {
2312 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2315 // end inline getTightCLength
2316 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2317 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2319 // We have everything, render it
2320 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2321 data
= this._sock
.rQshiftBytes(cl_data
);
2322 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2325 var filterId
= rQ
[rQi
+ 1];
2326 if (filterId
=== 1) {
2327 if (!handlePalette()) { return false; }
2329 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2330 // Filter 2, Gradient is valid but not use if jpeg is enabled
2331 this._fail("Unexpected server message",
2332 "Unsupported tight subencoding received, " +
2333 "filter: " + filterId
);
2337 if (!handleCopy()) { return false; }
2342 this._FBU
.bytes
= 0;
2348 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2349 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2351 last_rect: function () {
2352 this._FBU
.rects
= 0;
2356 handle_FB_resize: function () {
2357 this._fb_width
= this._FBU
.width
;
2358 this._fb_height
= this._FBU
.height
;
2359 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2360 this._display
.resize(this._fb_width
, this._fb_height
);
2361 this._onFBResize(this, this._fb_width
, this._fb_height
);
2362 this._timing
.fbu_rt_start
= (new Date()).getTime();
2363 this._updateContinuousUpdates();
2365 this._FBU
.bytes
= 0;
2366 this._FBU
.rects
-= 1;
2370 ExtendedDesktopSize: function () {
2371 this._FBU
.bytes
= 1;
2372 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2374 this._supportsSetDesktopSize
= true;
2375 var number_of_screens
= this._sock
.rQpeek8();
2377 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2378 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2380 this._sock
.rQskipBytes(1); // number-of-screens
2381 this._sock
.rQskipBytes(3); // padding
2383 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2384 // Save the id and flags of the first screen
2386 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2387 this._sock
.rQskipBytes(2); // x-position
2388 this._sock
.rQskipBytes(2); // y-position
2389 this._sock
.rQskipBytes(2); // width
2390 this._sock
.rQskipBytes(2); // height
2391 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2393 this._sock
.rQskipBytes(16);
2398 * The x-position indicates the reason for the change:
2400 * 0 - server resized on its own
2401 * 1 - this client requested the resize
2402 * 2 - another client requested the resize
2405 // We need to handle errors when we requested the resize.
2406 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2408 // The y-position indicates the status code from the server
2409 switch (this._FBU
.y
) {
2411 msg
= "Resize is administratively prohibited";
2414 msg
= "Out of resources";
2417 msg
= "Invalid screen layout";
2420 msg
= "Unknown reason";
2423 this._notification("Server did not accept the resize request: "
2428 this._encHandlers
.handle_FB_resize();
2432 DesktopSize: function () {
2433 this._encHandlers
.handle_FB_resize();
2437 Cursor: function () {
2438 Log
.Debug(">> set_cursor");
2439 var x
= this._FBU
.x
; // hotspot-x
2440 var y
= this._FBU
.y
; // hotspot-y
2441 var w
= this._FBU
.width
;
2442 var h
= this._FBU
.height
;
2444 var pixelslength
= w
* h
* this._fb_Bpp
;
2445 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2447 this._FBU
.bytes
= pixelslength
+ masklength
;
2448 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2450 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2451 this._sock
.rQshiftBytes(masklength
),
2454 this._FBU
.bytes
= 0;
2457 Log
.Debug("<< set_cursor");
2461 QEMUExtendedKeyEvent: function () {
2464 var keyboardEvent
= document
.createEvent("keyboardEvent");
2465 if (keyboardEvent
.code
!== undefined) {
2466 this._qemuExtKeyEventSupported
= true;
2470 JPEG_quality_lo: function () {
2471 Log
.Error("Server sent jpeg_quality pseudo-encoding");
2474 compress_lo: function () {
2475 Log
.Error("Server sent compress level pseudo-encoding");