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', -254 ],
64 //['compress_max', -247 ],
66 ['DesktopSize', -223 ],
69 ['QEMUExtendedKeyEvent', -258 ],
70 ['ExtendedDesktopSize', -308 ],
73 ['ContinuousUpdates', -313 ]
76 this._encHandlers
= {};
80 this._sock
= null; // Websock object
81 this._display
= null; // Display object
82 this._flushing
= false; // Display flushing state
83 this._keyboard
= null; // Keyboard input handler object
84 this._mouse
= null; // Mouse input handler object
85 this._disconnTimer
= null; // disconnection timer
87 this._supportsFence
= false;
89 this._supportsContinuousUpdates
= false;
90 this._enabledContinuousUpdates
= false;
92 // Frame buffer update state
106 zlib
: [] // TIGHT zlib streams
115 this._destBuff
= null;
116 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
118 this._rre_chunk_sz
= 100;
133 this._supportsSetDesktopSize
= false;
135 this._screen_flags
= 0;
138 this._mouse_buttonMask
= 0;
139 this._mouse_arr
= [];
140 this._viewportDragging
= false;
141 this._viewportDragPos
= {};
142 this._viewportHasMoved
= false;
144 // QEMU Extended Key Event support - default to false
145 this._qemuExtKeyEventSupported
= false;
147 // set the default value on user-facing properties
148 Util
.set_defaults(this, defaults
, {
149 'target': 'null', // VNC display rendering Canvas object
150 'focusContainer': document
, // DOM element that captures keyboard input
151 'encrypt': false, // Use TLS/SSL/wss encryption
152 'true_color': true, // Request true color pixel data
153 'local_cursor': false, // Request locally rendered cursor
154 'shared': true, // Request shared mode
155 'view_only': false, // Disable client mouse/keyboard
156 'xvp_password_sep': '@', // Separator for XVP password fields
157 'disconnectTimeout': 3, // Time (s) to wait for disconnection
158 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
159 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
160 'viewportDrag': false, // Move the viewport on mouse drags
162 // Callback functions
163 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
164 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
165 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
166 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
167 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
168 'onBell': function () { }, // onBell(rfb): RFB Bell message received
169 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
170 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
171 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
172 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
173 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
177 Util
.Debug(">> RFB.constructor");
179 // populate encHandlers with bound versions
180 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
181 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
184 // Create lookup tables based on encoding number
185 for (var i
= 0; i
< this._encodings
.length
; i
++) {
186 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
187 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
188 this._encStats
[this._encodings
[i
][1]] = [0, 0];
191 // NB: nothing that needs explicit teardown should be done
192 // before this point, since this can throw an exception
194 this._display
= new Display({target
: this._target
,
195 onFlush
: this._onFlush
.bind(this)});
197 Util
.Error("Display exception: " + exc
);
201 this._keyboard
= new Keyboard({target
: this._focusContainer
,
202 onKeyPress
: this._handleKeyPress
.bind(this)});
204 this._mouse
= new Mouse({target
: this._target
,
205 onMouseButton
: this._handleMouseButton
.bind(this),
206 onMouseMove
: this._handleMouseMove
.bind(this),
207 notify
: this._keyboard
.sync
.bind(this._keyboard
)});
209 this._sock
= new Websock();
210 this._sock
.on('message', this._handle_message
.bind(this));
211 this._sock
.on('open', function () {
212 if ((this._rfb_connection_state
=== 'connecting') &&
213 (this._rfb_init_state
=== '')) {
214 this._rfb_init_state
= 'ProtocolVersion';
215 Util
.Debug("Starting VNC handshake");
217 this._fail("Unexpected server connection");
220 this._sock
.on('close', function (e
) {
221 Util
.Warn("WebSocket on-close event");
224 msg
= " (code: " + e
.code
;
226 msg
+= ", reason: " + e
.reason
;
230 switch (this._rfb_connection_state
) {
231 case 'disconnecting':
232 this._updateConnectionState('disconnected');
235 this._fail('Failed to connect to server', msg
);
238 // Handle disconnects that were initiated server-side
239 this._updateConnectionState('disconnecting');
240 this._updateConnectionState('disconnected');
243 this._fail("Unexpected server disconnect",
244 "Already disconnected: " + msg
);
247 this._fail("Unexpected server disconnect",
248 "Not in any state yet: " + msg
);
251 this._sock
.off('close');
253 this._sock
.on('error', function (e
) {
254 Util
.Warn("WebSocket on-error event");
260 var rmode
= this._display
.get_render_mode();
261 Util
.Info("Using native WebSockets, render mode: " + rmode
);
263 Util
.Debug("<< RFB.constructor");
267 var _
= Util
.Localisation
.get;
271 connect: function (host
, port
, password
, path
) {
272 this._rfb_host
= host
;
273 this._rfb_port
= port
;
274 this._rfb_password
= (password
!== undefined) ? password
: "";
275 this._rfb_path
= (path
!== undefined) ? path
: "";
277 if (!this._rfb_host
|| !this._rfb_port
) {
279 _("Must set host and port"));
282 this._rfb_init_state
= '';
283 this._updateConnectionState('connecting');
287 disconnect: function () {
288 this._updateConnectionState('disconnecting');
289 this._sock
.off('error');
290 this._sock
.off('message');
291 this._sock
.off('open');
294 sendPassword: function (passwd
) {
295 this._rfb_password
= passwd
;
296 setTimeout(this._init_msg
.bind(this), 0);
299 sendCtrlAltDel: function () {
300 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
301 Util
.Info("Sending Ctrl-Alt-Del");
303 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 1);
304 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 1);
305 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 1);
306 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 0);
307 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 0);
308 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 0);
312 xvpOp: function (ver
, op
) {
313 if (this._rfb_xvp_ver
< ver
) { return false; }
314 Util
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
315 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
319 xvpShutdown: function () {
320 return this.xvpOp(1, 2);
323 xvpReboot: function () {
324 return this.xvpOp(1, 3);
327 xvpReset: function () {
328 return this.xvpOp(1, 4);
331 // Send a key press. If 'down' is not specified then send a down key
332 // followed by an up key.
333 sendKey: function (keysym
, down
) {
334 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
335 if (typeof down
!== 'undefined') {
336 Util
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
337 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
339 Util
.Info("Sending keysym (down + up): " + keysym
);
340 RFB
.messages
.keyEvent(this._sock
, keysym
, 1);
341 RFB
.messages
.keyEvent(this._sock
, keysym
, 0);
346 clipboardPasteFrom: function (text
) {
347 if (this._rfb_connection_state
!== 'connected') { return; }
348 RFB
.messages
.clientCutText(this._sock
, text
);
351 // Requests a change of remote desktop size. This message is an extension
352 // and may only be sent if we have received an ExtendedDesktopSize message
353 requestDesktopSize: function (width
, height
) {
354 if (this._rfb_connection_state
!== 'connected' ||
359 if (this._supportsSetDesktopSize
) {
360 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
361 this._screen_id
, this._screen_flags
);
372 _connect: function () {
373 Util
.Debug(">> RFB.connect");
377 if (typeof UsingSocketIO
!== 'undefined') {
380 uri
= this._encrypt
? 'wss' : 'ws';
383 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
384 Util
.Info("connecting to " + uri
);
387 // WebSocket.onopen transitions to the RFB init states
388 this._sock
.open(uri
, this._wsProtocols
);
390 if (e
.name
=== 'SyntaxError') {
391 this._fail("Invalid host or port value given", e
);
393 this._fail("Error while connecting", e
);
397 Util
.Debug("<< RFB.connect");
400 _disconnect: function () {
401 Util
.Debug(">> RFB.disconnect");
405 Util
.Debug("<< RFB.disconnect");
408 _init_vars: function () {
411 this._FBU
.subrects
= 0; // RRE and HEXTILE
412 this._FBU
.lines
= 0; // RAW
413 this._FBU
.tiles
= 0; // HEXTILE
414 this._FBU
.zlibs
= []; // TIGHT zlib encoders
415 this._mouse_buttonMask
= 0;
416 this._mouse_arr
= [];
417 this._rfb_tightvnc
= false;
419 // Clear the per connection encoding stats
421 for (i
= 0; i
< this._encodings
.length
; i
++) {
422 this._encStats
[this._encodings
[i
][1]][0] = 0;
425 for (i
= 0; i
< 4; i
++) {
426 this._FBU
.zlibs
[i
] = new Inflator
.Inflate();
430 _print_stats: function () {
431 Util
.Info("Encoding stats for this connection:");
433 for (i
= 0; i
< this._encodings
.length
; i
++) {
434 s
= this._encStats
[this._encodings
[i
][1]];
435 if (s
[0] + s
[1] > 0) {
436 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
440 Util
.Info("Encoding stats since page load:");
441 for (i
= 0; i
< this._encodings
.length
; i
++) {
442 s
= this._encStats
[this._encodings
[i
][1]];
443 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
447 _cleanup: function () {
448 if (this._display
&& this._display
.get_context()) {
449 if (!this._view_only
) { this._keyboard
.ungrab(); }
450 if (!this._view_only
) { this._mouse
.ungrab(); }
451 this._display
.defaultCursor();
452 if (Util
.get_logging() !== 'debug') {
453 // Show noVNC logo on load and when disconnected, unless in
455 this._display
.clear();
465 * disconnected - permanent state
467 _updateConnectionState: function (state
) {
468 var oldstate
= this._rfb_connection_state
;
470 if (state
=== oldstate
) {
471 Util
.Debug("Already in state '" + state
+ "', ignoring");
475 // The 'disconnected' state is permanent for each RFB object
476 if (oldstate
=== 'disconnected') {
477 Util
.Error("Tried changing state of a disconnected RFB object");
481 // Ensure proper transitions before doing anything
484 if (oldstate
!== 'connecting') {
485 Util
.Error("Bad transition to connected state, " +
486 "previous connection state: " + oldstate
);
492 if (oldstate
!== 'disconnecting') {
493 Util
.Error("Bad transition to disconnected state, " +
494 "previous connection state: " + oldstate
);
500 if (oldstate
!== '') {
501 Util
.Error("Bad transition to connecting state, " +
502 "previous connection state: " + oldstate
);
507 case 'disconnecting':
508 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
509 Util
.Error("Bad transition to disconnecting state, " +
510 "previous connection state: " + oldstate
);
516 Util
.Error("Unknown connection state: " + state
);
520 // State change actions
522 this._rfb_connection_state
= state
;
523 this._onUpdateState(this, state
, oldstate
);
525 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
528 if (this._disconnTimer
&& state
!== 'disconnecting') {
529 Util
.Debug("Clearing disconnect timer");
530 clearTimeout(this._disconnTimer
);
531 this._disconnTimer
= null;
533 // make sure we don't get a double event
534 this._sock
.off('close');
539 // Call onDisconnected callback after onUpdateState since
540 // we don't know if the UI only displays the latest message
541 if (this._rfb_disconnect_reason
!== "") {
542 this._onDisconnected(this, this._rfb_disconnect_reason
);
544 // No reason means clean disconnect
545 this._onDisconnected(this);
553 case 'disconnecting':
556 this._disconnTimer
= setTimeout(function () {
557 this._rfb_disconnect_reason
= _("Disconnect timeout");
558 this._updateConnectionState('disconnected');
559 }.bind(this), this._disconnectTimeout
* 1000);
564 /* Print errors and disconnect
566 * The optional parameter 'details' is used for information that
567 * should be logged but not sent to the user interface.
569 _fail: function (msg
, details
) {
571 if (typeof details
!== 'undefined') {
572 fullmsg
= msg
+ " (" + details
+ ")";
574 switch (this._rfb_connection_state
) {
575 case 'disconnecting':
576 Util
.Error("Failed when disconnecting: " + fullmsg
);
579 Util
.Error("Failed while connected: " + fullmsg
);
582 Util
.Error("Failed when connecting: " + fullmsg
);
585 Util
.Error("RFB failure: " + fullmsg
);
588 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
590 // Transition to disconnected without waiting for socket to close
591 this._updateConnectionState('disconnecting');
592 this._updateConnectionState('disconnected');
598 * Send a notification to the UI. Valid levels are:
599 * 'normal'|'warn'|'error'
601 * NOTE: Options could be added in the future.
602 * NOTE: If this function is called multiple times, remember that the
603 * interface could be only showing the latest notification.
605 _notification: function(msg
, level
, options
) {
610 Util
.Debug("Notification[" + level
+ "]:" + msg
);
613 Util
.Error("Invalid notification level: " + level
);
618 this._onNotification(this, msg
, level
, options
);
620 this._onNotification(this, msg
, level
);
624 _handle_message: function () {
625 if (this._sock
.rQlen() === 0) {
626 Util
.Warn("handle_message called on an empty receive queue");
630 switch (this._rfb_connection_state
) {
632 Util
.Error("Got data while disconnected");
636 if (this._flushing
) {
639 if (!this._normal_msg()) {
642 if (this._sock
.rQlen() === 0) {
653 _handleKeyPress: function (keyevent
) {
654 if (this._view_only
) { return; } // View only, skip keyboard, events
656 var down
= (keyevent
.type
== 'keydown');
657 if (this._qemuExtKeyEventSupported
) {
658 var scancode
= XtScancode
[keyevent
.code
];
660 var keysym
= keyevent
.keysym
;
661 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
663 Util
.Error('Unable to find a xt scancode for code = ' + keyevent
.code
);
666 keysym
= keyevent
.keysym
.keysym
;
667 RFB
.messages
.keyEvent(this._sock
, keysym
, down
);
671 _handleMouseButton: function (x
, y
, down
, bmask
) {
673 this._mouse_buttonMask
|= bmask
;
675 this._mouse_buttonMask
^= bmask
;
678 if (this._viewportDrag
) {
679 if (down
&& !this._viewportDragging
) {
680 this._viewportDragging
= true;
681 this._viewportDragPos
= {'x': x
, 'y': y
};
683 // Skip sending mouse events
686 this._viewportDragging
= false;
688 // If the viewport didn't actually move, then treat as a mouse click event
689 // Send the button down event here, as the button up event is sent at the end of this function
690 if (!this._viewportHasMoved
&& !this._view_only
) {
691 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
693 this._viewportHasMoved
= false;
697 if (this._view_only
) { return; } // View only, skip mouse events
699 if (this._rfb_connection_state
!== 'connected') { return; }
700 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
703 _handleMouseMove: function (x
, y
) {
704 if (this._viewportDragging
) {
705 var deltaX
= this._viewportDragPos
.x
- x
;
706 var deltaY
= this._viewportDragPos
.y
- y
;
708 // The goal is to trigger on a certain physical width, the
709 // devicePixelRatio brings us a bit closer but is not optimal.
710 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
712 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
713 Math
.abs(deltaY
) > dragThreshold
)) {
714 this._viewportHasMoved
= true;
716 this._viewportDragPos
= {'x': x
, 'y': y
};
717 this._display
.viewportChangePos(deltaX
, deltaY
);
720 // Skip sending mouse events
724 if (this._view_only
) { return; } // View only, skip mouse events
726 if (this._rfb_connection_state
!== 'connected') { return; }
727 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
732 _negotiate_protocol_version: function () {
733 if (this._sock
.rQlen() < 12) {
734 return this._fail("Error while negotiating with server",
735 "Incomplete protocol version");
738 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
739 Util
.Info("Server ProtocolVersion: " + sversion
);
742 case "000.000": // UltraVNC repeater
746 case "003.006": // UltraVNC
747 case "003.889": // Apple Remote Desktop
748 this._rfb_version
= 3.3;
751 this._rfb_version
= 3.7;
754 case "004.000": // Intel AMT KVM
755 case "004.001": // RealVNC 4.6
756 case "005.000": // RealVNC 5.3
757 this._rfb_version
= 3.8;
760 return this._fail("Unsupported server",
761 "Invalid server version: " + sversion
);
765 var repeaterID
= this._repeaterID
;
766 while (repeaterID
.length
< 250) {
769 this._sock
.send_string(repeaterID
);
773 if (this._rfb_version
> this._rfb_max_version
) {
774 this._rfb_version
= this._rfb_max_version
;
777 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
778 ".00" + ((this._rfb_version
* 10) % 10);
779 this._sock
.send_string("RFB " + cversion
+ "\n");
780 Util
.Debug('Sent ProtocolVersion: ' + cversion
);
782 this._rfb_init_state
= 'Security';
785 _negotiate_security: function () {
786 if (this._rfb_version
>= 3.7) {
787 // Server sends supported list, client decides
788 var num_types
= this._sock
.rQshift8();
789 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
791 if (num_types
=== 0) {
792 var strlen
= this._sock
.rQshift32();
793 var reason
= this._sock
.rQshiftStr(strlen
);
794 return this._fail("Error while negotiating with server",
795 "Security failure: " + reason
);
798 this._rfb_auth_scheme
= 0;
799 var types
= this._sock
.rQshiftBytes(num_types
);
800 Util
.Debug("Server security types: " + types
);
801 for (var i
= 0; i
< types
.length
; i
++) {
804 case 2: // VNC Authentication
807 if (types
[i
] > this._rfb_auth_scheme
) {
808 this._rfb_auth_scheme
= types
[i
];
816 if (this._rfb_auth_scheme
=== 0) {
817 return this._fail("Unsupported server",
818 "Unsupported security types: " + types
);
821 this._sock
.send([this._rfb_auth_scheme
]);
824 if (this._sock
.rQwait("security scheme", 4)) { return false; }
825 this._rfb_auth_scheme
= this._sock
.rQshift32();
828 this._rfb_init_state
= 'Authentication';
829 Util
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
831 return this._init_msg(); // jump to authentication
835 _negotiate_xvp_auth: function () {
836 var xvp_sep
= this._xvp_password_sep
;
837 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
838 if (xvp_auth
.length
< 3) {
839 var msg
= 'XVP credentials required (user' + xvp_sep
+
840 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
841 this._onPasswordRequired(this, msg
);
845 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
846 String
.fromCharCode(xvp_auth
[1].length
) +
849 this._sock
.send_string(xvp_auth_str
);
850 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
851 this._rfb_auth_scheme
= 2;
852 return this._negotiate_authentication();
855 _negotiate_std_vnc_auth: function () {
856 if (this._rfb_password
.length
=== 0) {
857 this._onPasswordRequired(this);
861 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
863 // TODO(directxman12): make genDES not require an Array
864 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
865 var response
= RFB
.genDES(this._rfb_password
, challenge
);
866 this._sock
.send(response
);
867 this._rfb_init_state
= "SecurityResult";
871 _negotiate_tight_tunnels: function (numTunnels
) {
872 var clientSupportedTunnelTypes
= {
873 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
875 var serverSupportedTunnelTypes
= {};
876 // receive tunnel capabilities
877 for (var i
= 0; i
< numTunnels
; i
++) {
878 var cap_code
= this._sock
.rQshift32();
879 var cap_vendor
= this._sock
.rQshiftStr(4);
880 var cap_signature
= this._sock
.rQshiftStr(8);
881 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
884 // choose the notunnel type
885 if (serverSupportedTunnelTypes
[0]) {
886 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
887 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
888 return this._fail("Unsupported server",
889 "Client's tunnel type had the incorrect " +
890 "vendor or signature");
892 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
893 return false; // wait until we receive the sub auth count to continue
895 return this._fail("Unsupported server",
896 "Server wanted tunnels, but doesn't support " +
897 "the notunnel type");
901 _negotiate_tight_auth: function () {
902 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
903 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
904 var numTunnels
= this._sock
.rQshift32();
905 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
907 this._rfb_tightvnc
= true;
909 if (numTunnels
> 0) {
910 this._negotiate_tight_tunnels(numTunnels
);
911 return false; // wait until we receive the sub auth to continue
915 // second pass, do the sub-auth negotiation
916 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
917 var subAuthCount
= this._sock
.rQshift32();
918 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
919 this._rfb_init_state
= 'SecurityResult';
923 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
925 var clientSupportedTypes
= {
930 var serverSupportedTypes
= [];
932 for (var i
= 0; i
< subAuthCount
; i
++) {
933 var capNum
= this._sock
.rQshift32();
934 var capabilities
= this._sock
.rQshiftStr(12);
935 serverSupportedTypes
.push(capabilities
);
938 for (var authType
in clientSupportedTypes
) {
939 if (serverSupportedTypes
.indexOf(authType
) != -1) {
940 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
943 case 'STDVNOAUTH__': // no auth
944 this._rfb_init_state
= 'SecurityResult';
946 case 'STDVVNCAUTH_': // VNC auth
947 this._rfb_auth_scheme
= 2;
948 return this._init_msg();
950 return this._fail("Unsupported server",
951 "Unsupported tiny auth scheme: " +
957 return this._fail("Unsupported server",
958 "No supported sub-auth types!");
961 _negotiate_authentication: function () {
962 switch (this._rfb_auth_scheme
) {
963 case 0: // connection failed
964 if (this._sock
.rQwait("auth reason", 4)) { return false; }
965 var strlen
= this._sock
.rQshift32();
966 var reason
= this._sock
.rQshiftStr(strlen
);
967 return this._fail("Authentication failure", reason
);
970 if (this._rfb_version
>= 3.8) {
971 this._rfb_init_state
= 'SecurityResult';
974 this._rfb_init_state
= 'ClientInitialisation';
975 return this._init_msg();
978 return this._negotiate_xvp_auth();
980 case 2: // VNC authentication
981 return this._negotiate_std_vnc_auth();
983 case 16: // TightVNC Security Type
984 return this._negotiate_tight_auth();
987 return this._fail("Unsupported server",
988 "Unsupported auth scheme: " +
989 this._rfb_auth_scheme
);
993 _handle_security_result: function () {
994 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
995 switch (this._sock
.rQshift32()) {
997 this._rfb_init_state
= 'ClientInitialisation';
998 Util
.Debug('Authentication OK');
999 return this._init_msg();
1001 if (this._rfb_version
>= 3.8) {
1002 var length
= this._sock
.rQshift32();
1003 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
1004 var reason
= this._sock
.rQshiftStr(length
);
1005 return this._fail("Authentication failure", reason
);
1007 return this._fail("Authentication failure");
1011 return this._fail("Too many authentication attempts");
1013 return this._fail("Unsupported server",
1014 "Unknown SecurityResult");
1018 _negotiate_server_init: function () {
1019 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1022 this._fb_width
= this._sock
.rQshift16();
1023 this._fb_height
= this._sock
.rQshift16();
1024 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1027 var bpp
= this._sock
.rQshift8();
1028 var depth
= this._sock
.rQshift8();
1029 var big_endian
= this._sock
.rQshift8();
1030 var true_color
= this._sock
.rQshift8();
1032 var red_max
= this._sock
.rQshift16();
1033 var green_max
= this._sock
.rQshift16();
1034 var blue_max
= this._sock
.rQshift16();
1035 var red_shift
= this._sock
.rQshift8();
1036 var green_shift
= this._sock
.rQshift8();
1037 var blue_shift
= this._sock
.rQshift8();
1038 this._sock
.rQskipBytes(3); // padding
1040 // NB(directxman12): we don't want to call any callbacks or print messages until
1041 // *after* we're past the point where we could backtrack
1043 /* Connection name/title */
1044 var name_length = this._sock.rQshift32();
1045 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1046 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
1048 if (this._rfb_tightvnc) {
1049 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1050 // In TightVNC mode, ServerInit message is extended
1051 var numServerMessages = this._sock.rQshift16();
1052 var numClientMessages = this._sock.rQshift16();
1053 var numEncodings = this._sock.rQshift16();
1054 this._sock.rQskipBytes(2); // padding
1056 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1057 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1059 // we don't actually do anything with the capability information that TIGHT sends,
1060 // so we just skip the all of this.
1062 // TIGHT server message capabilities
1063 this._sock.rQskipBytes(16 * numServerMessages);
1065 // TIGHT client message capabilities
1066 this._sock.rQskipBytes(16 * numClientMessages);
1068 // TIGHT encoding capabilities
1069 this._sock.rQskipBytes(16 * numEncodings);
1072 // NB(directxman12): these are down here so that we don't run them multiple times
1074 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1075 ", bpp: " + bpp + ", depth: " + depth +
1076 ", big_endian: " + big_endian +
1077 ", true_color: " + true_color +
1078 ", red_max: " + red_max +
1079 ", green_max: " + green_max +
1080 ", blue_max: " + blue_max +
1081 ", red_shift: " + red_shift +
1082 ", green_shift: " + green_shift +
1083 ", blue_shift: " + blue_shift);
1085 if (big_endian !== 0) {
1086 Util.Warn("Server native endian is not little endian");
1089 if (red_shift !== 16) {
1090 Util.Warn("Server native red-shift is not 16");
1093 if (blue_shift !== 0) {
1094 Util.Warn("Server native blue-shift is not 0");
1097 // we're past the point where we could backtrack, so it's safe to call this
1098 this._onDesktopName(this, this._fb_name);
1100 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1101 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1102 this._true_color = false;
1105 this._display.set_true_color(this._true_color);
1106 this._display.resize(this._fb_width, this._fb_height);
1107 this._onFBResize(this, this._fb_width, this._fb_height);
1109 if (!this._view_only) { this._keyboard.grab(); }
1110 if (!this._view_only) { this._mouse.grab(); }
1112 if (this._true_color) {
1120 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1121 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1122 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1124 this._timing.fbu_rt_start = (new Date()).getTime();
1125 this._timing.pixels = 0;
1127 this._updateConnectionState('connected');
1131 /* RFB protocol initialization states:
1136 * ClientInitialization - not triggered by server message
1137 * ServerInitialization
1139 _init_msg: function () {
1140 switch (this._rfb_init_state
) {
1141 case 'ProtocolVersion':
1142 return this._negotiate_protocol_version();
1145 return this._negotiate_security();
1147 case 'Authentication':
1148 return this._negotiate_authentication();
1150 case 'SecurityResult':
1151 return this._handle_security_result();
1153 case 'ClientInitialisation':
1154 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1155 this._rfb_init_state
= 'ServerInitialisation';
1158 case 'ServerInitialisation':
1159 return this._negotiate_server_init();
1162 return this._fail("Internal error", "Unknown init state: " +
1163 this._rfb_init_state
);
1167 _handle_set_colour_map_msg: function () {
1168 Util
.Debug("SetColorMapEntries");
1169 this._sock
.rQskip8(); // Padding
1171 var first_colour
= this._sock
.rQshift16();
1172 var num_colours
= this._sock
.rQshift16();
1173 if (this._sock
.rQwait('SetColorMapEntries', num_colours
* 6, 6)) { return false; }
1175 for (var c
= 0; c
< num_colours
; c
++) {
1176 var red
= parseInt(this._sock
.rQshift16() / 256, 10);
1177 var green
= parseInt(this._sock
.rQshift16() / 256, 10);
1178 var blue
= parseInt(this._sock
.rQshift16() / 256, 10);
1179 this._display
.set_colourMap([blue
, green
, red
], first_colour
+ c
);
1181 Util
.Debug("colourMap: " + this._display
.get_colourMap());
1182 Util
.Info("Registered " + num_colours
+ " colourMap entries");
1187 _handle_server_cut_text: function () {
1188 Util
.Debug("ServerCutText");
1189 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1190 this._sock
.rQskipBytes(3); // Padding
1191 var length
= this._sock
.rQshift32();
1192 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1194 var text
= this._sock
.rQshiftStr(length
);
1195 this._onClipboard(this, text
);
1200 _handle_server_fence_msg: function() {
1201 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1202 this._sock
.rQskipBytes(3); // Padding
1203 var flags
= this._sock
.rQshift32();
1204 var length
= this._sock
.rQshift8();
1206 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1209 Util
.Warn("Bad payload length (" + length
+ ") in fence response");
1213 var payload
= this._sock
.rQshiftStr(length
);
1215 this._supportsFence
= true;
1220 * (1<<0) - BlockBefore
1221 * (1<<1) - BlockAfter
1226 if (!(flags
& (1<<31))) {
1227 return this._fail("Internal error",
1228 "Unexpected fence response");
1231 // Filter out unsupported flags
1232 // FIXME: support syncNext
1233 flags
&= (1<<0) | (1<<1);
1235 // BlockBefore and BlockAfter are automatically handled by
1236 // the fact that we process each incoming message
1238 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1243 _handle_xvp_msg: function () {
1244 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1245 this._sock
.rQskip8(); // Padding
1246 var xvp_ver
= this._sock
.rQshift8();
1247 var xvp_msg
= this._sock
.rQshift8();
1251 Util
.Error("Operation Failed");
1252 this._notification("XVP Operation Failed", 'error');
1255 this._rfb_xvp_ver
= xvp_ver
;
1256 Util
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1257 this._onXvpInit(this._rfb_xvp_ver
);
1260 this._fail("Unexpected server message",
1261 "Illegal server XVP message " + xvp_msg
);
1268 _normal_msg: function () {
1271 if (this._FBU
.rects
> 0) {
1274 msg_type
= this._sock
.rQshift8();
1278 case 0: // FramebufferUpdate
1279 var ret
= this._framebufferUpdate();
1280 if (ret
&& !this._enabledContinuousUpdates
) {
1281 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1282 this._fb_width
, this._fb_height
);
1286 case 1: // SetColorMapEntries
1287 return this._handle_set_colour_map_msg();
1294 case 3: // ServerCutText
1295 return this._handle_server_cut_text();
1297 case 150: // EndOfContinuousUpdates
1298 var first
= !(this._supportsContinuousUpdates
);
1299 this._supportsContinuousUpdates
= true;
1300 this._enabledContinuousUpdates
= false;
1302 this._enabledContinuousUpdates
= true;
1303 this._updateContinuousUpdates();
1304 Util
.Info("Enabling continuous updates.");
1306 // FIXME: We need to send a framebufferupdaterequest here
1307 // if we add support for turning off continuous updates
1311 case 248: // ServerFence
1312 return this._handle_server_fence_msg();
1315 return this._handle_xvp_msg();
1318 this._fail("Unexpected server message", "Type:" + msg_type
);
1319 Util
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1324 _onFlush: function() {
1325 this._flushing
= false;
1326 // Resume processing
1327 if (this._sock
.rQlen() > 0) {
1328 this._handle_message();
1332 _framebufferUpdate: function () {
1336 if (this._FBU
.rects
=== 0) {
1337 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1338 this._sock
.rQskip8(); // Padding
1339 this._FBU
.rects
= this._sock
.rQshift16();
1340 this._FBU
.bytes
= 0;
1341 this._timing
.cur_fbu
= 0;
1342 if (this._timing
.fbu_rt_start
> 0) {
1343 now
= (new Date()).getTime();
1344 Util
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1347 // Make sure the previous frame is fully rendered first
1348 // to avoid building up an excessive queue
1349 if (this._display
.pending()) {
1350 this._flushing
= true;
1351 this._display
.flush();
1356 while (this._FBU
.rects
> 0) {
1357 if (this._rfb_connection_state
!== 'connected') { return false; }
1359 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1360 if (this._FBU
.bytes
=== 0) {
1361 if (this._sock
.rQwait("rect header", 12)) { return false; }
1362 /* New FramebufferUpdate */
1364 var hdr
= this._sock
.rQshiftBytes(12);
1365 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1366 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1367 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1368 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1369 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1370 (hdr
[10] << 8) + hdr
[11], 10);
1372 this._onFBUReceive(this,
1373 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1374 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1375 'encoding': this._FBU
.encoding
,
1376 'encodingName': this._encNames
[this._FBU
.encoding
]});
1378 if (!this._encNames
[this._FBU
.encoding
]) {
1379 this._fail("Unexpected server message",
1380 "Unsupported encoding " +
1381 this._FBU
.encoding
);
1386 this._timing
.last_fbu
= (new Date()).getTime();
1388 ret
= this._encHandlers
[this._FBU
.encoding
]();
1390 now
= (new Date()).getTime();
1391 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1394 this._encStats
[this._FBU
.encoding
][0]++;
1395 this._encStats
[this._FBU
.encoding
][1]++;
1396 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1399 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1400 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1401 this._timing
.fbu_rt_start
> 0) {
1402 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1403 this._timing
.full_fbu_cnt
++;
1404 Util
.Info("Timing of full FBU, curr: " +
1405 this._timing
.cur_fbu
+ ", total: " +
1406 this._timing
.full_fbu_total
+ ", cnt: " +
1407 this._timing
.full_fbu_cnt
+ ", avg: " +
1408 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1411 if (this._timing
.fbu_rt_start
> 0) {
1412 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1413 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1414 this._timing
.fbu_rt_cnt
++;
1415 Util
.Info("full FBU round-trip, cur: " +
1416 fbu_rt_diff
+ ", total: " +
1417 this._timing
.fbu_rt_total
+ ", cnt: " +
1418 this._timing
.fbu_rt_cnt
+ ", avg: " +
1419 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1420 this._timing
.fbu_rt_start
= 0;
1424 if (!ret
) { return ret
; } // need more data
1427 this._display
.flip();
1429 this._onFBUComplete(this,
1430 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1431 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1432 'encoding': this._FBU
.encoding
,
1433 'encodingName': this._encNames
[this._FBU
.encoding
]});
1435 return true; // We finished this FBU
1438 _updateContinuousUpdates: function() {
1439 if (!this._enabledContinuousUpdates
) { return; }
1441 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1442 this._fb_width
, this._fb_height
);
1446 Util
.make_properties(RFB
, [
1447 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1448 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1449 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1450 ['true_color', 'rw', 'bool'], // Request true color pixel data
1451 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1452 ['shared', 'rw', 'bool'], // Request shared mode
1453 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1454 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1455 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1456 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1457 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1458 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1460 // Callback functions
1461 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1462 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1463 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1464 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1465 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1466 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1467 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1468 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1469 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1470 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1471 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1474 RFB
.prototype.set_local_cursor = function (cursor
) {
1475 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1476 this._local_cursor
= false;
1477 this._display
.disableLocalCursor(); //Only show server-side cursor
1479 if (this._display
.get_cursor_uri()) {
1480 this._local_cursor
= true;
1482 Util
.Warn("Browser does not support local cursor");
1483 this._display
.disableLocalCursor();
1488 RFB
.prototype.get_display = function () { return this._display
; };
1489 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1490 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1494 keyEvent: function (sock
, keysym
, down
) {
1495 var buff
= sock
._sQ
;
1496 var offset
= sock
._sQlen
;
1498 buff
[offset
] = 4; // msg-type
1499 buff
[offset
+ 1] = down
;
1501 buff
[offset
+ 2] = 0;
1502 buff
[offset
+ 3] = 0;
1504 buff
[offset
+ 4] = (keysym
>> 24);
1505 buff
[offset
+ 5] = (keysym
>> 16);
1506 buff
[offset
+ 6] = (keysym
>> 8);
1507 buff
[offset
+ 7] = keysym
;
1513 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1514 function getRFBkeycode(xt_scancode
) {
1515 var upperByte
= (keycode
>> 8);
1516 var lowerByte
= (keycode
& 0x00ff);
1517 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1518 lowerByte
= lowerByte
| 0x80;
1524 var buff
= sock
._sQ
;
1525 var offset
= sock
._sQlen
;
1527 buff
[offset
] = 255; // msg-type
1528 buff
[offset
+ 1] = 0; // sub msg-type
1530 buff
[offset
+ 2] = (down
>> 8);
1531 buff
[offset
+ 3] = down
;
1533 buff
[offset
+ 4] = (keysym
>> 24);
1534 buff
[offset
+ 5] = (keysym
>> 16);
1535 buff
[offset
+ 6] = (keysym
>> 8);
1536 buff
[offset
+ 7] = keysym
;
1538 var RFBkeycode
= getRFBkeycode(keycode
);
1540 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1541 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1542 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1543 buff
[offset
+ 11] = RFBkeycode
;
1549 pointerEvent: function (sock
, x
, y
, mask
) {
1550 var buff
= sock
._sQ
;
1551 var offset
= sock
._sQlen
;
1553 buff
[offset
] = 5; // msg-type
1555 buff
[offset
+ 1] = mask
;
1557 buff
[offset
+ 2] = x
>> 8;
1558 buff
[offset
+ 3] = x
;
1560 buff
[offset
+ 4] = y
>> 8;
1561 buff
[offset
+ 5] = y
;
1567 // TODO(directxman12): make this unicode compatible?
1568 clientCutText: function (sock
, text
) {
1569 var buff
= sock
._sQ
;
1570 var offset
= sock
._sQlen
;
1572 buff
[offset
] = 6; // msg-type
1574 buff
[offset
+ 1] = 0; // padding
1575 buff
[offset
+ 2] = 0; // padding
1576 buff
[offset
+ 3] = 0; // padding
1578 var n
= text
.length
;
1580 buff
[offset
+ 4] = n
>> 24;
1581 buff
[offset
+ 5] = n
>> 16;
1582 buff
[offset
+ 6] = n
>> 8;
1583 buff
[offset
+ 7] = n
;
1585 for (var i
= 0; i
< n
; i
++) {
1586 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1589 sock
._sQlen
+= 8 + n
;
1593 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1594 var buff
= sock
._sQ
;
1595 var offset
= sock
._sQlen
;
1597 buff
[offset
] = 251; // msg-type
1598 buff
[offset
+ 1] = 0; // padding
1599 buff
[offset
+ 2] = width
>> 8; // width
1600 buff
[offset
+ 3] = width
;
1601 buff
[offset
+ 4] = height
>> 8; // height
1602 buff
[offset
+ 5] = height
;
1604 buff
[offset
+ 6] = 1; // number-of-screens
1605 buff
[offset
+ 7] = 0; // padding
1608 buff
[offset
+ 8] = id
>> 24; // id
1609 buff
[offset
+ 9] = id
>> 16;
1610 buff
[offset
+ 10] = id
>> 8;
1611 buff
[offset
+ 11] = id
;
1612 buff
[offset
+ 12] = 0; // x-position
1613 buff
[offset
+ 13] = 0;
1614 buff
[offset
+ 14] = 0; // y-position
1615 buff
[offset
+ 15] = 0;
1616 buff
[offset
+ 16] = width
>> 8; // width
1617 buff
[offset
+ 17] = width
;
1618 buff
[offset
+ 18] = height
>> 8; // height
1619 buff
[offset
+ 19] = height
;
1620 buff
[offset
+ 20] = flags
>> 24; // flags
1621 buff
[offset
+ 21] = flags
>> 16;
1622 buff
[offset
+ 22] = flags
>> 8;
1623 buff
[offset
+ 23] = flags
;
1629 clientFence: function (sock
, flags
, payload
) {
1630 var buff
= sock
._sQ
;
1631 var offset
= sock
._sQlen
;
1633 buff
[offset
] = 248; // msg-type
1635 buff
[offset
+ 1] = 0; // padding
1636 buff
[offset
+ 2] = 0; // padding
1637 buff
[offset
+ 3] = 0; // padding
1639 buff
[offset
+ 4] = flags
>> 24; // flags
1640 buff
[offset
+ 5] = flags
>> 16;
1641 buff
[offset
+ 6] = flags
>> 8;
1642 buff
[offset
+ 7] = flags
;
1644 var n
= payload
.length
;
1646 buff
[offset
+ 8] = n
; // length
1648 for (var i
= 0; i
< n
; i
++) {
1649 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1652 sock
._sQlen
+= 9 + n
;
1656 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1657 var buff
= sock
._sQ
;
1658 var offset
= sock
._sQlen
;
1660 buff
[offset
] = 150; // msg-type
1661 buff
[offset
+ 1] = enable
; // enable-flag
1663 buff
[offset
+ 2] = x
>> 8; // x
1664 buff
[offset
+ 3] = x
;
1665 buff
[offset
+ 4] = y
>> 8; // y
1666 buff
[offset
+ 5] = y
;
1667 buff
[offset
+ 6] = width
>> 8; // width
1668 buff
[offset
+ 7] = width
;
1669 buff
[offset
+ 8] = height
>> 8; // height
1670 buff
[offset
+ 9] = height
;
1676 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1677 var buff
= sock
._sQ
;
1678 var offset
= sock
._sQlen
;
1680 buff
[offset
] = 0; // msg-type
1682 buff
[offset
+ 1] = 0; // padding
1683 buff
[offset
+ 2] = 0; // padding
1684 buff
[offset
+ 3] = 0; // padding
1686 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1687 buff
[offset
+ 5] = depth
* 8; // depth
1688 buff
[offset
+ 6] = 0; // little-endian
1689 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1691 buff
[offset
+ 8] = 0; // red-max
1692 buff
[offset
+ 9] = 255; // red-max
1694 buff
[offset
+ 10] = 0; // green-max
1695 buff
[offset
+ 11] = 255; // green-max
1697 buff
[offset
+ 12] = 0; // blue-max
1698 buff
[offset
+ 13] = 255; // blue-max
1700 buff
[offset
+ 14] = 16; // red-shift
1701 buff
[offset
+ 15] = 8; // green-shift
1702 buff
[offset
+ 16] = 0; // blue-shift
1704 buff
[offset
+ 17] = 0; // padding
1705 buff
[offset
+ 18] = 0; // padding
1706 buff
[offset
+ 19] = 0; // padding
1712 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1713 var buff
= sock
._sQ
;
1714 var offset
= sock
._sQlen
;
1716 buff
[offset
] = 2; // msg-type
1717 buff
[offset
+ 1] = 0; // padding
1719 // offset + 2 and offset + 3 are encoding count
1721 var i
, j
= offset
+ 4, cnt
= 0;
1722 for (i
= 0; i
< encodings
.length
; i
++) {
1723 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1724 Util
.Debug("Skipping Cursor pseudo-encoding");
1725 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1726 // TODO: remove this when we have tight+non-true-color
1727 Util
.Warn("Skipping tight as it is only supported with true color");
1729 var enc
= encodings
[i
][1];
1730 buff
[j
] = enc
>> 24;
1731 buff
[j
+ 1] = enc
>> 16;
1732 buff
[j
+ 2] = enc
>> 8;
1740 buff
[offset
+ 2] = cnt
>> 8;
1741 buff
[offset
+ 3] = cnt
;
1743 sock
._sQlen
+= j
- offset
;
1747 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1748 var buff
= sock
._sQ
;
1749 var offset
= sock
._sQlen
;
1751 if (typeof(x
) === "undefined") { x
= 0; }
1752 if (typeof(y
) === "undefined") { y
= 0; }
1754 buff
[offset
] = 3; // msg-type
1755 buff
[offset
+ 1] = incremental
? 1 : 0;
1757 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1758 buff
[offset
+ 3] = x
& 0xFF;
1760 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1761 buff
[offset
+ 5] = y
& 0xFF;
1763 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1764 buff
[offset
+ 7] = w
& 0xFF;
1766 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1767 buff
[offset
+ 9] = h
& 0xFF;
1774 RFB
.genDES = function (password
, challenge
) {
1776 for (var i
= 0; i
< password
.length
; i
++) {
1777 passwd
.push(password
.charCodeAt(i
));
1779 return (new DES(passwd
)).encrypt(challenge
);
1782 RFB
.encodingHandlers
= {
1784 if (this._FBU
.lines
=== 0) {
1785 this._FBU
.lines
= this._FBU
.height
;
1788 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1789 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1790 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1791 var curr_height
= Math
.min(this._FBU
.lines
,
1792 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1793 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1794 curr_height
, this._sock
.get_rQ(),
1795 this._sock
.get_rQi());
1796 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1797 this._FBU
.lines
-= curr_height
;
1799 if (this._FBU
.lines
> 0) {
1800 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1803 this._FBU
.bytes
= 0;
1809 COPYRECT: function () {
1810 this._FBU
.bytes
= 4;
1811 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1812 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1813 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1817 this._FBU
.bytes
= 0;
1823 if (this._FBU
.subrects
=== 0) {
1824 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1825 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1826 this._FBU
.subrects
= this._sock
.rQshift32();
1827 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1828 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1831 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1832 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1833 var x
= this._sock
.rQshift16();
1834 var y
= this._sock
.rQshift16();
1835 var width
= this._sock
.rQshift16();
1836 var height
= this._sock
.rQshift16();
1837 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1838 this._FBU
.subrects
--;
1841 if (this._FBU
.subrects
> 0) {
1842 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1843 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1846 this._FBU
.bytes
= 0;
1852 HEXTILE: function () {
1853 var rQ
= this._sock
.get_rQ();
1854 var rQi
= this._sock
.get_rQi();
1856 if (this._FBU
.tiles
=== 0) {
1857 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1858 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1859 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1860 this._FBU
.tiles
= this._FBU
.total_tiles
;
1863 while (this._FBU
.tiles
> 0) {
1864 this._FBU
.bytes
= 1;
1865 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1866 var subencoding
= rQ
[rQi
]; // Peek
1867 if (subencoding
> 30) { // Raw
1868 this._fail("Unexpected server message",
1869 "Illegal hextile subencoding: " + subencoding
);
1874 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1875 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1876 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1877 var x
= this._FBU
.x
+ tile_x
* 16;
1878 var y
= this._FBU
.y
+ tile_y
* 16;
1879 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1880 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1882 // Figure out how much we are expecting
1883 if (subencoding
& 0x01) { // Raw
1884 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1886 if (subencoding
& 0x02) { // Background
1887 this._FBU
.bytes
+= this._fb_Bpp
;
1889 if (subencoding
& 0x04) { // Foreground
1890 this._FBU
.bytes
+= this._fb_Bpp
;
1892 if (subencoding
& 0x08) { // AnySubrects
1893 this._FBU
.bytes
++; // Since we aren't shifting it off
1894 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1895 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1896 if (subencoding
& 0x10) { // SubrectsColoured
1897 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1899 this._FBU
.bytes
+= subrects
* 2;
1904 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1906 // We know the encoding and have a whole tile
1907 this._FBU
.subencoding
= rQ
[rQi
];
1909 if (this._FBU
.subencoding
=== 0) {
1910 if (this._FBU
.lastsubencoding
& 0x01) {
1911 // Weird: ignore blanks are RAW
1912 Util
.Debug(" Ignoring blank after RAW");
1914 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1916 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1917 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1918 rQi
+= this._FBU
.bytes
- 1;
1920 if (this._FBU
.subencoding
& 0x02) { // Background
1921 if (this._fb_Bpp
== 1) {
1922 this._FBU
.background
= rQ
[rQi
];
1925 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1927 rQi
+= this._fb_Bpp
;
1929 if (this._FBU
.subencoding
& 0x04) { // Foreground
1930 if (this._fb_Bpp
== 1) {
1931 this._FBU
.foreground
= rQ
[rQi
];
1933 // this._fb_Bpp is 4
1934 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1936 rQi
+= this._fb_Bpp
;
1939 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1940 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1944 for (var s
= 0; s
< subrects
; s
++) {
1946 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1947 if (this._fb_Bpp
=== 1) {
1951 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1953 rQi
+= this._fb_Bpp
;
1955 color
= this._FBU
.foreground
;
1960 var sy
= (xy
& 0x0f);
1964 var sw
= (wh
>> 4) + 1;
1965 var sh
= (wh
& 0x0f) + 1;
1967 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1970 this._display
.finishTile();
1972 this._sock
.set_rQi(rQi
);
1973 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1974 this._FBU
.bytes
= 0;
1978 if (this._FBU
.tiles
=== 0) {
1985 getTightCLength: function (arr
) {
1986 var header
= 1, data
= 0;
1987 data
+= arr
[0] & 0x7f;
1988 if (arr
[0] & 0x80) {
1990 data
+= (arr
[1] & 0x7f) << 7;
1991 if (arr
[1] & 0x80) {
1993 data
+= arr
[2] << 14;
1996 return [header
, data
];
1999 display_tight: function (isTightPNG
) {
2000 if (this._fb_depth
=== 1) {
2001 this._fail("Internal error",
2002 "Tight protocol handler only implements " +
2006 this._FBU
.bytes
= 1; // compression-control byte
2007 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2009 var checksum = function (data
) {
2011 for (var i
= 0; i
< data
.length
; i
++) {
2013 if (sum
> 65536) sum
-= 65536;
2018 var resetStreams
= 0;
2020 var decompress = function (data
, expected
) {
2021 for (var i
= 0; i
< 4; i
++) {
2022 if ((resetStreams
>> i
) & 1) {
2023 this._FBU
.zlibs
[i
].reset();
2024 Util
.Info("Reset zlib stream " + i
);
2028 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2029 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2030 /*if (uncompressed.status !== 0) {
2031 Util.Error("Invalid data in zlib stream");
2034 //return uncompressed.data;
2035 return uncompressed
;
2038 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2039 // Convert indexed (palette based) image data to RGB
2040 // TODO: reduce number of calculations inside loop
2041 var dest
= this._destBuff
;
2042 var w
= Math
.floor((width
+ 7) / 8);
2043 var w1
= Math
.floor(width
/ 8);
2045 /*for (var y = 0; y < height; y++) {
2047 var yoffset = y * width;
2048 var ybitoffset = y * w;
2049 var xoffset, targetbyte;
2050 for (x = 0; x < w1; x++) {
2051 xoffset = yoffset + x * 8;
2052 targetbyte = data[ybitoffset + x];
2053 for (b = 7; b >= 0; b--) {
2054 dp = (xoffset + 7 - b) * 3;
2055 sp = (targetbyte >> b & 1) * 3;
2056 dest[dp] = palette[sp];
2057 dest[dp + 1] = palette[sp + 1];
2058 dest[dp + 2] = palette[sp + 2];
2062 xoffset = yoffset + x * 8;
2063 targetbyte = data[ybitoffset + x];
2064 for (b = 7; b >= 8 - width % 8; b--) {
2065 dp = (xoffset + 7 - b) * 3;
2066 sp = (targetbyte >> b & 1) * 3;
2067 dest[dp] = palette[sp];
2068 dest[dp + 1] = palette[sp + 1];
2069 dest[dp + 2] = palette[sp + 2];
2073 for (var y
= 0; y
< height
; y
++) {
2075 for (x
= 0; x
< w1
; x
++) {
2076 for (b
= 7; b
>= 0; b
--) {
2077 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2078 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2079 dest
[dp
] = palette
[sp
];
2080 dest
[dp
+ 1] = palette
[sp
+ 1];
2081 dest
[dp
+ 2] = palette
[sp
+ 2];
2086 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2087 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2088 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2089 dest
[dp
] = palette
[sp
];
2090 dest
[dp
+ 1] = palette
[sp
+ 1];
2091 dest
[dp
+ 2] = palette
[sp
+ 2];
2099 var indexedToRGBX = function (data
, palette
, width
, height
) {
2100 // Convert indexed (palette based) image data to RGB
2101 var dest
= this._destBuff
;
2102 var total
= width
* height
* 4;
2103 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2104 var sp
= data
[j
] * 3;
2105 dest
[i
] = palette
[sp
];
2106 dest
[i
+ 1] = palette
[sp
+ 1];
2107 dest
[i
+ 2] = palette
[sp
+ 2];
2114 var rQi
= this._sock
.get_rQi();
2115 var rQ
= this._sock
.rQwhole();
2117 var cl_header
, cl_data
;
2119 var handlePalette = function () {
2120 var numColors
= rQ
[rQi
+ 2] + 1;
2121 var paletteSize
= numColors
* this._fb_depth
;
2122 this._FBU
.bytes
+= paletteSize
;
2123 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2125 var bpp
= (numColors
<= 2) ? 1 : 8;
2126 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2128 if (rowSize
* this._FBU
.height
< 12) {
2131 cl_data
= rowSize
* this._FBU
.height
;
2132 //clength = [0, rowSize * this._FBU.height];
2134 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2135 var cl_offset
= rQi
+ 3 + paletteSize
;
2138 cl_data
+= rQ
[cl_offset
] & 0x7f;
2139 if (rQ
[cl_offset
] & 0x80) {
2141 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2142 if (rQ
[cl_offset
+ 1] & 0x80) {
2144 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2147 // end inline getTightCLength
2150 this._FBU
.bytes
+= cl_header
+ cl_data
;
2151 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2153 // Shift ctl, filter id, num colors, palette entries, and clength off
2154 this._sock
.rQskipBytes(3);
2155 //var palette = this._sock.rQshiftBytes(paletteSize);
2156 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2157 this._sock
.rQskipBytes(cl_header
);
2160 data
= this._sock
.rQshiftBytes(cl_data
);
2162 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2165 // Convert indexed (palette based) image data to RGB
2167 if (numColors
== 2) {
2168 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2169 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2171 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2172 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2179 var handleCopy = function () {
2181 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2182 if (uncompressedSize
< 12) {
2185 cl_data
= uncompressedSize
;
2187 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2188 var cl_offset
= rQi
+ 1;
2191 cl_data
+= rQ
[cl_offset
] & 0x7f;
2192 if (rQ
[cl_offset
] & 0x80) {
2194 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2195 if (rQ
[cl_offset
+ 1] & 0x80) {
2197 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2200 // end inline getTightCLength
2202 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2203 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2205 // Shift ctl, clength off
2206 this._sock
.rQshiftBytes(1 + cl_header
);
2209 data
= this._sock
.rQshiftBytes(cl_data
);
2211 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2214 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2219 var ctl
= this._sock
.rQpeek8();
2221 // Keep tight reset bits
2222 resetStreams
= ctl
& 0xF;
2224 // Figure out filter
2226 streamId
= ctl
& 0x3;
2228 if (ctl
=== 0x08) cmode
= "fill";
2229 else if (ctl
=== 0x09) cmode
= "jpeg";
2230 else if (ctl
=== 0x0A) cmode
= "png";
2231 else if (ctl
& 0x04) cmode
= "filter";
2232 else if (ctl
< 0x04) cmode
= "copy";
2233 else return this._fail("Unexpected server message",
2234 "Illegal tight compression received, " +
2237 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2238 return this._fail("Unexpected server message",
2239 "filter/copy received in tightPNG mode");
2243 // fill use fb_depth because TPIXELs drop the padding byte
2244 case "fill": // TPIXEL
2245 this._FBU
.bytes
+= this._fb_depth
;
2247 case "jpeg": // max clength
2248 this._FBU
.bytes
+= 3;
2250 case "png": // max clength
2251 this._FBU
.bytes
+= 3;
2253 case "filter": // filter id + num colors if palette
2254 this._FBU
.bytes
+= 2;
2260 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2262 // Determine FBU.bytes
2266 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);
2267 this._sock
.rQskipBytes(4);
2271 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2272 var cl_offset
= rQi
+ 1;
2275 cl_data
+= rQ
[cl_offset
] & 0x7f;
2276 if (rQ
[cl_offset
] & 0x80) {
2278 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2279 if (rQ
[cl_offset
+ 1] & 0x80) {
2281 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2284 // end inline getTightCLength
2285 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2286 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2288 // We have everything, render it
2289 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2290 data
= this._sock
.rQshiftBytes(cl_data
);
2291 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2294 var filterId
= rQ
[rQi
+ 1];
2295 if (filterId
=== 1) {
2296 if (!handlePalette()) { return false; }
2298 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2299 // Filter 2, Gradient is valid but not use if jpeg is enabled
2300 this._fail("Unexpected server message",
2301 "Unsupported tight subencoding received, " +
2302 "filter: " + filterId
);
2306 if (!handleCopy()) { return false; }
2311 this._FBU
.bytes
= 0;
2317 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2318 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2320 last_rect: function () {
2321 this._FBU
.rects
= 0;
2325 handle_FB_resize: function () {
2326 this._fb_width
= this._FBU
.width
;
2327 this._fb_height
= this._FBU
.height
;
2328 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2329 this._display
.resize(this._fb_width
, this._fb_height
);
2330 this._onFBResize(this, this._fb_width
, this._fb_height
);
2331 this._timing
.fbu_rt_start
= (new Date()).getTime();
2332 this._updateContinuousUpdates();
2334 this._FBU
.bytes
= 0;
2335 this._FBU
.rects
-= 1;
2339 ExtendedDesktopSize: function () {
2340 this._FBU
.bytes
= 1;
2341 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2343 this._supportsSetDesktopSize
= true;
2344 var number_of_screens
= this._sock
.rQpeek8();
2346 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2347 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2349 this._sock
.rQskipBytes(1); // number-of-screens
2350 this._sock
.rQskipBytes(3); // padding
2352 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2353 // Save the id and flags of the first screen
2355 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2356 this._sock
.rQskipBytes(2); // x-position
2357 this._sock
.rQskipBytes(2); // y-position
2358 this._sock
.rQskipBytes(2); // width
2359 this._sock
.rQskipBytes(2); // height
2360 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2362 this._sock
.rQskipBytes(16);
2367 * The x-position indicates the reason for the change:
2369 * 0 - server resized on its own
2370 * 1 - this client requested the resize
2371 * 2 - another client requested the resize
2374 // We need to handle errors when we requested the resize.
2375 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2377 // The y-position indicates the status code from the server
2378 switch (this._FBU
.y
) {
2380 msg
= "Resize is administratively prohibited";
2383 msg
= "Out of resources";
2386 msg
= "Invalid screen layout";
2389 msg
= "Unknown reason";
2392 this._notification("Server did not accept the resize request: "
2397 this._encHandlers
.handle_FB_resize();
2401 DesktopSize: function () {
2402 this._encHandlers
.handle_FB_resize();
2406 Cursor: function () {
2407 Util
.Debug(">> set_cursor");
2408 var x
= this._FBU
.x
; // hotspot-x
2409 var y
= this._FBU
.y
; // hotspot-y
2410 var w
= this._FBU
.width
;
2411 var h
= this._FBU
.height
;
2413 var pixelslength
= w
* h
* this._fb_Bpp
;
2414 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2416 this._FBU
.bytes
= pixelslength
+ masklength
;
2417 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2419 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2420 this._sock
.rQshiftBytes(masklength
),
2423 this._FBU
.bytes
= 0;
2426 Util
.Debug("<< set_cursor");
2430 QEMUExtendedKeyEvent: function () {
2433 var keyboardEvent
= document
.createEvent("keyboardEvent");
2434 if (keyboardEvent
.code
!== undefined) {
2435 this._qemuExtKeyEventSupported
= true;
2436 this._keyboard
.setQEMUVNCKeyboardHandler();
2440 JPEG_quality_lo: function () {
2441 Util
.Error("Server sent jpeg_quality pseudo-encoding");
2444 compress_lo: function () {
2445 Util
.Error("Server sent compress level pseudo-encoding");