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)
14 * import Util from "./util";
15 * import Display from "./display";
16 * import { Keyboard, Mouse } from "./input/devices"
17 * import Websock from "./websock"
18 * import Base64 from "./base64";
19 * import DES from "./des";
20 * import KeyTable from "./input/keysym";
21 * import XtScancode from "./input/xtscancodes";
22 * import Inflator from "./inflator.mod";
24 /*jslint white: false, browser: true */
25 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
27 /* [module] export default */ function RFB(defaults
) {
34 this._rfb_port
= 5900;
35 this._rfb_password
= '';
38 this._rfb_connection_state
= '';
39 this._rfb_init_state
= '';
40 this._rfb_version
= 0;
41 this._rfb_max_version
= 3.8;
42 this._rfb_auth_scheme
= '';
43 this._rfb_disconnect_reason
= "";
45 this._rfb_tightvnc
= false;
46 this._rfb_xvp_ver
= 0;
48 // In preference order
57 // Psuedo-encoding settings
59 //['JPEG_quality_lo', -32 ],
60 ['JPEG_quality_med', -26 ],
61 //['JPEG_quality_hi', -23 ],
62 //['compress_lo', -255 ],
63 ['compress_hi', -247 ],
65 ['DesktopSize', -223 ],
68 ['QEMUExtendedKeyEvent', -258 ],
69 ['ExtendedDesktopSize', -308 ],
72 ['ContinuousUpdates', -313 ]
75 this._encHandlers
= {};
79 this._sock
= null; // Websock object
80 this._display
= null; // Display object
81 this._flushing
= false; // Display flushing state
82 this._keyboard
= null; // Keyboard input handler object
83 this._mouse
= null; // Mouse input handler object
84 this._disconnTimer
= null; // disconnection timer
86 this._supportsFence
= false;
88 this._supportsContinuousUpdates
= false;
89 this._enabledContinuousUpdates
= false;
91 // Frame buffer update state
105 zlib
: [] // TIGHT zlib streams
114 this._destBuff
= null;
115 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
117 this._rre_chunk_sz
= 100;
132 this._supportsSetDesktopSize
= false;
134 this._screen_flags
= 0;
137 this._mouse_buttonMask
= 0;
138 this._mouse_arr
= [];
139 this._viewportDragging
= false;
140 this._viewportDragPos
= {};
141 this._viewportHasMoved
= false;
143 // QEMU Extended Key Event support - default to false
144 this._qemuExtKeyEventSupported
= false;
146 // set the default value on user-facing properties
147 Util
.set_defaults(this, defaults
, {
148 'target': 'null', // VNC display rendering Canvas object
149 'focusContainer': document
, // DOM element that captures keyboard input
150 'encrypt': false, // Use TLS/SSL/wss encryption
151 'true_color': true, // Request true color pixel data
152 'local_cursor': false, // Request locally rendered cursor
153 'shared': true, // Request shared mode
154 'view_only': false, // Disable client mouse/keyboard
155 'xvp_password_sep': '@', // Separator for XVP password fields
156 'disconnectTimeout': 3, // Time (s) to wait for disconnection
157 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
158 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
159 'viewportDrag': false, // Move the viewport on mouse drags
161 // Callback functions
162 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
163 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
164 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
165 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
166 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
167 'onBell': function () { }, // onBell(rfb): RFB Bell message received
168 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
169 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
170 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
171 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
172 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
176 Util
.Debug(">> RFB.constructor");
178 // populate encHandlers with bound versions
179 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
180 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
183 // Create lookup tables based on encoding number
184 for (var i
= 0; i
< this._encodings
.length
; i
++) {
185 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
186 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
187 this._encStats
[this._encodings
[i
][1]] = [0, 0];
190 // NB: nothing that needs explicit teardown should be done
191 // before this point, since this can throw an exception
193 this._display
= new Display({target
: this._target
,
194 onFlush
: this._onFlush
.bind(this)});
196 Util
.Error("Display exception: " + exc
);
200 this._keyboard
= new Keyboard({target
: this._focusContainer
,
201 onKeyPress
: this._handleKeyPress
.bind(this)});
203 this._mouse
= new Mouse({target
: this._target
,
204 onMouseButton
: this._handleMouseButton
.bind(this),
205 onMouseMove
: this._handleMouseMove
.bind(this),
206 notify
: this._keyboard
.sync
.bind(this._keyboard
)});
208 this._sock
= new Websock();
209 this._sock
.on('message', this._handle_message
.bind(this));
210 this._sock
.on('open', function () {
211 if ((this._rfb_connection_state
=== 'connecting') &&
212 (this._rfb_init_state
=== '')) {
213 this._rfb_init_state
= 'ProtocolVersion';
214 Util
.Debug("Starting VNC handshake");
216 this._fail("Unexpected server connection");
219 this._sock
.on('close', function (e
) {
220 Util
.Warn("WebSocket on-close event");
223 msg
= " (code: " + e
.code
;
225 msg
+= ", reason: " + e
.reason
;
229 switch (this._rfb_connection_state
) {
230 case 'disconnecting':
231 this._updateConnectionState('disconnected');
234 this._fail('Failed to connect to server', msg
);
237 // Handle disconnects that were initiated server-side
238 this._updateConnectionState('disconnecting');
239 this._updateConnectionState('disconnected');
242 this._fail("Unexpected server disconnect",
243 "Already disconnected: " + msg
);
246 this._fail("Unexpected server disconnect",
247 "Not in any state yet: " + msg
);
250 this._sock
.off('close');
252 this._sock
.on('error', function (e
) {
253 Util
.Warn("WebSocket on-error event");
259 var rmode
= this._display
.get_render_mode();
260 Util
.Info("Using native WebSockets, render mode: " + rmode
);
262 Util
.Debug("<< RFB.constructor");
266 var _
= Util
.Localisation
.get;
270 connect: function (host
, port
, password
, path
) {
271 this._rfb_host
= host
;
272 this._rfb_port
= port
;
273 this._rfb_password
= (password
!== undefined) ? password
: "";
274 this._rfb_path
= (path
!== undefined) ? path
: "";
276 if (!this._rfb_host
|| !this._rfb_port
) {
278 _("Must set host and port"));
281 this._rfb_init_state
= '';
282 this._updateConnectionState('connecting');
286 disconnect: function () {
287 this._updateConnectionState('disconnecting');
288 this._sock
.off('error');
289 this._sock
.off('message');
290 this._sock
.off('open');
293 sendPassword: function (passwd
) {
294 this._rfb_password
= passwd
;
295 setTimeout(this._init_msg
.bind(this), 0);
298 sendCtrlAltDel: function () {
299 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
300 Util
.Info("Sending Ctrl-Alt-Del");
302 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 1);
303 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 1);
304 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 1);
305 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 0);
306 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 0);
307 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 0);
311 xvpOp: function (ver
, op
) {
312 if (this._rfb_xvp_ver
< ver
) { return false; }
313 Util
.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
, down
) {
333 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
334 if (typeof down
!== 'undefined') {
335 Util
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
336 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
338 Util
.Info("Sending keysym (down + up): " + keysym
);
339 RFB
.messages
.keyEvent(this._sock
, keysym
, 1);
340 RFB
.messages
.keyEvent(this._sock
, keysym
, 0);
345 clipboardPasteFrom: function (text
) {
346 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
347 RFB
.messages
.clientCutText(this._sock
, text
);
350 // Requests a change of remote desktop size. This message is an extension
351 // and may only be sent if we have received an ExtendedDesktopSize message
352 requestDesktopSize: function (width
, height
) {
353 if (this._rfb_connection_state
!== 'connected' ||
358 if (this._supportsSetDesktopSize
) {
359 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
360 this._screen_id
, this._screen_flags
);
371 _connect: function () {
372 Util
.Debug(">> RFB.connect");
376 if (typeof UsingSocketIO
!== 'undefined') {
379 uri
= this._encrypt
? 'wss' : 'ws';
382 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
383 Util
.Info("connecting to " + uri
);
386 // WebSocket.onopen transitions to the RFB init states
387 this._sock
.open(uri
, this._wsProtocols
);
389 if (e
.name
=== 'SyntaxError') {
390 this._fail("Invalid host or port value given", e
);
392 this._fail("Error while connecting", e
);
396 Util
.Debug("<< RFB.connect");
399 _disconnect: function () {
400 Util
.Debug(">> RFB.disconnect");
404 Util
.Debug("<< RFB.disconnect");
407 _init_vars: function () {
410 this._FBU
.subrects
= 0; // RRE and HEXTILE
411 this._FBU
.lines
= 0; // RAW
412 this._FBU
.tiles
= 0; // HEXTILE
413 this._FBU
.zlibs
= []; // TIGHT zlib encoders
414 this._mouse_buttonMask
= 0;
415 this._mouse_arr
= [];
416 this._rfb_tightvnc
= false;
418 // Clear the per connection encoding stats
420 for (i
= 0; i
< this._encodings
.length
; i
++) {
421 this._encStats
[this._encodings
[i
][1]][0] = 0;
424 for (i
= 0; i
< 4; i
++) {
425 this._FBU
.zlibs
[i
] = new Inflator
.Inflate();
429 _print_stats: function () {
430 Util
.Info("Encoding stats for this connection:");
432 for (i
= 0; i
< this._encodings
.length
; i
++) {
433 s
= this._encStats
[this._encodings
[i
][1]];
434 if (s
[0] + s
[1] > 0) {
435 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
439 Util
.Info("Encoding stats since page load:");
440 for (i
= 0; i
< this._encodings
.length
; i
++) {
441 s
= this._encStats
[this._encodings
[i
][1]];
442 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
446 _cleanup: function () {
447 if (!this._view_only
) { this._keyboard
.ungrab(); }
448 if (!this._view_only
) { this._mouse
.ungrab(); }
449 this._display
.defaultCursor();
450 if (Util
.get_logging() !== 'debug') {
451 // Show noVNC logo on load and when disconnected, unless in
453 this._display
.clear();
462 * disconnected - permanent state
464 _updateConnectionState: function (state
) {
465 var oldstate
= this._rfb_connection_state
;
467 if (state
=== oldstate
) {
468 Util
.Debug("Already in state '" + state
+ "', ignoring");
472 // The 'disconnected' state is permanent for each RFB object
473 if (oldstate
=== 'disconnected') {
474 Util
.Error("Tried changing state of a disconnected RFB object");
478 // Ensure proper transitions before doing anything
481 if (oldstate
!== 'connecting') {
482 Util
.Error("Bad transition to connected state, " +
483 "previous connection state: " + oldstate
);
489 if (oldstate
!== 'disconnecting') {
490 Util
.Error("Bad transition to disconnected state, " +
491 "previous connection state: " + oldstate
);
497 if (oldstate
!== '') {
498 Util
.Error("Bad transition to connecting state, " +
499 "previous connection state: " + oldstate
);
504 case 'disconnecting':
505 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
506 Util
.Error("Bad transition to disconnecting state, " +
507 "previous connection state: " + oldstate
);
513 Util
.Error("Unknown connection state: " + state
);
517 // State change actions
519 this._rfb_connection_state
= state
;
520 this._onUpdateState(this, state
, oldstate
);
522 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
525 if (this._disconnTimer
&& state
!== 'disconnecting') {
526 Util
.Debug("Clearing disconnect timer");
527 clearTimeout(this._disconnTimer
);
528 this._disconnTimer
= null;
530 // make sure we don't get a double event
531 this._sock
.off('close');
536 // Call onDisconnected callback after onUpdateState since
537 // we don't know if the UI only displays the latest message
538 if (this._rfb_disconnect_reason
!== "") {
539 this._onDisconnected(this, this._rfb_disconnect_reason
);
541 // No reason means clean disconnect
542 this._onDisconnected(this);
550 case 'disconnecting':
553 this._disconnTimer
= setTimeout(function () {
554 this._rfb_disconnect_reason
= _("Disconnect timeout");
555 this._updateConnectionState('disconnected');
556 }.bind(this), this._disconnectTimeout
* 1000);
561 /* Print errors and disconnect
563 * The optional parameter 'details' is used for information that
564 * should be logged but not sent to the user interface.
566 _fail: function (msg
, details
) {
568 if (typeof details
!== 'undefined') {
569 fullmsg
= msg
+ " (" + details
+ ")";
571 switch (this._rfb_connection_state
) {
572 case 'disconnecting':
573 Util
.Error("Failed when disconnecting: " + fullmsg
);
576 Util
.Error("Failed while connected: " + fullmsg
);
579 Util
.Error("Failed when connecting: " + fullmsg
);
582 Util
.Error("RFB failure: " + fullmsg
);
585 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
587 // Transition to disconnected without waiting for socket to close
588 this._updateConnectionState('disconnecting');
589 this._updateConnectionState('disconnected');
595 * Send a notification to the UI. Valid levels are:
596 * 'normal'|'warn'|'error'
598 * NOTE: Options could be added in the future.
599 * NOTE: If this function is called multiple times, remember that the
600 * interface could be only showing the latest notification.
602 _notification: function(msg
, level
, options
) {
607 Util
.Debug("Notification[" + level
+ "]:" + msg
);
610 Util
.Error("Invalid notification level: " + level
);
615 this._onNotification(this, msg
, level
, options
);
617 this._onNotification(this, msg
, level
);
621 _handle_message: function () {
622 if (this._sock
.rQlen() === 0) {
623 Util
.Warn("handle_message called on an empty receive queue");
627 switch (this._rfb_connection_state
) {
629 Util
.Error("Got data while disconnected");
633 if (this._flushing
) {
636 if (!this._normal_msg()) {
639 if (this._sock
.rQlen() === 0) {
650 _handleKeyPress: function (keyevent
) {
651 if (this._view_only
) { return; } // View only, skip keyboard, events
653 var down
= (keyevent
.type
== 'keydown');
654 if (this._qemuExtKeyEventSupported
) {
655 var scancode
= XtScancode
[keyevent
.code
];
657 var keysym
= keyevent
.keysym
;
658 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
660 Util
.Error('Unable to find a xt scancode for code = ' + keyevent
.code
);
663 keysym
= keyevent
.keysym
.keysym
;
664 RFB
.messages
.keyEvent(this._sock
, keysym
, down
);
668 _handleMouseButton: function (x
, y
, down
, bmask
) {
670 this._mouse_buttonMask
|= bmask
;
672 this._mouse_buttonMask
^= bmask
;
675 if (this._viewportDrag
) {
676 if (down
&& !this._viewportDragging
) {
677 this._viewportDragging
= true;
678 this._viewportDragPos
= {'x': x
, 'y': y
};
680 // Skip sending mouse events
683 this._viewportDragging
= false;
685 // If the viewport didn't actually move, then treat as a mouse click event
686 // Send the button down event here, as the button up event is sent at the end of this function
687 if (!this._viewportHasMoved
&& !this._view_only
) {
688 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
690 this._viewportHasMoved
= false;
694 if (this._view_only
) { return; } // View only, skip mouse events
696 if (this._rfb_connection_state
!== 'connected') { return; }
697 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
700 _handleMouseMove: function (x
, y
) {
701 if (this._viewportDragging
) {
702 var deltaX
= this._viewportDragPos
.x
- x
;
703 var deltaY
= this._viewportDragPos
.y
- y
;
705 // The goal is to trigger on a certain physical width, the
706 // devicePixelRatio brings us a bit closer but is not optimal.
707 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
709 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
710 Math
.abs(deltaY
) > dragThreshold
)) {
711 this._viewportHasMoved
= true;
713 this._viewportDragPos
= {'x': x
, 'y': y
};
714 this._display
.viewportChangePos(deltaX
, deltaY
);
717 // Skip sending mouse events
721 if (this._view_only
) { return; } // View only, skip mouse events
723 if (this._rfb_connection_state
!== 'connected') { return; }
724 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
729 _negotiate_protocol_version: function () {
730 if (this._sock
.rQlen() < 12) {
731 return this._fail("Error while negotiating with server",
732 "Incomplete protocol version");
735 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
736 Util
.Info("Server ProtocolVersion: " + sversion
);
739 case "000.000": // UltraVNC repeater
743 case "003.006": // UltraVNC
744 case "003.889": // Apple Remote Desktop
745 this._rfb_version
= 3.3;
748 this._rfb_version
= 3.7;
751 case "004.000": // Intel AMT KVM
752 case "004.001": // RealVNC 4.6
753 case "005.000": // RealVNC 5.3
754 this._rfb_version
= 3.8;
757 return this._fail("Unsupported server",
758 "Invalid server version: " + sversion
);
762 var repeaterID
= this._repeaterID
;
763 while (repeaterID
.length
< 250) {
766 this._sock
.send_string(repeaterID
);
770 if (this._rfb_version
> this._rfb_max_version
) {
771 this._rfb_version
= this._rfb_max_version
;
774 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
775 ".00" + ((this._rfb_version
* 10) % 10);
776 this._sock
.send_string("RFB " + cversion
+ "\n");
777 Util
.Debug('Sent ProtocolVersion: ' + cversion
);
779 this._rfb_init_state
= 'Security';
782 _negotiate_security: function () {
783 if (this._rfb_version
>= 3.7) {
784 // Server sends supported list, client decides
785 var num_types
= this._sock
.rQshift8();
786 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
788 if (num_types
=== 0) {
789 var strlen
= this._sock
.rQshift32();
790 var reason
= this._sock
.rQshiftStr(strlen
);
791 return this._fail("Error while negotiating with server",
792 "Security failure: " + reason
);
795 var types
= this._sock
.rQshiftBytes(num_types
);
796 Util
.Debug("Server security types: " + types
);
798 // Polyfill since IE and PhantomJS doesn't have
799 // TypedArray.includes()
800 function includes(item
, array
) {
801 for (var i
= 0; i
< array
.length
; i
++) {
802 if (array
[i
] === item
) {
809 // Look for each auth in preferred order
810 this._rfb_auth_scheme
= 0;
811 if (includes(1, types
)) {
812 this._rfb_auth_scheme
= 1; // None
813 } else if (includes(22, types
)) {
814 this._rfb_auth_scheme
= 22; // XVP
815 } else if (includes(16, types
)) {
816 this._rfb_auth_scheme
= 16; // Tight
817 } else if (includes(2, types
)) {
818 this._rfb_auth_scheme
= 2; // VNC Auth
820 return this._fail("Unsupported server",
821 "Unsupported security types: " + types
);
824 this._sock
.send([this._rfb_auth_scheme
]);
827 if (this._sock
.rQwait("security scheme", 4)) { return false; }
828 this._rfb_auth_scheme
= this._sock
.rQshift32();
831 this._rfb_init_state
= 'Authentication';
832 Util
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
834 return this._init_msg(); // jump to authentication
838 _negotiate_xvp_auth: function () {
839 var xvp_sep
= this._xvp_password_sep
;
840 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
841 if (xvp_auth
.length
< 3) {
842 var msg
= 'XVP credentials required (user' + xvp_sep
+
843 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
844 this._onPasswordRequired(this, msg
);
848 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
849 String
.fromCharCode(xvp_auth
[1].length
) +
852 this._sock
.send_string(xvp_auth_str
);
853 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
854 this._rfb_auth_scheme
= 2;
855 return this._negotiate_authentication();
858 _negotiate_std_vnc_auth: function () {
859 if (this._rfb_password
.length
=== 0) {
860 this._onPasswordRequired(this);
864 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
866 // TODO(directxman12): make genDES not require an Array
867 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
868 var response
= RFB
.genDES(this._rfb_password
, challenge
);
869 this._sock
.send(response
);
870 this._rfb_init_state
= "SecurityResult";
874 _negotiate_tight_tunnels: function (numTunnels
) {
875 var clientSupportedTunnelTypes
= {
876 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
878 var serverSupportedTunnelTypes
= {};
879 // receive tunnel capabilities
880 for (var i
= 0; i
< numTunnels
; i
++) {
881 var cap_code
= this._sock
.rQshift32();
882 var cap_vendor
= this._sock
.rQshiftStr(4);
883 var cap_signature
= this._sock
.rQshiftStr(8);
884 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
887 // choose the notunnel type
888 if (serverSupportedTunnelTypes
[0]) {
889 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
890 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
891 return this._fail("Unsupported server",
892 "Client's tunnel type had the incorrect " +
893 "vendor or signature");
895 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
896 return false; // wait until we receive the sub auth count to continue
898 return this._fail("Unsupported server",
899 "Server wanted tunnels, but doesn't support " +
900 "the notunnel type");
904 _negotiate_tight_auth: function () {
905 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
906 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
907 var numTunnels
= this._sock
.rQshift32();
908 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
910 this._rfb_tightvnc
= true;
912 if (numTunnels
> 0) {
913 this._negotiate_tight_tunnels(numTunnels
);
914 return false; // wait until we receive the sub auth to continue
918 // second pass, do the sub-auth negotiation
919 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
920 var subAuthCount
= this._sock
.rQshift32();
921 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
922 this._rfb_init_state
= 'SecurityResult';
926 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
928 var clientSupportedTypes
= {
933 var serverSupportedTypes
= [];
935 for (var i
= 0; i
< subAuthCount
; i
++) {
936 var capNum
= this._sock
.rQshift32();
937 var capabilities
= this._sock
.rQshiftStr(12);
938 serverSupportedTypes
.push(capabilities
);
941 for (var authType
in clientSupportedTypes
) {
942 if (serverSupportedTypes
.indexOf(authType
) != -1) {
943 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
946 case 'STDVNOAUTH__': // no auth
947 this._rfb_init_state
= 'SecurityResult';
949 case 'STDVVNCAUTH_': // VNC auth
950 this._rfb_auth_scheme
= 2;
951 return this._init_msg();
953 return this._fail("Unsupported server",
954 "Unsupported tiny auth scheme: " +
960 return this._fail("Unsupported server",
961 "No supported sub-auth types!");
964 _negotiate_authentication: function () {
965 switch (this._rfb_auth_scheme
) {
966 case 0: // connection failed
967 if (this._sock
.rQwait("auth reason", 4)) { return false; }
968 var strlen
= this._sock
.rQshift32();
969 var reason
= this._sock
.rQshiftStr(strlen
);
970 return this._fail("Authentication failure", reason
);
973 if (this._rfb_version
>= 3.8) {
974 this._rfb_init_state
= 'SecurityResult';
977 this._rfb_init_state
= 'ClientInitialisation';
978 return this._init_msg();
981 return this._negotiate_xvp_auth();
983 case 2: // VNC authentication
984 return this._negotiate_std_vnc_auth();
986 case 16: // TightVNC Security Type
987 return this._negotiate_tight_auth();
990 return this._fail("Unsupported server",
991 "Unsupported auth scheme: " +
992 this._rfb_auth_scheme
);
996 _handle_security_result: function () {
997 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
998 switch (this._sock
.rQshift32()) {
1000 this._rfb_init_state
= 'ClientInitialisation';
1001 Util
.Debug('Authentication OK');
1002 return this._init_msg();
1004 if (this._rfb_version
>= 3.8) {
1005 var length
= this._sock
.rQshift32();
1006 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
1007 var reason
= this._sock
.rQshiftStr(length
);
1008 return this._fail("Authentication failure", reason
);
1010 return this._fail("Authentication failure");
1014 return this._fail("Too many authentication attempts");
1016 return this._fail("Unsupported server",
1017 "Unknown SecurityResult");
1021 _negotiate_server_init: function () {
1022 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1025 this._fb_width
= this._sock
.rQshift16();
1026 this._fb_height
= this._sock
.rQshift16();
1027 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1030 var bpp
= this._sock
.rQshift8();
1031 var depth
= this._sock
.rQshift8();
1032 var big_endian
= this._sock
.rQshift8();
1033 var true_color
= this._sock
.rQshift8();
1035 var red_max
= this._sock
.rQshift16();
1036 var green_max
= this._sock
.rQshift16();
1037 var blue_max
= this._sock
.rQshift16();
1038 var red_shift
= this._sock
.rQshift8();
1039 var green_shift
= this._sock
.rQshift8();
1040 var blue_shift
= this._sock
.rQshift8();
1041 this._sock
.rQskipBytes(3); // padding
1043 // NB(directxman12): we don't want to call any callbacks or print messages until
1044 // *after* we're past the point where we could backtrack
1046 /* Connection name/title */
1047 var name_length = this._sock.rQshift32();
1048 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1049 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
1051 if (this._rfb_tightvnc) {
1052 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1053 // In TightVNC mode, ServerInit message is extended
1054 var numServerMessages = this._sock.rQshift16();
1055 var numClientMessages = this._sock.rQshift16();
1056 var numEncodings = this._sock.rQshift16();
1057 this._sock.rQskipBytes(2); // padding
1059 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1060 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1062 // we don't actually do anything with the capability information that TIGHT sends,
1063 // so we just skip the all of this.
1065 // TIGHT server message capabilities
1066 this._sock.rQskipBytes(16 * numServerMessages);
1068 // TIGHT client message capabilities
1069 this._sock.rQskipBytes(16 * numClientMessages);
1071 // TIGHT encoding capabilities
1072 this._sock.rQskipBytes(16 * numEncodings);
1075 // NB(directxman12): these are down here so that we don't run them multiple times
1077 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1078 ", bpp: " + bpp + ", depth: " + depth +
1079 ", big_endian: " + big_endian +
1080 ", true_color: " + true_color +
1081 ", red_max: " + red_max +
1082 ", green_max: " + green_max +
1083 ", blue_max: " + blue_max +
1084 ", red_shift: " + red_shift +
1085 ", green_shift: " + green_shift +
1086 ", blue_shift: " + blue_shift);
1088 if (big_endian !== 0) {
1089 Util.Warn("Server native endian is not little endian");
1092 if (red_shift !== 16) {
1093 Util.Warn("Server native red-shift is not 16");
1096 if (blue_shift !== 0) {
1097 Util.Warn("Server native blue-shift is not 0");
1100 // we're past the point where we could backtrack, so it's safe to call this
1101 this._onDesktopName(this, this._fb_name);
1103 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1104 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1105 this._true_color = false;
1108 this._display.set_true_color(this._true_color);
1109 this._display.resize(this._fb_width, this._fb_height);
1110 this._onFBResize(this, this._fb_width, this._fb_height);
1112 if (!this._view_only) { this._keyboard.grab(); }
1113 if (!this._view_only) { this._mouse.grab(); }
1115 if (this._true_color) {
1123 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1124 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1125 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1127 this._timing.fbu_rt_start = (new Date()).getTime();
1128 this._timing.pixels = 0;
1130 this._updateConnectionState('connected');
1134 /* RFB protocol initialization states:
1139 * ClientInitialization - not triggered by server message
1140 * ServerInitialization
1142 _init_msg: function () {
1143 switch (this._rfb_init_state
) {
1144 case 'ProtocolVersion':
1145 return this._negotiate_protocol_version();
1148 return this._negotiate_security();
1150 case 'Authentication':
1151 return this._negotiate_authentication();
1153 case 'SecurityResult':
1154 return this._handle_security_result();
1156 case 'ClientInitialisation':
1157 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1158 this._rfb_init_state
= 'ServerInitialisation';
1161 case 'ServerInitialisation':
1162 return this._negotiate_server_init();
1165 return this._fail("Internal error", "Unknown init state: " +
1166 this._rfb_init_state
);
1170 _handle_set_colour_map_msg: function () {
1171 Util
.Debug("SetColorMapEntries");
1172 this._sock
.rQskip8(); // Padding
1174 var first_colour
= this._sock
.rQshift16();
1175 var num_colours
= this._sock
.rQshift16();
1176 if (this._sock
.rQwait('SetColorMapEntries', num_colours
* 6, 6)) { return false; }
1178 for (var c
= 0; c
< num_colours
; c
++) {
1179 var red
= parseInt(this._sock
.rQshift16() / 256, 10);
1180 var green
= parseInt(this._sock
.rQshift16() / 256, 10);
1181 var blue
= parseInt(this._sock
.rQshift16() / 256, 10);
1182 this._display
.set_colourMap([blue
, green
, red
], first_colour
+ c
);
1184 Util
.Debug("colourMap: " + this._display
.get_colourMap());
1185 Util
.Info("Registered " + num_colours
+ " colourMap entries");
1190 _handle_server_cut_text: function () {
1191 Util
.Debug("ServerCutText");
1192 if (this._view_only
) { return true; }
1194 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1195 this._sock
.rQskipBytes(3); // Padding
1196 var length
= this._sock
.rQshift32();
1197 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1199 var text
= this._sock
.rQshiftStr(length
);
1200 this._onClipboard(this, text
);
1205 _handle_server_fence_msg: function() {
1206 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1207 this._sock
.rQskipBytes(3); // Padding
1208 var flags
= this._sock
.rQshift32();
1209 var length
= this._sock
.rQshift8();
1211 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1214 Util
.Warn("Bad payload length (" + length
+ ") in fence response");
1218 var payload
= this._sock
.rQshiftStr(length
);
1220 this._supportsFence
= true;
1225 * (1<<0) - BlockBefore
1226 * (1<<1) - BlockAfter
1231 if (!(flags
& (1<<31))) {
1232 return this._fail("Internal error",
1233 "Unexpected fence response");
1236 // Filter out unsupported flags
1237 // FIXME: support syncNext
1238 flags
&= (1<<0) | (1<<1);
1240 // BlockBefore and BlockAfter are automatically handled by
1241 // the fact that we process each incoming message
1243 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1248 _handle_xvp_msg: function () {
1249 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1250 this._sock
.rQskip8(); // Padding
1251 var xvp_ver
= this._sock
.rQshift8();
1252 var xvp_msg
= this._sock
.rQshift8();
1256 Util
.Error("Operation Failed");
1257 this._notification("XVP Operation Failed", 'error');
1260 this._rfb_xvp_ver
= xvp_ver
;
1261 Util
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1262 this._onXvpInit(this._rfb_xvp_ver
);
1265 this._fail("Unexpected server message",
1266 "Illegal server XVP message " + xvp_msg
);
1273 _normal_msg: function () {
1276 if (this._FBU
.rects
> 0) {
1279 msg_type
= this._sock
.rQshift8();
1283 case 0: // FramebufferUpdate
1284 var ret
= this._framebufferUpdate();
1285 if (ret
&& !this._enabledContinuousUpdates
) {
1286 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1287 this._fb_width
, this._fb_height
);
1291 case 1: // SetColorMapEntries
1292 return this._handle_set_colour_map_msg();
1299 case 3: // ServerCutText
1300 return this._handle_server_cut_text();
1302 case 150: // EndOfContinuousUpdates
1303 var first
= !(this._supportsContinuousUpdates
);
1304 this._supportsContinuousUpdates
= true;
1305 this._enabledContinuousUpdates
= false;
1307 this._enabledContinuousUpdates
= true;
1308 this._updateContinuousUpdates();
1309 Util
.Info("Enabling continuous updates.");
1311 // FIXME: We need to send a framebufferupdaterequest here
1312 // if we add support for turning off continuous updates
1316 case 248: // ServerFence
1317 return this._handle_server_fence_msg();
1320 return this._handle_xvp_msg();
1323 this._fail("Unexpected server message", "Type:" + msg_type
);
1324 Util
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1329 _onFlush: function() {
1330 this._flushing
= false;
1331 // Resume processing
1332 if (this._sock
.rQlen() > 0) {
1333 this._handle_message();
1337 _framebufferUpdate: function () {
1341 if (this._FBU
.rects
=== 0) {
1342 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1343 this._sock
.rQskip8(); // Padding
1344 this._FBU
.rects
= this._sock
.rQshift16();
1345 this._FBU
.bytes
= 0;
1346 this._timing
.cur_fbu
= 0;
1347 if (this._timing
.fbu_rt_start
> 0) {
1348 now
= (new Date()).getTime();
1349 Util
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1352 // Make sure the previous frame is fully rendered first
1353 // to avoid building up an excessive queue
1354 if (this._display
.pending()) {
1355 this._flushing
= true;
1356 this._display
.flush();
1361 while (this._FBU
.rects
> 0) {
1362 if (this._rfb_connection_state
!== 'connected') { return false; }
1364 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1365 if (this._FBU
.bytes
=== 0) {
1366 if (this._sock
.rQwait("rect header", 12)) { return false; }
1367 /* New FramebufferUpdate */
1369 var hdr
= this._sock
.rQshiftBytes(12);
1370 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1371 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1372 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1373 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1374 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1375 (hdr
[10] << 8) + hdr
[11], 10);
1377 this._onFBUReceive(this,
1378 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1379 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1380 'encoding': this._FBU
.encoding
,
1381 'encodingName': this._encNames
[this._FBU
.encoding
]});
1383 if (!this._encNames
[this._FBU
.encoding
]) {
1384 this._fail("Unexpected server message",
1385 "Unsupported encoding " +
1386 this._FBU
.encoding
);
1391 this._timing
.last_fbu
= (new Date()).getTime();
1393 ret
= this._encHandlers
[this._FBU
.encoding
]();
1395 now
= (new Date()).getTime();
1396 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1399 this._encStats
[this._FBU
.encoding
][0]++;
1400 this._encStats
[this._FBU
.encoding
][1]++;
1401 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1404 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1405 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1406 this._timing
.fbu_rt_start
> 0) {
1407 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1408 this._timing
.full_fbu_cnt
++;
1409 Util
.Info("Timing of full FBU, curr: " +
1410 this._timing
.cur_fbu
+ ", total: " +
1411 this._timing
.full_fbu_total
+ ", cnt: " +
1412 this._timing
.full_fbu_cnt
+ ", avg: " +
1413 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1416 if (this._timing
.fbu_rt_start
> 0) {
1417 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1418 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1419 this._timing
.fbu_rt_cnt
++;
1420 Util
.Info("full FBU round-trip, cur: " +
1421 fbu_rt_diff
+ ", total: " +
1422 this._timing
.fbu_rt_total
+ ", cnt: " +
1423 this._timing
.fbu_rt_cnt
+ ", avg: " +
1424 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1425 this._timing
.fbu_rt_start
= 0;
1429 if (!ret
) { return ret
; } // need more data
1432 this._display
.flip();
1434 this._onFBUComplete(this,
1435 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1436 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1437 'encoding': this._FBU
.encoding
,
1438 'encodingName': this._encNames
[this._FBU
.encoding
]});
1440 return true; // We finished this FBU
1443 _updateContinuousUpdates: function() {
1444 if (!this._enabledContinuousUpdates
) { return; }
1446 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1447 this._fb_width
, this._fb_height
);
1451 Util
.make_properties(RFB
, [
1452 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1453 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1454 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1455 ['true_color', 'rw', 'bool'], // Request true color pixel data
1456 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1457 ['shared', 'rw', 'bool'], // Request shared mode
1458 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1459 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1460 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1461 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1462 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1463 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1465 // Callback functions
1466 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1467 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1468 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1469 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1470 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1471 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1472 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1473 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1474 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1475 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1476 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1479 RFB
.prototype.set_local_cursor = function (cursor
) {
1480 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1481 this._local_cursor
= false;
1482 this._display
.disableLocalCursor(); //Only show server-side cursor
1484 if (this._display
.get_cursor_uri()) {
1485 this._local_cursor
= true;
1487 Util
.Warn("Browser does not support local cursor");
1488 this._display
.disableLocalCursor();
1492 // Need to send an updated list of encodings if we are connected
1493 if (this._rfb_connection_state
=== "connected") {
1494 RFB
.messages
.clientEncodings(this._sock
, this._encodings
, cursor
,
1499 RFB
.prototype.set_view_only = function (view_only
) {
1500 this._view_only
= view_only
;
1502 if (this._rfb_connection_state
=== "connecting" ||
1503 this._rfb_connection_state
=== "connected") {
1505 this._keyboard
.ungrab();
1506 this._mouse
.ungrab();
1508 this._keyboard
.grab();
1514 RFB
.prototype.get_display = function () { return this._display
; };
1515 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1516 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1520 keyEvent: function (sock
, keysym
, down
) {
1521 var buff
= sock
._sQ
;
1522 var offset
= sock
._sQlen
;
1524 buff
[offset
] = 4; // msg-type
1525 buff
[offset
+ 1] = down
;
1527 buff
[offset
+ 2] = 0;
1528 buff
[offset
+ 3] = 0;
1530 buff
[offset
+ 4] = (keysym
>> 24);
1531 buff
[offset
+ 5] = (keysym
>> 16);
1532 buff
[offset
+ 6] = (keysym
>> 8);
1533 buff
[offset
+ 7] = keysym
;
1539 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1540 function getRFBkeycode(xt_scancode
) {
1541 var upperByte
= (keycode
>> 8);
1542 var lowerByte
= (keycode
& 0x00ff);
1543 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1544 lowerByte
= lowerByte
| 0x80;
1550 var buff
= sock
._sQ
;
1551 var offset
= sock
._sQlen
;
1553 buff
[offset
] = 255; // msg-type
1554 buff
[offset
+ 1] = 0; // sub msg-type
1556 buff
[offset
+ 2] = (down
>> 8);
1557 buff
[offset
+ 3] = down
;
1559 buff
[offset
+ 4] = (keysym
>> 24);
1560 buff
[offset
+ 5] = (keysym
>> 16);
1561 buff
[offset
+ 6] = (keysym
>> 8);
1562 buff
[offset
+ 7] = keysym
;
1564 var RFBkeycode
= getRFBkeycode(keycode
);
1566 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1567 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1568 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1569 buff
[offset
+ 11] = RFBkeycode
;
1575 pointerEvent: function (sock
, x
, y
, mask
) {
1576 var buff
= sock
._sQ
;
1577 var offset
= sock
._sQlen
;
1579 buff
[offset
] = 5; // msg-type
1581 buff
[offset
+ 1] = mask
;
1583 buff
[offset
+ 2] = x
>> 8;
1584 buff
[offset
+ 3] = x
;
1586 buff
[offset
+ 4] = y
>> 8;
1587 buff
[offset
+ 5] = y
;
1593 // TODO(directxman12): make this unicode compatible?
1594 clientCutText: function (sock
, text
) {
1595 var buff
= sock
._sQ
;
1596 var offset
= sock
._sQlen
;
1598 buff
[offset
] = 6; // msg-type
1600 buff
[offset
+ 1] = 0; // padding
1601 buff
[offset
+ 2] = 0; // padding
1602 buff
[offset
+ 3] = 0; // padding
1604 var n
= text
.length
;
1606 buff
[offset
+ 4] = n
>> 24;
1607 buff
[offset
+ 5] = n
>> 16;
1608 buff
[offset
+ 6] = n
>> 8;
1609 buff
[offset
+ 7] = n
;
1611 for (var i
= 0; i
< n
; i
++) {
1612 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1615 sock
._sQlen
+= 8 + n
;
1619 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1620 var buff
= sock
._sQ
;
1621 var offset
= sock
._sQlen
;
1623 buff
[offset
] = 251; // msg-type
1624 buff
[offset
+ 1] = 0; // padding
1625 buff
[offset
+ 2] = width
>> 8; // width
1626 buff
[offset
+ 3] = width
;
1627 buff
[offset
+ 4] = height
>> 8; // height
1628 buff
[offset
+ 5] = height
;
1630 buff
[offset
+ 6] = 1; // number-of-screens
1631 buff
[offset
+ 7] = 0; // padding
1634 buff
[offset
+ 8] = id
>> 24; // id
1635 buff
[offset
+ 9] = id
>> 16;
1636 buff
[offset
+ 10] = id
>> 8;
1637 buff
[offset
+ 11] = id
;
1638 buff
[offset
+ 12] = 0; // x-position
1639 buff
[offset
+ 13] = 0;
1640 buff
[offset
+ 14] = 0; // y-position
1641 buff
[offset
+ 15] = 0;
1642 buff
[offset
+ 16] = width
>> 8; // width
1643 buff
[offset
+ 17] = width
;
1644 buff
[offset
+ 18] = height
>> 8; // height
1645 buff
[offset
+ 19] = height
;
1646 buff
[offset
+ 20] = flags
>> 24; // flags
1647 buff
[offset
+ 21] = flags
>> 16;
1648 buff
[offset
+ 22] = flags
>> 8;
1649 buff
[offset
+ 23] = flags
;
1655 clientFence: function (sock
, flags
, payload
) {
1656 var buff
= sock
._sQ
;
1657 var offset
= sock
._sQlen
;
1659 buff
[offset
] = 248; // msg-type
1661 buff
[offset
+ 1] = 0; // padding
1662 buff
[offset
+ 2] = 0; // padding
1663 buff
[offset
+ 3] = 0; // padding
1665 buff
[offset
+ 4] = flags
>> 24; // flags
1666 buff
[offset
+ 5] = flags
>> 16;
1667 buff
[offset
+ 6] = flags
>> 8;
1668 buff
[offset
+ 7] = flags
;
1670 var n
= payload
.length
;
1672 buff
[offset
+ 8] = n
; // length
1674 for (var i
= 0; i
< n
; i
++) {
1675 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1678 sock
._sQlen
+= 9 + n
;
1682 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1683 var buff
= sock
._sQ
;
1684 var offset
= sock
._sQlen
;
1686 buff
[offset
] = 150; // msg-type
1687 buff
[offset
+ 1] = enable
; // enable-flag
1689 buff
[offset
+ 2] = x
>> 8; // x
1690 buff
[offset
+ 3] = x
;
1691 buff
[offset
+ 4] = y
>> 8; // y
1692 buff
[offset
+ 5] = y
;
1693 buff
[offset
+ 6] = width
>> 8; // width
1694 buff
[offset
+ 7] = width
;
1695 buff
[offset
+ 8] = height
>> 8; // height
1696 buff
[offset
+ 9] = height
;
1702 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1703 var buff
= sock
._sQ
;
1704 var offset
= sock
._sQlen
;
1706 buff
[offset
] = 0; // msg-type
1708 buff
[offset
+ 1] = 0; // padding
1709 buff
[offset
+ 2] = 0; // padding
1710 buff
[offset
+ 3] = 0; // padding
1712 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1713 buff
[offset
+ 5] = depth
* 8; // depth
1714 buff
[offset
+ 6] = 0; // little-endian
1715 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1717 buff
[offset
+ 8] = 0; // red-max
1718 buff
[offset
+ 9] = 255; // red-max
1720 buff
[offset
+ 10] = 0; // green-max
1721 buff
[offset
+ 11] = 255; // green-max
1723 buff
[offset
+ 12] = 0; // blue-max
1724 buff
[offset
+ 13] = 255; // blue-max
1726 buff
[offset
+ 14] = 16; // red-shift
1727 buff
[offset
+ 15] = 8; // green-shift
1728 buff
[offset
+ 16] = 0; // blue-shift
1730 buff
[offset
+ 17] = 0; // padding
1731 buff
[offset
+ 18] = 0; // padding
1732 buff
[offset
+ 19] = 0; // padding
1738 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1739 var buff
= sock
._sQ
;
1740 var offset
= sock
._sQlen
;
1742 buff
[offset
] = 2; // msg-type
1743 buff
[offset
+ 1] = 0; // padding
1745 // offset + 2 and offset + 3 are encoding count
1747 var i
, j
= offset
+ 4, cnt
= 0;
1748 for (i
= 0; i
< encodings
.length
; i
++) {
1749 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1750 Util
.Debug("Skipping Cursor pseudo-encoding");
1751 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1752 // TODO: remove this when we have tight+non-true-color
1753 Util
.Warn("Skipping tight as it is only supported with true color");
1755 var enc
= encodings
[i
][1];
1756 buff
[j
] = enc
>> 24;
1757 buff
[j
+ 1] = enc
>> 16;
1758 buff
[j
+ 2] = enc
>> 8;
1766 buff
[offset
+ 2] = cnt
>> 8;
1767 buff
[offset
+ 3] = cnt
;
1769 sock
._sQlen
+= j
- offset
;
1773 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1774 var buff
= sock
._sQ
;
1775 var offset
= sock
._sQlen
;
1777 if (typeof(x
) === "undefined") { x
= 0; }
1778 if (typeof(y
) === "undefined") { y
= 0; }
1780 buff
[offset
] = 3; // msg-type
1781 buff
[offset
+ 1] = incremental
? 1 : 0;
1783 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1784 buff
[offset
+ 3] = x
& 0xFF;
1786 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1787 buff
[offset
+ 5] = y
& 0xFF;
1789 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1790 buff
[offset
+ 7] = w
& 0xFF;
1792 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1793 buff
[offset
+ 9] = h
& 0xFF;
1800 RFB
.genDES = function (password
, challenge
) {
1802 for (var i
= 0; i
< password
.length
; i
++) {
1803 passwd
.push(password
.charCodeAt(i
));
1805 return (new DES(passwd
)).encrypt(challenge
);
1808 RFB
.encodingHandlers
= {
1810 if (this._FBU
.lines
=== 0) {
1811 this._FBU
.lines
= this._FBU
.height
;
1814 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1815 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1816 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1817 var curr_height
= Math
.min(this._FBU
.lines
,
1818 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1819 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1820 curr_height
, this._sock
.get_rQ(),
1821 this._sock
.get_rQi());
1822 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1823 this._FBU
.lines
-= curr_height
;
1825 if (this._FBU
.lines
> 0) {
1826 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1829 this._FBU
.bytes
= 0;
1835 COPYRECT: function () {
1836 this._FBU
.bytes
= 4;
1837 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1838 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1839 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1843 this._FBU
.bytes
= 0;
1849 if (this._FBU
.subrects
=== 0) {
1850 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1851 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1852 this._FBU
.subrects
= this._sock
.rQshift32();
1853 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1854 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1857 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1858 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1859 var x
= this._sock
.rQshift16();
1860 var y
= this._sock
.rQshift16();
1861 var width
= this._sock
.rQshift16();
1862 var height
= this._sock
.rQshift16();
1863 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1864 this._FBU
.subrects
--;
1867 if (this._FBU
.subrects
> 0) {
1868 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1869 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1872 this._FBU
.bytes
= 0;
1878 HEXTILE: function () {
1879 var rQ
= this._sock
.get_rQ();
1880 var rQi
= this._sock
.get_rQi();
1882 if (this._FBU
.tiles
=== 0) {
1883 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1884 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1885 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1886 this._FBU
.tiles
= this._FBU
.total_tiles
;
1889 while (this._FBU
.tiles
> 0) {
1890 this._FBU
.bytes
= 1;
1891 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1892 var subencoding
= rQ
[rQi
]; // Peek
1893 if (subencoding
> 30) { // Raw
1894 this._fail("Unexpected server message",
1895 "Illegal hextile subencoding: " + subencoding
);
1900 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1901 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1902 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1903 var x
= this._FBU
.x
+ tile_x
* 16;
1904 var y
= this._FBU
.y
+ tile_y
* 16;
1905 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1906 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1908 // Figure out how much we are expecting
1909 if (subencoding
& 0x01) { // Raw
1910 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1912 if (subencoding
& 0x02) { // Background
1913 this._FBU
.bytes
+= this._fb_Bpp
;
1915 if (subencoding
& 0x04) { // Foreground
1916 this._FBU
.bytes
+= this._fb_Bpp
;
1918 if (subencoding
& 0x08) { // AnySubrects
1919 this._FBU
.bytes
++; // Since we aren't shifting it off
1920 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1921 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1922 if (subencoding
& 0x10) { // SubrectsColoured
1923 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1925 this._FBU
.bytes
+= subrects
* 2;
1930 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1932 // We know the encoding and have a whole tile
1933 this._FBU
.subencoding
= rQ
[rQi
];
1935 if (this._FBU
.subencoding
=== 0) {
1936 if (this._FBU
.lastsubencoding
& 0x01) {
1937 // Weird: ignore blanks are RAW
1938 Util
.Debug(" Ignoring blank after RAW");
1940 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1942 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1943 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1944 rQi
+= this._FBU
.bytes
- 1;
1946 if (this._FBU
.subencoding
& 0x02) { // Background
1947 if (this._fb_Bpp
== 1) {
1948 this._FBU
.background
= rQ
[rQi
];
1951 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1953 rQi
+= this._fb_Bpp
;
1955 if (this._FBU
.subencoding
& 0x04) { // Foreground
1956 if (this._fb_Bpp
== 1) {
1957 this._FBU
.foreground
= rQ
[rQi
];
1959 // this._fb_Bpp is 4
1960 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1962 rQi
+= this._fb_Bpp
;
1965 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1966 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1970 for (var s
= 0; s
< subrects
; s
++) {
1972 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1973 if (this._fb_Bpp
=== 1) {
1977 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1979 rQi
+= this._fb_Bpp
;
1981 color
= this._FBU
.foreground
;
1986 var sy
= (xy
& 0x0f);
1990 var sw
= (wh
>> 4) + 1;
1991 var sh
= (wh
& 0x0f) + 1;
1993 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1996 this._display
.finishTile();
1998 this._sock
.set_rQi(rQi
);
1999 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2000 this._FBU
.bytes
= 0;
2004 if (this._FBU
.tiles
=== 0) {
2011 getTightCLength: function (arr
) {
2012 var header
= 1, data
= 0;
2013 data
+= arr
[0] & 0x7f;
2014 if (arr
[0] & 0x80) {
2016 data
+= (arr
[1] & 0x7f) << 7;
2017 if (arr
[1] & 0x80) {
2019 data
+= arr
[2] << 14;
2022 return [header
, data
];
2025 display_tight: function (isTightPNG
) {
2026 if (this._fb_depth
=== 1) {
2027 this._fail("Internal error",
2028 "Tight protocol handler only implements " +
2032 this._FBU
.bytes
= 1; // compression-control byte
2033 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2035 var checksum = function (data
) {
2037 for (var i
= 0; i
< data
.length
; i
++) {
2039 if (sum
> 65536) sum
-= 65536;
2044 var resetStreams
= 0;
2046 var decompress = function (data
, expected
) {
2047 for (var i
= 0; i
< 4; i
++) {
2048 if ((resetStreams
>> i
) & 1) {
2049 this._FBU
.zlibs
[i
].reset();
2050 Util
.Info("Reset zlib stream " + i
);
2054 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2055 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2056 /*if (uncompressed.status !== 0) {
2057 Util.Error("Invalid data in zlib stream");
2060 //return uncompressed.data;
2061 return uncompressed
;
2064 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2065 // Convert indexed (palette based) image data to RGB
2066 // TODO: reduce number of calculations inside loop
2067 var dest
= this._destBuff
;
2068 var w
= Math
.floor((width
+ 7) / 8);
2069 var w1
= Math
.floor(width
/ 8);
2071 /*for (var y = 0; y < height; y++) {
2073 var yoffset = y * width;
2074 var ybitoffset = y * w;
2075 var xoffset, targetbyte;
2076 for (x = 0; x < w1; x++) {
2077 xoffset = yoffset + x * 8;
2078 targetbyte = data[ybitoffset + x];
2079 for (b = 7; b >= 0; b--) {
2080 dp = (xoffset + 7 - b) * 3;
2081 sp = (targetbyte >> b & 1) * 3;
2082 dest[dp] = palette[sp];
2083 dest[dp + 1] = palette[sp + 1];
2084 dest[dp + 2] = palette[sp + 2];
2088 xoffset = yoffset + x * 8;
2089 targetbyte = data[ybitoffset + x];
2090 for (b = 7; b >= 8 - width % 8; b--) {
2091 dp = (xoffset + 7 - b) * 3;
2092 sp = (targetbyte >> b & 1) * 3;
2093 dest[dp] = palette[sp];
2094 dest[dp + 1] = palette[sp + 1];
2095 dest[dp + 2] = palette[sp + 2];
2099 for (var y
= 0; y
< height
; y
++) {
2101 for (x
= 0; x
< w1
; x
++) {
2102 for (b
= 7; b
>= 0; b
--) {
2103 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2104 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2105 dest
[dp
] = palette
[sp
];
2106 dest
[dp
+ 1] = palette
[sp
+ 1];
2107 dest
[dp
+ 2] = palette
[sp
+ 2];
2112 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2113 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2114 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2115 dest
[dp
] = palette
[sp
];
2116 dest
[dp
+ 1] = palette
[sp
+ 1];
2117 dest
[dp
+ 2] = palette
[sp
+ 2];
2125 var indexedToRGBX = function (data
, palette
, width
, height
) {
2126 // Convert indexed (palette based) image data to RGB
2127 var dest
= this._destBuff
;
2128 var total
= width
* height
* 4;
2129 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2130 var sp
= data
[j
] * 3;
2131 dest
[i
] = palette
[sp
];
2132 dest
[i
+ 1] = palette
[sp
+ 1];
2133 dest
[i
+ 2] = palette
[sp
+ 2];
2140 var rQi
= this._sock
.get_rQi();
2141 var rQ
= this._sock
.rQwhole();
2143 var cl_header
, cl_data
;
2145 var handlePalette = function () {
2146 var numColors
= rQ
[rQi
+ 2] + 1;
2147 var paletteSize
= numColors
* this._fb_depth
;
2148 this._FBU
.bytes
+= paletteSize
;
2149 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2151 var bpp
= (numColors
<= 2) ? 1 : 8;
2152 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2154 if (rowSize
* this._FBU
.height
< 12) {
2157 cl_data
= rowSize
* this._FBU
.height
;
2158 //clength = [0, rowSize * this._FBU.height];
2160 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2161 var cl_offset
= rQi
+ 3 + paletteSize
;
2164 cl_data
+= rQ
[cl_offset
] & 0x7f;
2165 if (rQ
[cl_offset
] & 0x80) {
2167 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2168 if (rQ
[cl_offset
+ 1] & 0x80) {
2170 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2173 // end inline getTightCLength
2176 this._FBU
.bytes
+= cl_header
+ cl_data
;
2177 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2179 // Shift ctl, filter id, num colors, palette entries, and clength off
2180 this._sock
.rQskipBytes(3);
2181 //var palette = this._sock.rQshiftBytes(paletteSize);
2182 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2183 this._sock
.rQskipBytes(cl_header
);
2186 data
= this._sock
.rQshiftBytes(cl_data
);
2188 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2191 // Convert indexed (palette based) image data to RGB
2193 if (numColors
== 2) {
2194 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2195 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2197 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2198 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2205 var handleCopy = function () {
2207 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2208 if (uncompressedSize
< 12) {
2211 cl_data
= uncompressedSize
;
2213 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2214 var cl_offset
= rQi
+ 1;
2217 cl_data
+= rQ
[cl_offset
] & 0x7f;
2218 if (rQ
[cl_offset
] & 0x80) {
2220 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2221 if (rQ
[cl_offset
+ 1] & 0x80) {
2223 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2226 // end inline getTightCLength
2228 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2229 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2231 // Shift ctl, clength off
2232 this._sock
.rQshiftBytes(1 + cl_header
);
2235 data
= this._sock
.rQshiftBytes(cl_data
);
2237 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2240 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2245 var ctl
= this._sock
.rQpeek8();
2247 // Keep tight reset bits
2248 resetStreams
= ctl
& 0xF;
2250 // Figure out filter
2252 streamId
= ctl
& 0x3;
2254 if (ctl
=== 0x08) cmode
= "fill";
2255 else if (ctl
=== 0x09) cmode
= "jpeg";
2256 else if (ctl
=== 0x0A) cmode
= "png";
2257 else if (ctl
& 0x04) cmode
= "filter";
2258 else if (ctl
< 0x04) cmode
= "copy";
2259 else return this._fail("Unexpected server message",
2260 "Illegal tight compression received, " +
2263 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2264 return this._fail("Unexpected server message",
2265 "filter/copy received in tightPNG mode");
2269 // fill use fb_depth because TPIXELs drop the padding byte
2270 case "fill": // TPIXEL
2271 this._FBU
.bytes
+= this._fb_depth
;
2273 case "jpeg": // max clength
2274 this._FBU
.bytes
+= 3;
2276 case "png": // max clength
2277 this._FBU
.bytes
+= 3;
2279 case "filter": // filter id + num colors if palette
2280 this._FBU
.bytes
+= 2;
2286 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2288 // Determine FBU.bytes
2292 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);
2293 this._sock
.rQskipBytes(4);
2297 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2298 var cl_offset
= rQi
+ 1;
2301 cl_data
+= rQ
[cl_offset
] & 0x7f;
2302 if (rQ
[cl_offset
] & 0x80) {
2304 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2305 if (rQ
[cl_offset
+ 1] & 0x80) {
2307 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2310 // end inline getTightCLength
2311 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2312 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2314 // We have everything, render it
2315 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2316 data
= this._sock
.rQshiftBytes(cl_data
);
2317 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2320 var filterId
= rQ
[rQi
+ 1];
2321 if (filterId
=== 1) {
2322 if (!handlePalette()) { return false; }
2324 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2325 // Filter 2, Gradient is valid but not use if jpeg is enabled
2326 this._fail("Unexpected server message",
2327 "Unsupported tight subencoding received, " +
2328 "filter: " + filterId
);
2332 if (!handleCopy()) { return false; }
2337 this._FBU
.bytes
= 0;
2343 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2344 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2346 last_rect: function () {
2347 this._FBU
.rects
= 0;
2351 handle_FB_resize: function () {
2352 this._fb_width
= this._FBU
.width
;
2353 this._fb_height
= this._FBU
.height
;
2354 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2355 this._display
.resize(this._fb_width
, this._fb_height
);
2356 this._onFBResize(this, this._fb_width
, this._fb_height
);
2357 this._timing
.fbu_rt_start
= (new Date()).getTime();
2358 this._updateContinuousUpdates();
2360 this._FBU
.bytes
= 0;
2361 this._FBU
.rects
-= 1;
2365 ExtendedDesktopSize: function () {
2366 this._FBU
.bytes
= 1;
2367 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2369 this._supportsSetDesktopSize
= true;
2370 var number_of_screens
= this._sock
.rQpeek8();
2372 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2373 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2375 this._sock
.rQskipBytes(1); // number-of-screens
2376 this._sock
.rQskipBytes(3); // padding
2378 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2379 // Save the id and flags of the first screen
2381 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2382 this._sock
.rQskipBytes(2); // x-position
2383 this._sock
.rQskipBytes(2); // y-position
2384 this._sock
.rQskipBytes(2); // width
2385 this._sock
.rQskipBytes(2); // height
2386 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2388 this._sock
.rQskipBytes(16);
2393 * The x-position indicates the reason for the change:
2395 * 0 - server resized on its own
2396 * 1 - this client requested the resize
2397 * 2 - another client requested the resize
2400 // We need to handle errors when we requested the resize.
2401 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2403 // The y-position indicates the status code from the server
2404 switch (this._FBU
.y
) {
2406 msg
= "Resize is administratively prohibited";
2409 msg
= "Out of resources";
2412 msg
= "Invalid screen layout";
2415 msg
= "Unknown reason";
2418 this._notification("Server did not accept the resize request: "
2423 this._encHandlers
.handle_FB_resize();
2427 DesktopSize: function () {
2428 this._encHandlers
.handle_FB_resize();
2432 Cursor: function () {
2433 Util
.Debug(">> set_cursor");
2434 var x
= this._FBU
.x
; // hotspot-x
2435 var y
= this._FBU
.y
; // hotspot-y
2436 var w
= this._FBU
.width
;
2437 var h
= this._FBU
.height
;
2439 var pixelslength
= w
* h
* this._fb_Bpp
;
2440 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2442 this._FBU
.bytes
= pixelslength
+ masklength
;
2443 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2445 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2446 this._sock
.rQshiftBytes(masklength
),
2449 this._FBU
.bytes
= 0;
2452 Util
.Debug("<< set_cursor");
2456 QEMUExtendedKeyEvent: function () {
2459 var keyboardEvent
= document
.createEvent("keyboardEvent");
2460 if (keyboardEvent
.code
!== undefined) {
2461 this._qemuExtKeyEventSupported
= true;
2462 this._keyboard
.setQEMUVNCKeyboardHandler();
2466 JPEG_quality_lo: function () {
2467 Util
.Error("Server sent jpeg_quality pseudo-encoding");
2470 compress_lo: function () {
2471 Util
.Error("Server sent compress level pseudo-encoding");