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', -247 ],
67 ['DesktopSize', -223 ],
70 ['QEMUExtendedKeyEvent', -258 ],
71 ['ExtendedDesktopSize', -308 ],
74 ['ContinuousUpdates', -313 ]
77 this._encHandlers
= {};
81 this._sock
= null; // Websock object
82 this._display
= null; // Display object
83 this._flushing
= false; // Display flushing state
84 this._keyboard
= null; // Keyboard input handler object
85 this._mouse
= null; // Mouse input handler object
86 this._disconnTimer
= null; // disconnection timer
88 this._supportsFence
= false;
90 this._supportsContinuousUpdates
= false;
91 this._enabledContinuousUpdates
= false;
93 // Frame buffer update state
107 zlib
: [] // TIGHT zlib streams
116 this._destBuff
= null;
117 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
119 this._rre_chunk_sz
= 100;
134 this._supportsSetDesktopSize
= false;
136 this._screen_flags
= 0;
139 this._mouse_buttonMask
= 0;
140 this._mouse_arr
= [];
141 this._viewportDragging
= false;
142 this._viewportDragPos
= {};
143 this._viewportHasMoved
= false;
145 // QEMU Extended Key Event support - default to false
146 this._qemuExtKeyEventSupported
= false;
148 // set the default value on user-facing properties
149 set_defaults(this, defaults
, {
150 'target': 'null', // VNC display rendering Canvas object
151 'focusContainer': document
, // DOM element that captures keyboard input
152 'encrypt': false, // Use TLS/SSL/wss encryption
153 'true_color': true, // Request true color pixel data
154 'local_cursor': false, // Request locally rendered cursor
155 'shared': true, // Request shared mode
156 'view_only': false, // Disable client mouse/keyboard
157 'xvp_password_sep': '@', // Separator for XVP password fields
158 'disconnectTimeout': 3, // Time (s) to wait for disconnection
159 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
160 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
161 'viewportDrag': false, // Move the viewport on mouse drags
163 // Callback functions
164 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
165 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
166 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
167 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
168 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
169 'onBell': function () { }, // onBell(rfb): RFB Bell message received
170 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
171 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
172 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
173 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
174 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
178 Log
.Debug(">> RFB.constructor");
180 // populate encHandlers with bound versions
181 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
182 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
185 // Create lookup tables based on encoding number
186 for (var i
= 0; i
< this._encodings
.length
; i
++) {
187 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
188 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
189 this._encStats
[this._encodings
[i
][1]] = [0, 0];
192 // NB: nothing that needs explicit teardown should be done
193 // before this point, since this can throw an exception
195 this._display
= new Display({target
: this._target
,
196 onFlush
: this._onFlush
.bind(this)});
198 Log
.Error("Display exception: " + exc
);
202 this._keyboard
= new Keyboard({target
: this._focusContainer
,
203 onKeyPress
: this._handleKeyPress
.bind(this)});
205 this._mouse
= new Mouse({target
: this._target
,
206 onMouseButton
: this._handleMouseButton
.bind(this),
207 onMouseMove
: this._handleMouseMove
.bind(this),
208 notify
: this._keyboard
.sync
.bind(this._keyboard
)});
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 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 1);
302 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 1);
303 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 1);
304 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 0);
305 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 0);
306 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 0);
310 xvpOp: function (ver
, op
) {
311 if (this._rfb_xvp_ver
< ver
) { return false; }
312 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
313 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
317 xvpShutdown: function () {
318 return this.xvpOp(1, 2);
321 xvpReboot: function () {
322 return this.xvpOp(1, 3);
325 xvpReset: function () {
326 return this.xvpOp(1, 4);
329 // Send a key press. If 'down' is not specified then send a down key
330 // followed by an up key.
331 sendKey: function (keysym
, down
) {
332 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
333 if (typeof down
!== 'undefined') {
334 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
335 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
337 Log
.Info("Sending keysym (down + up): " + keysym
);
338 RFB
.messages
.keyEvent(this._sock
, keysym
, 1);
339 RFB
.messages
.keyEvent(this._sock
, keysym
, 0);
344 clipboardPasteFrom: function (text
) {
345 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
346 RFB
.messages
.clientCutText(this._sock
, text
);
349 // Requests a change of remote desktop size. This message is an extension
350 // and may only be sent if we have received an ExtendedDesktopSize message
351 requestDesktopSize: function (width
, height
) {
352 if (this._rfb_connection_state
!== 'connected' ||
357 if (this._supportsSetDesktopSize
) {
358 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
359 this._screen_id
, this._screen_flags
);
370 _connect: function () {
371 Log
.Debug(">> RFB.connect");
375 if (typeof UsingSocketIO
!== 'undefined') {
378 uri
= this._encrypt
? 'wss' : 'ws';
381 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
382 Log
.Info("connecting to " + uri
);
385 // WebSocket.onopen transitions to the RFB init states
386 this._sock
.open(uri
, this._wsProtocols
);
388 if (e
.name
=== 'SyntaxError') {
389 this._fail("Invalid host or port value given", e
);
391 this._fail("Error while connecting", e
);
395 Log
.Debug("<< RFB.connect");
398 _disconnect: function () {
399 Log
.Debug(">> RFB.disconnect");
403 Log
.Debug("<< RFB.disconnect");
406 _init_vars: function () {
409 this._FBU
.subrects
= 0; // RRE and HEXTILE
410 this._FBU
.lines
= 0; // RAW
411 this._FBU
.tiles
= 0; // HEXTILE
412 this._FBU
.zlibs
= []; // TIGHT zlib encoders
413 this._mouse_buttonMask
= 0;
414 this._mouse_arr
= [];
415 this._rfb_tightvnc
= false;
417 // Clear the per connection encoding stats
419 for (i
= 0; i
< this._encodings
.length
; i
++) {
420 this._encStats
[this._encodings
[i
][1]][0] = 0;
423 for (i
= 0; i
< 4; i
++) {
424 this._FBU
.zlibs
[i
] = new Inflator();
428 _print_stats: function () {
429 Log
.Info("Encoding stats for this connection:");
431 for (i
= 0; i
< this._encodings
.length
; i
++) {
432 s
= this._encStats
[this._encodings
[i
][1]];
433 if (s
[0] + s
[1] > 0) {
434 Log
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
438 Log
.Info("Encoding stats since page load:");
439 for (i
= 0; i
< this._encodings
.length
; i
++) {
440 s
= this._encStats
[this._encodings
[i
][1]];
441 Log
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
445 _cleanup: function () {
446 if (!this._view_only
) { this._keyboard
.ungrab(); }
447 if (!this._view_only
) { this._mouse
.ungrab(); }
448 this._display
.defaultCursor();
449 if (Log
.get_logging() !== 'debug') {
450 // Show noVNC logo on load and when disconnected, unless in
452 this._display
.clear();
461 * disconnected - permanent state
463 _updateConnectionState: function (state
) {
464 var oldstate
= this._rfb_connection_state
;
466 if (state
=== oldstate
) {
467 Log
.Debug("Already in state '" + state
+ "', ignoring");
471 // The 'disconnected' state is permanent for each RFB object
472 if (oldstate
=== 'disconnected') {
473 Log
.Error("Tried changing state of a disconnected RFB object");
477 // Ensure proper transitions before doing anything
480 if (oldstate
!== 'connecting') {
481 Log
.Error("Bad transition to connected state, " +
482 "previous connection state: " + oldstate
);
488 if (oldstate
!== 'disconnecting') {
489 Log
.Error("Bad transition to disconnected state, " +
490 "previous connection state: " + oldstate
);
496 if (oldstate
!== '') {
497 Log
.Error("Bad transition to connecting state, " +
498 "previous connection state: " + oldstate
);
503 case 'disconnecting':
504 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
505 Log
.Error("Bad transition to disconnecting state, " +
506 "previous connection state: " + oldstate
);
512 Log
.Error("Unknown connection state: " + state
);
516 // State change actions
518 this._rfb_connection_state
= state
;
519 this._onUpdateState(this, state
, oldstate
);
521 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
524 if (this._disconnTimer
&& state
!== 'disconnecting') {
525 Log
.Debug("Clearing disconnect timer");
526 clearTimeout(this._disconnTimer
);
527 this._disconnTimer
= null;
529 // make sure we don't get a double event
530 this._sock
.off('close');
535 // Call onDisconnected callback after onUpdateState since
536 // we don't know if the UI only displays the latest message
537 if (this._rfb_disconnect_reason
!== "") {
538 this._onDisconnected(this, this._rfb_disconnect_reason
);
540 // No reason means clean disconnect
541 this._onDisconnected(this);
549 case 'disconnecting':
552 this._disconnTimer
= setTimeout(function () {
553 this._rfb_disconnect_reason
= _("Disconnect timeout");
554 this._updateConnectionState('disconnected');
555 }.bind(this), this._disconnectTimeout
* 1000);
560 /* Print errors and disconnect
562 * The optional parameter 'details' is used for information that
563 * should be logged but not sent to the user interface.
565 _fail: function (msg
, details
) {
567 if (typeof details
!== 'undefined') {
568 fullmsg
= msg
+ " (" + details
+ ")";
570 switch (this._rfb_connection_state
) {
571 case 'disconnecting':
572 Log
.Error("Failed when disconnecting: " + fullmsg
);
575 Log
.Error("Failed while connected: " + fullmsg
);
578 Log
.Error("Failed when connecting: " + fullmsg
);
581 Log
.Error("RFB failure: " + fullmsg
);
584 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
586 // Transition to disconnected without waiting for socket to close
587 this._updateConnectionState('disconnecting');
588 this._updateConnectionState('disconnected');
594 * Send a notification to the UI. Valid levels are:
595 * 'normal'|'warn'|'error'
597 * NOTE: Options could be added in the future.
598 * NOTE: If this function is called multiple times, remember that the
599 * interface could be only showing the latest notification.
601 _notification: function(msg
, level
, options
) {
606 Log
.Debug("Notification[" + level
+ "]:" + msg
);
609 Log
.Error("Invalid notification level: " + level
);
614 this._onNotification(this, msg
, level
, options
);
616 this._onNotification(this, msg
, level
);
620 _handle_message: function () {
621 if (this._sock
.rQlen() === 0) {
622 Log
.Warn("handle_message called on an empty receive queue");
626 switch (this._rfb_connection_state
) {
628 Log
.Error("Got data while disconnected");
632 if (this._flushing
) {
635 if (!this._normal_msg()) {
638 if (this._sock
.rQlen() === 0) {
649 _handleKeyPress: function (keyevent
) {
650 if (this._view_only
) { return; } // View only, skip keyboard, events
652 var down
= (keyevent
.type
== 'keydown');
653 if (this._qemuExtKeyEventSupported
) {
654 var scancode
= XtScancode
[keyevent
.code
];
656 var keysym
= keyevent
.keysym
;
657 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
659 Log
.Error('Unable to find a xt scancode for code = ' + keyevent
.code
);
662 keysym
= keyevent
.keysym
.keysym
;
663 RFB
.messages
.keyEvent(this._sock
, keysym
, down
);
667 _handleMouseButton: function (x
, y
, down
, bmask
) {
669 this._mouse_buttonMask
|= bmask
;
671 this._mouse_buttonMask
^= bmask
;
674 if (this._viewportDrag
) {
675 if (down
&& !this._viewportDragging
) {
676 this._viewportDragging
= true;
677 this._viewportDragPos
= {'x': x
, 'y': y
};
679 // Skip sending mouse events
682 this._viewportDragging
= false;
684 // If the viewport didn't actually move, then treat as a mouse click event
685 // Send the button down event here, as the button up event is sent at the end of this function
686 if (!this._viewportHasMoved
&& !this._view_only
) {
687 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
689 this._viewportHasMoved
= false;
693 if (this._view_only
) { return; } // View only, skip mouse events
695 if (this._rfb_connection_state
!== 'connected') { return; }
696 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
699 _handleMouseMove: function (x
, y
) {
700 if (this._viewportDragging
) {
701 var deltaX
= this._viewportDragPos
.x
- x
;
702 var deltaY
= this._viewportDragPos
.y
- y
;
704 // The goal is to trigger on a certain physical width, the
705 // devicePixelRatio brings us a bit closer but is not optimal.
706 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
708 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
709 Math
.abs(deltaY
) > dragThreshold
)) {
710 this._viewportHasMoved
= true;
712 this._viewportDragPos
= {'x': x
, 'y': y
};
713 this._display
.viewportChangePos(deltaX
, deltaY
);
716 // Skip sending mouse events
720 if (this._view_only
) { return; } // View only, skip mouse events
722 if (this._rfb_connection_state
!== 'connected') { return; }
723 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
728 _negotiate_protocol_version: function () {
729 if (this._sock
.rQlen() < 12) {
730 return this._fail("Error while negotiating with server",
731 "Incomplete protocol version");
734 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
735 Log
.Info("Server ProtocolVersion: " + sversion
);
738 case "000.000": // UltraVNC repeater
742 case "003.006": // UltraVNC
743 case "003.889": // Apple Remote Desktop
744 this._rfb_version
= 3.3;
747 this._rfb_version
= 3.7;
750 case "004.000": // Intel AMT KVM
751 case "004.001": // RealVNC 4.6
752 case "005.000": // RealVNC 5.3
753 this._rfb_version
= 3.8;
756 return this._fail("Unsupported server",
757 "Invalid server version: " + sversion
);
761 var repeaterID
= this._repeaterID
;
762 while (repeaterID
.length
< 250) {
765 this._sock
.send_string(repeaterID
);
769 if (this._rfb_version
> this._rfb_max_version
) {
770 this._rfb_version
= this._rfb_max_version
;
773 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
774 ".00" + ((this._rfb_version
* 10) % 10);
775 this._sock
.send_string("RFB " + cversion
+ "\n");
776 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
778 this._rfb_init_state
= 'Security';
781 _negotiate_security: function () {
782 // Polyfill since IE and PhantomJS doesn't have
783 // TypedArray.includes()
784 function includes(item
, array
) {
785 for (var i
= 0; i
< array
.length
; i
++) {
786 if (array
[i
] === item
) {
793 if (this._rfb_version
>= 3.7) {
794 // Server sends supported list, client decides
795 var num_types
= this._sock
.rQshift8();
796 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
798 if (num_types
=== 0) {
799 var strlen
= this._sock
.rQshift32();
800 var reason
= this._sock
.rQshiftStr(strlen
);
801 return this._fail("Error while negotiating with server",
802 "Security failure: " + reason
);
805 var types
= this._sock
.rQshiftBytes(num_types
);
806 Log
.Debug("Server security types: " + types
);
808 // Look for each auth in preferred order
809 this._rfb_auth_scheme
= 0;
810 if (includes(1, types
)) {
811 this._rfb_auth_scheme
= 1; // None
812 } else if (includes(22, types
)) {
813 this._rfb_auth_scheme
= 22; // XVP
814 } else if (includes(16, types
)) {
815 this._rfb_auth_scheme
= 16; // Tight
816 } else if (includes(2, types
)) {
817 this._rfb_auth_scheme
= 2; // VNC Auth
819 return this._fail("Unsupported server",
820 "Unsupported security types: " + types
);
823 this._sock
.send([this._rfb_auth_scheme
]);
826 if (this._sock
.rQwait("security scheme", 4)) { return false; }
827 this._rfb_auth_scheme
= this._sock
.rQshift32();
830 this._rfb_init_state
= 'Authentication';
831 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
833 return this._init_msg(); // jump to authentication
837 _negotiate_xvp_auth: function () {
838 var xvp_sep
= this._xvp_password_sep
;
839 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
840 if (xvp_auth
.length
< 3) {
841 var msg
= 'XVP credentials required (user' + xvp_sep
+
842 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
843 this._onPasswordRequired(this, msg
);
847 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
848 String
.fromCharCode(xvp_auth
[1].length
) +
851 this._sock
.send_string(xvp_auth_str
);
852 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
853 this._rfb_auth_scheme
= 2;
854 return this._negotiate_authentication();
857 _negotiate_std_vnc_auth: function () {
858 if (this._rfb_password
.length
=== 0) {
859 this._onPasswordRequired(this);
863 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
865 // TODO(directxman12): make genDES not require an Array
866 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
867 var response
= RFB
.genDES(this._rfb_password
, challenge
);
868 this._sock
.send(response
);
869 this._rfb_init_state
= "SecurityResult";
873 _negotiate_tight_tunnels: function (numTunnels
) {
874 var clientSupportedTunnelTypes
= {
875 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
877 var serverSupportedTunnelTypes
= {};
878 // receive tunnel capabilities
879 for (var i
= 0; i
< numTunnels
; i
++) {
880 var cap_code
= this._sock
.rQshift32();
881 var cap_vendor
= this._sock
.rQshiftStr(4);
882 var cap_signature
= this._sock
.rQshiftStr(8);
883 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
886 // choose the notunnel type
887 if (serverSupportedTunnelTypes
[0]) {
888 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
889 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
890 return this._fail("Unsupported server",
891 "Client's tunnel type had the incorrect " +
892 "vendor or signature");
894 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
895 return false; // wait until we receive the sub auth count to continue
897 return this._fail("Unsupported server",
898 "Server wanted tunnels, but doesn't support " +
899 "the notunnel type");
903 _negotiate_tight_auth: function () {
904 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
905 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
906 var numTunnels
= this._sock
.rQshift32();
907 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
909 this._rfb_tightvnc
= true;
911 if (numTunnels
> 0) {
912 this._negotiate_tight_tunnels(numTunnels
);
913 return false; // wait until we receive the sub auth to continue
917 // second pass, do the sub-auth negotiation
918 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
919 var subAuthCount
= this._sock
.rQshift32();
920 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
921 this._rfb_init_state
= 'SecurityResult';
925 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
927 var clientSupportedTypes
= {
932 var serverSupportedTypes
= [];
934 for (var i
= 0; i
< subAuthCount
; i
++) {
935 var capNum
= this._sock
.rQshift32();
936 var capabilities
= this._sock
.rQshiftStr(12);
937 serverSupportedTypes
.push(capabilities
);
940 for (var authType
in clientSupportedTypes
) {
941 if (serverSupportedTypes
.indexOf(authType
) != -1) {
942 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
945 case 'STDVNOAUTH__': // no auth
946 this._rfb_init_state
= 'SecurityResult';
948 case 'STDVVNCAUTH_': // VNC auth
949 this._rfb_auth_scheme
= 2;
950 return this._init_msg();
952 return this._fail("Unsupported server",
953 "Unsupported tiny auth scheme: " +
959 return this._fail("Unsupported server",
960 "No supported sub-auth types!");
963 _negotiate_authentication: function () {
964 switch (this._rfb_auth_scheme
) {
965 case 0: // connection failed
966 if (this._sock
.rQwait("auth reason", 4)) { return false; }
967 var strlen
= this._sock
.rQshift32();
968 var reason
= this._sock
.rQshiftStr(strlen
);
969 return this._fail("Authentication failure", reason
);
972 if (this._rfb_version
>= 3.8) {
973 this._rfb_init_state
= 'SecurityResult';
976 this._rfb_init_state
= 'ClientInitialisation';
977 return this._init_msg();
980 return this._negotiate_xvp_auth();
982 case 2: // VNC authentication
983 return this._negotiate_std_vnc_auth();
985 case 16: // TightVNC Security Type
986 return this._negotiate_tight_auth();
989 return this._fail("Unsupported server",
990 "Unsupported auth scheme: " +
991 this._rfb_auth_scheme
);
995 _handle_security_result: function () {
996 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
997 switch (this._sock
.rQshift32()) {
999 this._rfb_init_state
= 'ClientInitialisation';
1000 Log
.Debug('Authentication OK');
1001 return this._init_msg();
1003 if (this._rfb_version
>= 3.8) {
1004 var length
= this._sock
.rQshift32();
1005 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
1006 var reason
= this._sock
.rQshiftStr(length
);
1007 return this._fail("Authentication failure", reason
);
1009 return this._fail("Authentication failure");
1013 return this._fail("Too many authentication attempts");
1015 return this._fail("Unsupported server",
1016 "Unknown SecurityResult");
1020 _negotiate_server_init: function () {
1021 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1024 this._fb_width
= this._sock
.rQshift16();
1025 this._fb_height
= this._sock
.rQshift16();
1026 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1029 var bpp
= this._sock
.rQshift8();
1030 var depth
= this._sock
.rQshift8();
1031 var big_endian
= this._sock
.rQshift8();
1032 var true_color
= this._sock
.rQshift8();
1034 var red_max
= this._sock
.rQshift16();
1035 var green_max
= this._sock
.rQshift16();
1036 var blue_max
= this._sock
.rQshift16();
1037 var red_shift
= this._sock
.rQshift8();
1038 var green_shift
= this._sock
.rQshift8();
1039 var blue_shift
= this._sock
.rQshift8();
1040 this._sock
.rQskipBytes(3); // padding
1042 // NB(directxman12): we don't want to call any callbacks or print messages until
1043 // *after* we're past the point where we could backtrack
1045 /* Connection name/title */
1046 var name_length = this._sock.rQshift32();
1047 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1048 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1050 if (this._rfb_tightvnc) {
1051 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1052 // In TightVNC mode, ServerInit message is extended
1053 var numServerMessages = this._sock.rQshift16();
1054 var numClientMessages = this._sock.rQshift16();
1055 var numEncodings = this._sock.rQshift16();
1056 this._sock.rQskipBytes(2); // padding
1058 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1059 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1061 // we don't actually do anything with the capability information that TIGHT sends,
1062 // so we just skip the all of this.
1064 // TIGHT server message capabilities
1065 this._sock.rQskipBytes(16 * numServerMessages);
1067 // TIGHT client message capabilities
1068 this._sock.rQskipBytes(16 * numClientMessages);
1070 // TIGHT encoding capabilities
1071 this._sock.rQskipBytes(16 * numEncodings);
1074 // NB(directxman12): these are down here so that we don't run them multiple times
1076 Log.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1077 ", bpp: " + bpp + ", depth: " + depth +
1078 ", big_endian: " + big_endian +
1079 ", true_color: " + true_color +
1080 ", red_max: " + red_max +
1081 ", green_max: " + green_max +
1082 ", blue_max: " + blue_max +
1083 ", red_shift: " + red_shift +
1084 ", green_shift: " + green_shift +
1085 ", blue_shift: " + blue_shift);
1087 if (big_endian !== 0) {
1088 Log.Warn("Server native endian is not little endian");
1091 if (red_shift !== 16) {
1092 Log.Warn("Server native red-shift is not 16");
1095 if (blue_shift !== 0) {
1096 Log.Warn("Server native blue-shift is not 0");
1099 // we're past the point where we could backtrack, so it's safe to call this
1100 this._onDesktopName(this, this._fb_name);
1102 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1103 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1104 this._true_color = false;
1107 this._display.set_true_color(this._true_color);
1108 this._display.resize(this._fb_width, this._fb_height);
1109 this._onFBResize(this, this._fb_width, this._fb_height);
1111 if (!this._view_only) { this._keyboard.grab(); }
1112 if (!this._view_only) { this._mouse.grab(); }
1114 if (this._true_color) {
1122 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1123 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1124 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1126 this._timing.fbu_rt_start = (new Date()).getTime();
1127 this._timing.pixels = 0;
1129 this._updateConnectionState('connected');
1133 /* RFB protocol initialization states:
1138 * ClientInitialization - not triggered by server message
1139 * ServerInitialization
1141 _init_msg: function () {
1142 switch (this._rfb_init_state
) {
1143 case 'ProtocolVersion':
1144 return this._negotiate_protocol_version();
1147 return this._negotiate_security();
1149 case 'Authentication':
1150 return this._negotiate_authentication();
1152 case 'SecurityResult':
1153 return this._handle_security_result();
1155 case 'ClientInitialisation':
1156 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1157 this._rfb_init_state
= 'ServerInitialisation';
1160 case 'ServerInitialisation':
1161 return this._negotiate_server_init();
1164 return this._fail("Internal error", "Unknown init state: " +
1165 this._rfb_init_state
);
1169 _handle_set_colour_map_msg: function () {
1170 Log
.Debug("SetColorMapEntries");
1171 this._sock
.rQskip8(); // Padding
1173 var first_colour
= this._sock
.rQshift16();
1174 var num_colours
= this._sock
.rQshift16();
1175 if (this._sock
.rQwait('SetColorMapEntries', num_colours
* 6, 6)) { return false; }
1177 for (var c
= 0; c
< num_colours
; c
++) {
1178 var red
= parseInt(this._sock
.rQshift16() / 256, 10);
1179 var green
= parseInt(this._sock
.rQshift16() / 256, 10);
1180 var blue
= parseInt(this._sock
.rQshift16() / 256, 10);
1181 this._display
.set_colourMap([blue
, green
, red
], first_colour
+ c
);
1183 Log
.Debug("colourMap: " + this._display
.get_colourMap());
1184 Log
.Info("Registered " + num_colours
+ " colourMap entries");
1189 _handle_server_cut_text: function () {
1190 Log
.Debug("ServerCutText");
1192 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1193 this._sock
.rQskipBytes(3); // Padding
1194 var length
= this._sock
.rQshift32();
1195 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1197 var text
= this._sock
.rQshiftStr(length
);
1199 if (this._view_only
) { return true; }
1201 this._onClipboard(this, text
);
1206 _handle_server_fence_msg: function() {
1207 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1208 this._sock
.rQskipBytes(3); // Padding
1209 var flags
= this._sock
.rQshift32();
1210 var length
= this._sock
.rQshift8();
1212 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1215 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1219 var payload
= this._sock
.rQshiftStr(length
);
1221 this._supportsFence
= true;
1226 * (1<<0) - BlockBefore
1227 * (1<<1) - BlockAfter
1232 if (!(flags
& (1<<31))) {
1233 return this._fail("Internal error",
1234 "Unexpected fence response");
1237 // Filter out unsupported flags
1238 // FIXME: support syncNext
1239 flags
&= (1<<0) | (1<<1);
1241 // BlockBefore and BlockAfter are automatically handled by
1242 // the fact that we process each incoming message
1244 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1249 _handle_xvp_msg: function () {
1250 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1251 this._sock
.rQskip8(); // Padding
1252 var xvp_ver
= this._sock
.rQshift8();
1253 var xvp_msg
= this._sock
.rQshift8();
1257 Log
.Error("Operation Failed");
1258 this._notification("XVP Operation Failed", 'error');
1261 this._rfb_xvp_ver
= xvp_ver
;
1262 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1263 this._onXvpInit(this._rfb_xvp_ver
);
1266 this._fail("Unexpected server message",
1267 "Illegal server XVP message " + xvp_msg
);
1274 _normal_msg: function () {
1277 if (this._FBU
.rects
> 0) {
1280 msg_type
= this._sock
.rQshift8();
1284 case 0: // FramebufferUpdate
1285 var ret
= this._framebufferUpdate();
1286 if (ret
&& !this._enabledContinuousUpdates
) {
1287 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1288 this._fb_width
, this._fb_height
);
1292 case 1: // SetColorMapEntries
1293 return this._handle_set_colour_map_msg();
1300 case 3: // ServerCutText
1301 return this._handle_server_cut_text();
1303 case 150: // EndOfContinuousUpdates
1304 var first
= !(this._supportsContinuousUpdates
);
1305 this._supportsContinuousUpdates
= true;
1306 this._enabledContinuousUpdates
= false;
1308 this._enabledContinuousUpdates
= true;
1309 this._updateContinuousUpdates();
1310 Log
.Info("Enabling continuous updates.");
1312 // FIXME: We need to send a framebufferupdaterequest here
1313 // if we add support for turning off continuous updates
1317 case 248: // ServerFence
1318 return this._handle_server_fence_msg();
1321 return this._handle_xvp_msg();
1324 this._fail("Unexpected server message", "Type:" + msg_type
);
1325 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1330 _onFlush: function() {
1331 this._flushing
= false;
1332 // Resume processing
1333 if (this._sock
.rQlen() > 0) {
1334 this._handle_message();
1338 _framebufferUpdate: function () {
1342 if (this._FBU
.rects
=== 0) {
1343 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1344 this._sock
.rQskip8(); // Padding
1345 this._FBU
.rects
= this._sock
.rQshift16();
1346 this._FBU
.bytes
= 0;
1347 this._timing
.cur_fbu
= 0;
1348 if (this._timing
.fbu_rt_start
> 0) {
1349 now
= (new Date()).getTime();
1350 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1353 // Make sure the previous frame is fully rendered first
1354 // to avoid building up an excessive queue
1355 if (this._display
.pending()) {
1356 this._flushing
= true;
1357 this._display
.flush();
1362 while (this._FBU
.rects
> 0) {
1363 if (this._rfb_connection_state
!== 'connected') { return false; }
1365 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1366 if (this._FBU
.bytes
=== 0) {
1367 if (this._sock
.rQwait("rect header", 12)) { return false; }
1368 /* New FramebufferUpdate */
1370 var hdr
= this._sock
.rQshiftBytes(12);
1371 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1372 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1373 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1374 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1375 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1376 (hdr
[10] << 8) + hdr
[11], 10);
1378 this._onFBUReceive(this,
1379 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1380 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1381 'encoding': this._FBU
.encoding
,
1382 'encodingName': this._encNames
[this._FBU
.encoding
]});
1384 if (!this._encNames
[this._FBU
.encoding
]) {
1385 this._fail("Unexpected server message",
1386 "Unsupported encoding " +
1387 this._FBU
.encoding
);
1392 this._timing
.last_fbu
= (new Date()).getTime();
1394 ret
= this._encHandlers
[this._FBU
.encoding
]();
1396 now
= (new Date()).getTime();
1397 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1400 this._encStats
[this._FBU
.encoding
][0]++;
1401 this._encStats
[this._FBU
.encoding
][1]++;
1402 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1405 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1406 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1407 this._timing
.fbu_rt_start
> 0) {
1408 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1409 this._timing
.full_fbu_cnt
++;
1410 Log
.Info("Timing of full FBU, curr: " +
1411 this._timing
.cur_fbu
+ ", total: " +
1412 this._timing
.full_fbu_total
+ ", cnt: " +
1413 this._timing
.full_fbu_cnt
+ ", avg: " +
1414 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1417 if (this._timing
.fbu_rt_start
> 0) {
1418 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1419 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1420 this._timing
.fbu_rt_cnt
++;
1421 Log
.Info("full FBU round-trip, cur: " +
1422 fbu_rt_diff
+ ", total: " +
1423 this._timing
.fbu_rt_total
+ ", cnt: " +
1424 this._timing
.fbu_rt_cnt
+ ", avg: " +
1425 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1426 this._timing
.fbu_rt_start
= 0;
1430 if (!ret
) { return ret
; } // need more data
1433 this._display
.flip();
1435 this._onFBUComplete(this,
1436 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1437 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1438 'encoding': this._FBU
.encoding
,
1439 'encodingName': this._encNames
[this._FBU
.encoding
]});
1441 return true; // We finished this FBU
1444 _updateContinuousUpdates: function() {
1445 if (!this._enabledContinuousUpdates
) { return; }
1447 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1448 this._fb_width
, this._fb_height
);
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 ['true_color', 'rw', 'bool'], // Request true color pixel data
1457 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1458 ['shared', 'rw', 'bool'], // Request shared mode
1459 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1460 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1461 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1462 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1463 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1464 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1466 // Callback functions
1467 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1468 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1469 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1470 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1471 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1472 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1473 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1474 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1475 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1476 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1477 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1480 RFB
.prototype.set_local_cursor = function (cursor
) {
1481 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1482 this._local_cursor
= false;
1483 this._display
.disableLocalCursor(); //Only show server-side cursor
1485 if (this._display
.get_cursor_uri()) {
1486 this._local_cursor
= true;
1488 Log
.Warn("Browser does not support local cursor");
1489 this._display
.disableLocalCursor();
1493 // Need to send an updated list of encodings if we are connected
1494 if (this._rfb_connection_state
=== "connected") {
1495 RFB
.messages
.clientEncodings(this._sock
, this._encodings
, cursor
,
1500 RFB
.prototype.set_view_only = function (view_only
) {
1501 this._view_only
= view_only
;
1503 if (this._rfb_connection_state
=== "connecting" ||
1504 this._rfb_connection_state
=== "connected") {
1506 this._keyboard
.ungrab();
1507 this._mouse
.ungrab();
1509 this._keyboard
.grab();
1515 RFB
.prototype.get_display = function () { return this._display
; };
1516 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1517 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1521 keyEvent: function (sock
, keysym
, down
) {
1522 var buff
= sock
._sQ
;
1523 var offset
= sock
._sQlen
;
1525 buff
[offset
] = 4; // msg-type
1526 buff
[offset
+ 1] = down
;
1528 buff
[offset
+ 2] = 0;
1529 buff
[offset
+ 3] = 0;
1531 buff
[offset
+ 4] = (keysym
>> 24);
1532 buff
[offset
+ 5] = (keysym
>> 16);
1533 buff
[offset
+ 6] = (keysym
>> 8);
1534 buff
[offset
+ 7] = keysym
;
1540 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1541 function getRFBkeycode(xt_scancode
) {
1542 var upperByte
= (keycode
>> 8);
1543 var lowerByte
= (keycode
& 0x00ff);
1544 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1545 lowerByte
= lowerByte
| 0x80;
1551 var buff
= sock
._sQ
;
1552 var offset
= sock
._sQlen
;
1554 buff
[offset
] = 255; // msg-type
1555 buff
[offset
+ 1] = 0; // sub msg-type
1557 buff
[offset
+ 2] = (down
>> 8);
1558 buff
[offset
+ 3] = down
;
1560 buff
[offset
+ 4] = (keysym
>> 24);
1561 buff
[offset
+ 5] = (keysym
>> 16);
1562 buff
[offset
+ 6] = (keysym
>> 8);
1563 buff
[offset
+ 7] = keysym
;
1565 var RFBkeycode
= getRFBkeycode(keycode
);
1567 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1568 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1569 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1570 buff
[offset
+ 11] = RFBkeycode
;
1576 pointerEvent: function (sock
, x
, y
, mask
) {
1577 var buff
= sock
._sQ
;
1578 var offset
= sock
._sQlen
;
1580 buff
[offset
] = 5; // msg-type
1582 buff
[offset
+ 1] = mask
;
1584 buff
[offset
+ 2] = x
>> 8;
1585 buff
[offset
+ 3] = x
;
1587 buff
[offset
+ 4] = y
>> 8;
1588 buff
[offset
+ 5] = y
;
1594 // TODO(directxman12): make this unicode compatible?
1595 clientCutText: function (sock
, text
) {
1596 var buff
= sock
._sQ
;
1597 var offset
= sock
._sQlen
;
1599 buff
[offset
] = 6; // msg-type
1601 buff
[offset
+ 1] = 0; // padding
1602 buff
[offset
+ 2] = 0; // padding
1603 buff
[offset
+ 3] = 0; // padding
1605 var n
= text
.length
;
1607 buff
[offset
+ 4] = n
>> 24;
1608 buff
[offset
+ 5] = n
>> 16;
1609 buff
[offset
+ 6] = n
>> 8;
1610 buff
[offset
+ 7] = n
;
1612 for (var i
= 0; i
< n
; i
++) {
1613 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1616 sock
._sQlen
+= 8 + n
;
1620 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1621 var buff
= sock
._sQ
;
1622 var offset
= sock
._sQlen
;
1624 buff
[offset
] = 251; // msg-type
1625 buff
[offset
+ 1] = 0; // padding
1626 buff
[offset
+ 2] = width
>> 8; // width
1627 buff
[offset
+ 3] = width
;
1628 buff
[offset
+ 4] = height
>> 8; // height
1629 buff
[offset
+ 5] = height
;
1631 buff
[offset
+ 6] = 1; // number-of-screens
1632 buff
[offset
+ 7] = 0; // padding
1635 buff
[offset
+ 8] = id
>> 24; // id
1636 buff
[offset
+ 9] = id
>> 16;
1637 buff
[offset
+ 10] = id
>> 8;
1638 buff
[offset
+ 11] = id
;
1639 buff
[offset
+ 12] = 0; // x-position
1640 buff
[offset
+ 13] = 0;
1641 buff
[offset
+ 14] = 0; // y-position
1642 buff
[offset
+ 15] = 0;
1643 buff
[offset
+ 16] = width
>> 8; // width
1644 buff
[offset
+ 17] = width
;
1645 buff
[offset
+ 18] = height
>> 8; // height
1646 buff
[offset
+ 19] = height
;
1647 buff
[offset
+ 20] = flags
>> 24; // flags
1648 buff
[offset
+ 21] = flags
>> 16;
1649 buff
[offset
+ 22] = flags
>> 8;
1650 buff
[offset
+ 23] = flags
;
1656 clientFence: function (sock
, flags
, payload
) {
1657 var buff
= sock
._sQ
;
1658 var offset
= sock
._sQlen
;
1660 buff
[offset
] = 248; // msg-type
1662 buff
[offset
+ 1] = 0; // padding
1663 buff
[offset
+ 2] = 0; // padding
1664 buff
[offset
+ 3] = 0; // padding
1666 buff
[offset
+ 4] = flags
>> 24; // flags
1667 buff
[offset
+ 5] = flags
>> 16;
1668 buff
[offset
+ 6] = flags
>> 8;
1669 buff
[offset
+ 7] = flags
;
1671 var n
= payload
.length
;
1673 buff
[offset
+ 8] = n
; // length
1675 for (var i
= 0; i
< n
; i
++) {
1676 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1679 sock
._sQlen
+= 9 + n
;
1683 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1684 var buff
= sock
._sQ
;
1685 var offset
= sock
._sQlen
;
1687 buff
[offset
] = 150; // msg-type
1688 buff
[offset
+ 1] = enable
; // enable-flag
1690 buff
[offset
+ 2] = x
>> 8; // x
1691 buff
[offset
+ 3] = x
;
1692 buff
[offset
+ 4] = y
>> 8; // y
1693 buff
[offset
+ 5] = y
;
1694 buff
[offset
+ 6] = width
>> 8; // width
1695 buff
[offset
+ 7] = width
;
1696 buff
[offset
+ 8] = height
>> 8; // height
1697 buff
[offset
+ 9] = height
;
1703 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1704 var buff
= sock
._sQ
;
1705 var offset
= sock
._sQlen
;
1707 buff
[offset
] = 0; // msg-type
1709 buff
[offset
+ 1] = 0; // padding
1710 buff
[offset
+ 2] = 0; // padding
1711 buff
[offset
+ 3] = 0; // padding
1713 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1714 buff
[offset
+ 5] = depth
* 8; // depth
1715 buff
[offset
+ 6] = 0; // little-endian
1716 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1718 buff
[offset
+ 8] = 0; // red-max
1719 buff
[offset
+ 9] = 255; // red-max
1721 buff
[offset
+ 10] = 0; // green-max
1722 buff
[offset
+ 11] = 255; // green-max
1724 buff
[offset
+ 12] = 0; // blue-max
1725 buff
[offset
+ 13] = 255; // blue-max
1727 buff
[offset
+ 14] = 16; // red-shift
1728 buff
[offset
+ 15] = 8; // green-shift
1729 buff
[offset
+ 16] = 0; // blue-shift
1731 buff
[offset
+ 17] = 0; // padding
1732 buff
[offset
+ 18] = 0; // padding
1733 buff
[offset
+ 19] = 0; // padding
1739 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1740 var buff
= sock
._sQ
;
1741 var offset
= sock
._sQlen
;
1743 buff
[offset
] = 2; // msg-type
1744 buff
[offset
+ 1] = 0; // padding
1746 // offset + 2 and offset + 3 are encoding count
1748 var i
, j
= offset
+ 4, cnt
= 0;
1749 for (i
= 0; i
< encodings
.length
; i
++) {
1750 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1751 Log
.Debug("Skipping Cursor pseudo-encoding");
1752 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1753 // TODO: remove this when we have tight+non-true-color
1754 Log
.Warn("Skipping tight as it is only supported with true color");
1756 var enc
= encodings
[i
][1];
1757 buff
[j
] = enc
>> 24;
1758 buff
[j
+ 1] = enc
>> 16;
1759 buff
[j
+ 2] = enc
>> 8;
1767 buff
[offset
+ 2] = cnt
>> 8;
1768 buff
[offset
+ 3] = cnt
;
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 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1816 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1817 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1818 var curr_height
= Math
.min(this._FBU
.lines
,
1819 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1820 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1821 curr_height
, this._sock
.get_rQ(),
1822 this._sock
.get_rQi());
1823 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1824 this._FBU
.lines
-= curr_height
;
1826 if (this._FBU
.lines
> 0) {
1827 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1830 this._FBU
.bytes
= 0;
1836 COPYRECT: function () {
1837 this._FBU
.bytes
= 4;
1838 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1839 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1840 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1844 this._FBU
.bytes
= 0;
1850 if (this._FBU
.subrects
=== 0) {
1851 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1852 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1853 this._FBU
.subrects
= this._sock
.rQshift32();
1854 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1855 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1858 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1859 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1860 var x
= this._sock
.rQshift16();
1861 var y
= this._sock
.rQshift16();
1862 var width
= this._sock
.rQshift16();
1863 var height
= this._sock
.rQshift16();
1864 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1865 this._FBU
.subrects
--;
1868 if (this._FBU
.subrects
> 0) {
1869 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1870 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1873 this._FBU
.bytes
= 0;
1879 HEXTILE: function () {
1880 var rQ
= this._sock
.get_rQ();
1881 var rQi
= this._sock
.get_rQi();
1883 if (this._FBU
.tiles
=== 0) {
1884 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1885 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1886 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1887 this._FBU
.tiles
= this._FBU
.total_tiles
;
1890 while (this._FBU
.tiles
> 0) {
1891 this._FBU
.bytes
= 1;
1892 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1893 var subencoding
= rQ
[rQi
]; // Peek
1894 if (subencoding
> 30) { // Raw
1895 this._fail("Unexpected server message",
1896 "Illegal hextile subencoding: " + subencoding
);
1901 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1902 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1903 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1904 var x
= this._FBU
.x
+ tile_x
* 16;
1905 var y
= this._FBU
.y
+ tile_y
* 16;
1906 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1907 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1909 // Figure out how much we are expecting
1910 if (subencoding
& 0x01) { // Raw
1911 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1913 if (subencoding
& 0x02) { // Background
1914 this._FBU
.bytes
+= this._fb_Bpp
;
1916 if (subencoding
& 0x04) { // Foreground
1917 this._FBU
.bytes
+= this._fb_Bpp
;
1919 if (subencoding
& 0x08) { // AnySubrects
1920 this._FBU
.bytes
++; // Since we aren't shifting it off
1921 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1922 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1923 if (subencoding
& 0x10) { // SubrectsColoured
1924 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1926 this._FBU
.bytes
+= subrects
* 2;
1931 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1933 // We know the encoding and have a whole tile
1934 this._FBU
.subencoding
= rQ
[rQi
];
1936 if (this._FBU
.subencoding
=== 0) {
1937 if (this._FBU
.lastsubencoding
& 0x01) {
1938 // Weird: ignore blanks are RAW
1939 Log
.Debug(" Ignoring blank after RAW");
1941 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1943 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1944 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1945 rQi
+= this._FBU
.bytes
- 1;
1947 if (this._FBU
.subencoding
& 0x02) { // Background
1948 if (this._fb_Bpp
== 1) {
1949 this._FBU
.background
= rQ
[rQi
];
1952 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1954 rQi
+= this._fb_Bpp
;
1956 if (this._FBU
.subencoding
& 0x04) { // Foreground
1957 if (this._fb_Bpp
== 1) {
1958 this._FBU
.foreground
= rQ
[rQi
];
1960 // this._fb_Bpp is 4
1961 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1963 rQi
+= this._fb_Bpp
;
1966 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1967 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1971 for (var s
= 0; s
< subrects
; s
++) {
1973 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1974 if (this._fb_Bpp
=== 1) {
1978 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1980 rQi
+= this._fb_Bpp
;
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 getTightCLength: function (arr
) {
2013 var header
= 1, data
= 0;
2014 data
+= arr
[0] & 0x7f;
2015 if (arr
[0] & 0x80) {
2017 data
+= (arr
[1] & 0x7f) << 7;
2018 if (arr
[1] & 0x80) {
2020 data
+= arr
[2] << 14;
2023 return [header
, data
];
2026 display_tight: function (isTightPNG
) {
2027 if (this._fb_depth
=== 1) {
2028 this._fail("Internal error",
2029 "Tight protocol handler only implements " +
2033 this._FBU
.bytes
= 1; // compression-control byte
2034 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2036 var checksum = function (data
) {
2038 for (var i
= 0; i
< data
.length
; i
++) {
2040 if (sum
> 65536) sum
-= 65536;
2045 var resetStreams
= 0;
2047 var decompress = function (data
, expected
) {
2048 for (var i
= 0; i
< 4; i
++) {
2049 if ((resetStreams
>> i
) & 1) {
2050 this._FBU
.zlibs
[i
].reset();
2051 Log
.Info("Reset zlib stream " + i
);
2055 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2056 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2057 /*if (uncompressed.status !== 0) {
2058 Log.Error("Invalid data in zlib stream");
2061 //return uncompressed.data;
2062 return uncompressed
;
2065 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2066 // Convert indexed (palette based) image data to RGB
2067 // TODO: reduce number of calculations inside loop
2068 var dest
= this._destBuff
;
2069 var w
= Math
.floor((width
+ 7) / 8);
2070 var w1
= Math
.floor(width
/ 8);
2072 /*for (var y = 0; y < height; y++) {
2074 var yoffset = y * width;
2075 var ybitoffset = y * w;
2076 var xoffset, targetbyte;
2077 for (x = 0; x < w1; x++) {
2078 xoffset = yoffset + x * 8;
2079 targetbyte = data[ybitoffset + x];
2080 for (b = 7; b >= 0; b--) {
2081 dp = (xoffset + 7 - b) * 3;
2082 sp = (targetbyte >> b & 1) * 3;
2083 dest[dp] = palette[sp];
2084 dest[dp + 1] = palette[sp + 1];
2085 dest[dp + 2] = palette[sp + 2];
2089 xoffset = yoffset + x * 8;
2090 targetbyte = data[ybitoffset + x];
2091 for (b = 7; b >= 8 - width % 8; b--) {
2092 dp = (xoffset + 7 - b) * 3;
2093 sp = (targetbyte >> b & 1) * 3;
2094 dest[dp] = palette[sp];
2095 dest[dp + 1] = palette[sp + 1];
2096 dest[dp + 2] = palette[sp + 2];
2100 for (var y
= 0; y
< height
; y
++) {
2102 for (x
= 0; x
< w1
; x
++) {
2103 for (b
= 7; b
>= 0; b
--) {
2104 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2105 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2106 dest
[dp
] = palette
[sp
];
2107 dest
[dp
+ 1] = palette
[sp
+ 1];
2108 dest
[dp
+ 2] = palette
[sp
+ 2];
2113 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2114 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2115 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2116 dest
[dp
] = palette
[sp
];
2117 dest
[dp
+ 1] = palette
[sp
+ 1];
2118 dest
[dp
+ 2] = palette
[sp
+ 2];
2126 var indexedToRGBX = function (data
, palette
, width
, height
) {
2127 // Convert indexed (palette based) image data to RGB
2128 var dest
= this._destBuff
;
2129 var total
= width
* height
* 4;
2130 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2131 var sp
= data
[j
] * 3;
2132 dest
[i
] = palette
[sp
];
2133 dest
[i
+ 1] = palette
[sp
+ 1];
2134 dest
[i
+ 2] = palette
[sp
+ 2];
2141 var rQi
= this._sock
.get_rQi();
2142 var rQ
= this._sock
.rQwhole();
2144 var cl_header
, cl_data
;
2146 var handlePalette = function () {
2147 var numColors
= rQ
[rQi
+ 2] + 1;
2148 var paletteSize
= numColors
* this._fb_depth
;
2149 this._FBU
.bytes
+= paletteSize
;
2150 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2152 var bpp
= (numColors
<= 2) ? 1 : 8;
2153 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2155 if (rowSize
* this._FBU
.height
< 12) {
2158 cl_data
= rowSize
* this._FBU
.height
;
2159 //clength = [0, rowSize * this._FBU.height];
2161 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2162 var cl_offset
= rQi
+ 3 + paletteSize
;
2165 cl_data
+= rQ
[cl_offset
] & 0x7f;
2166 if (rQ
[cl_offset
] & 0x80) {
2168 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2169 if (rQ
[cl_offset
+ 1] & 0x80) {
2171 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2174 // end inline getTightCLength
2177 this._FBU
.bytes
+= cl_header
+ cl_data
;
2178 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2180 // Shift ctl, filter id, num colors, palette entries, and clength off
2181 this._sock
.rQskipBytes(3);
2182 //var palette = this._sock.rQshiftBytes(paletteSize);
2183 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2184 this._sock
.rQskipBytes(cl_header
);
2187 data
= this._sock
.rQshiftBytes(cl_data
);
2189 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2192 // Convert indexed (palette based) image data to RGB
2194 if (numColors
== 2) {
2195 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2196 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2198 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2199 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2206 var handleCopy = function () {
2208 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2209 if (uncompressedSize
< 12) {
2212 cl_data
= uncompressedSize
;
2214 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2215 var cl_offset
= rQi
+ 1;
2218 cl_data
+= rQ
[cl_offset
] & 0x7f;
2219 if (rQ
[cl_offset
] & 0x80) {
2221 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2222 if (rQ
[cl_offset
+ 1] & 0x80) {
2224 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2227 // end inline getTightCLength
2229 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2230 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2232 // Shift ctl, clength off
2233 this._sock
.rQshiftBytes(1 + cl_header
);
2236 data
= this._sock
.rQshiftBytes(cl_data
);
2238 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2241 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2246 var ctl
= this._sock
.rQpeek8();
2248 // Keep tight reset bits
2249 resetStreams
= ctl
& 0xF;
2251 // Figure out filter
2253 streamId
= ctl
& 0x3;
2255 if (ctl
=== 0x08) cmode
= "fill";
2256 else if (ctl
=== 0x09) cmode
= "jpeg";
2257 else if (ctl
=== 0x0A) cmode
= "png";
2258 else if (ctl
& 0x04) cmode
= "filter";
2259 else if (ctl
< 0x04) cmode
= "copy";
2260 else return this._fail("Unexpected server message",
2261 "Illegal tight compression received, " +
2264 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2265 return this._fail("Unexpected server message",
2266 "filter/copy received in tightPNG mode");
2270 // fill use fb_depth because TPIXELs drop the padding byte
2271 case "fill": // TPIXEL
2272 this._FBU
.bytes
+= this._fb_depth
;
2274 case "jpeg": // max clength
2275 this._FBU
.bytes
+= 3;
2277 case "png": // max clength
2278 this._FBU
.bytes
+= 3;
2280 case "filter": // filter id + num colors if palette
2281 this._FBU
.bytes
+= 2;
2287 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2289 // Determine FBU.bytes
2293 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);
2294 this._sock
.rQskipBytes(4);
2298 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2299 var cl_offset
= rQi
+ 1;
2302 cl_data
+= rQ
[cl_offset
] & 0x7f;
2303 if (rQ
[cl_offset
] & 0x80) {
2305 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2306 if (rQ
[cl_offset
+ 1] & 0x80) {
2308 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2311 // end inline getTightCLength
2312 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2313 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2315 // We have everything, render it
2316 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2317 data
= this._sock
.rQshiftBytes(cl_data
);
2318 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2321 var filterId
= rQ
[rQi
+ 1];
2322 if (filterId
=== 1) {
2323 if (!handlePalette()) { return false; }
2325 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2326 // Filter 2, Gradient is valid but not use if jpeg is enabled
2327 this._fail("Unexpected server message",
2328 "Unsupported tight subencoding received, " +
2329 "filter: " + filterId
);
2333 if (!handleCopy()) { return false; }
2338 this._FBU
.bytes
= 0;
2344 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2345 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2347 last_rect: function () {
2348 this._FBU
.rects
= 0;
2352 handle_FB_resize: function () {
2353 this._fb_width
= this._FBU
.width
;
2354 this._fb_height
= this._FBU
.height
;
2355 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2356 this._display
.resize(this._fb_width
, this._fb_height
);
2357 this._onFBResize(this, this._fb_width
, this._fb_height
);
2358 this._timing
.fbu_rt_start
= (new Date()).getTime();
2359 this._updateContinuousUpdates();
2361 this._FBU
.bytes
= 0;
2362 this._FBU
.rects
-= 1;
2366 ExtendedDesktopSize: function () {
2367 this._FBU
.bytes
= 1;
2368 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2370 this._supportsSetDesktopSize
= true;
2371 var number_of_screens
= this._sock
.rQpeek8();
2373 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2374 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2376 this._sock
.rQskipBytes(1); // number-of-screens
2377 this._sock
.rQskipBytes(3); // padding
2379 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2380 // Save the id and flags of the first screen
2382 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2383 this._sock
.rQskipBytes(2); // x-position
2384 this._sock
.rQskipBytes(2); // y-position
2385 this._sock
.rQskipBytes(2); // width
2386 this._sock
.rQskipBytes(2); // height
2387 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2389 this._sock
.rQskipBytes(16);
2394 * The x-position indicates the reason for the change:
2396 * 0 - server resized on its own
2397 * 1 - this client requested the resize
2398 * 2 - another client requested the resize
2401 // We need to handle errors when we requested the resize.
2402 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2404 // The y-position indicates the status code from the server
2405 switch (this._FBU
.y
) {
2407 msg
= "Resize is administratively prohibited";
2410 msg
= "Out of resources";
2413 msg
= "Invalid screen layout";
2416 msg
= "Unknown reason";
2419 this._notification("Server did not accept the resize request: "
2424 this._encHandlers
.handle_FB_resize();
2428 DesktopSize: function () {
2429 this._encHandlers
.handle_FB_resize();
2433 Cursor: function () {
2434 Log
.Debug(">> set_cursor");
2435 var x
= this._FBU
.x
; // hotspot-x
2436 var y
= this._FBU
.y
; // hotspot-y
2437 var w
= this._FBU
.width
;
2438 var h
= this._FBU
.height
;
2440 var pixelslength
= w
* h
* this._fb_Bpp
;
2441 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2443 this._FBU
.bytes
= pixelslength
+ masklength
;
2444 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2446 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2447 this._sock
.rQshiftBytes(masklength
),
2450 this._FBU
.bytes
= 0;
2453 Log
.Debug("<< set_cursor");
2457 QEMUExtendedKeyEvent: function () {
2460 var keyboardEvent
= document
.createEvent("keyboardEvent");
2461 if (keyboardEvent
.code
!== undefined) {
2462 this._qemuExtKeyEventSupported
= true;
2463 this._keyboard
.setQEMUVNCKeyboardHandler();
2467 JPEG_quality_lo: function () {
2468 Log
.Error("Server sent jpeg_quality pseudo-encoding");
2471 compress_lo: function () {
2472 Log
.Error("Server sent compress level pseudo-encoding");