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_state
= 'disconnected';
39 this._rfb_version
= 0;
40 this._rfb_max_version
= 3.8;
41 this._rfb_auth_scheme
= '';
43 this._rfb_tightvnc
= false;
44 this._rfb_xvp_ver
= 0;
46 // In preference order
55 // Psuedo-encoding settings
57 //['JPEG_quality_lo', -32 ],
58 ['JPEG_quality_med', -26 ],
59 //['JPEG_quality_hi', -23 ],
60 //['compress_lo', -255 ],
61 ['compress_hi', -247 ],
63 ['DesktopSize', -223 ],
66 ['QEMUExtendedKeyEvent', -258 ],
67 ['ExtendedDesktopSize', -308 ],
70 ['ContinuousUpdates', -313 ]
73 this._encHandlers
= {};
77 this._sock
= null; // Websock object
78 this._display
= null; // Display object
79 this._keyboard
= null; // Keyboard input handler object
80 this._mouse
= null; // Mouse input handler object
81 this._disconnTimer
= null; // disconnection timer
82 this._msgTimer
= null; // queued handle_msg timer
84 this._supportsFence
= false;
86 this._supportsContinuousUpdates
= false;
87 this._enabledContinuousUpdates
= false;
89 // Frame buffer update state
103 zlib
: [] // TIGHT zlib streams
112 this._destBuff
= null;
113 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
115 this._rre_chunk_sz
= 100;
130 this._supportsSetDesktopSize
= false;
132 this._screen_flags
= 0;
135 this._mouse_buttonMask
= 0;
136 this._mouse_arr
= [];
137 this._viewportDragging
= false;
138 this._viewportDragPos
= {};
139 this._viewportHasMoved
= false;
141 // QEMU Extended Key Event support - default to false
142 this._qemuExtKeyEventSupported
= false;
144 // set the default value on user-facing properties
145 Util
.set_defaults(this, defaults
, {
146 'target': 'null', // VNC display rendering Canvas object
147 'focusContainer': document
, // DOM element that captures keyboard input
148 'encrypt': false, // Use TLS/SSL/wss encryption
149 'true_color': true, // Request true color pixel data
150 'local_cursor': false, // Request locally rendered cursor
151 'shared': true, // Request shared mode
152 'view_only': false, // Disable client mouse/keyboard
153 'xvp_password_sep': '@', // Separator for XVP password fields
154 'disconnectTimeout': 3, // Time (s) to wait for disconnection
155 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
156 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
157 'viewportDrag': false, // Move the viewport on mouse drags
159 // Callback functions
160 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate, statusMsg): state update/change
161 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
162 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
163 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
164 'onBell': function () { }, // onBell(rfb): RFB Bell message received
165 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
166 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
167 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
168 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
169 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
173 Util
.Debug(">> RFB.constructor");
175 // populate encHandlers with bound versions
176 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
177 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
180 // Create lookup tables based on encoding number
181 for (var i
= 0; i
< this._encodings
.length
; i
++) {
182 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
183 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
184 this._encStats
[this._encodings
[i
][1]] = [0, 0];
187 // NB: nothing that needs explicit teardown should be done
188 // before this point, since this can throw an exception
190 this._display
= new Display({target
: this._target
});
192 Util
.Error("Display exception: " + exc
);
196 this._keyboard
= new Keyboard({target
: this._focusContainer
,
197 onKeyPress
: this._handleKeyPress
.bind(this)});
199 this._mouse
= new Mouse({target
: this._target
,
200 onMouseButton
: this._handleMouseButton
.bind(this),
201 onMouseMove
: this._handleMouseMove
.bind(this),
202 notify
: this._keyboard
.sync
.bind(this._keyboard
)});
204 this._sock
= new Websock();
205 this._sock
.on('message', this._handle_message
.bind(this));
206 this._sock
.on('open', function () {
207 if (this._rfb_state
=== 'connect') {
208 this._updateState('ProtocolVersion', "Starting VNC handshake");
210 this._fail("Got unexpected WebSocket connection");
213 this._sock
.on('close', function (e
) {
214 Util
.Warn("WebSocket on-close event");
217 msg
= " (code: " + e
.code
;
219 msg
+= ", reason: " + e
.reason
;
223 if (this._rfb_state
=== 'disconnect') {
224 this._updateState('disconnected', 'VNC disconnected' + msg
);
225 } else if (this._rfb_state
=== 'ProtocolVersion') {
226 this._fail('Failed to connect to server' + msg
);
227 } else if (this._rfb_state
in {'failed': 1, 'disconnected': 1}) {
228 Util
.Error("Received onclose while disconnected" + msg
);
230 this._fail("Server disconnected" + msg
);
232 this._sock
.off('close');
234 this._sock
.on('error', function (e
) {
235 Util
.Warn("WebSocket on-error event");
240 var rmode
= this._display
.get_render_mode();
241 Util
.Info("Using native WebSockets");
242 this._updateState('loaded', 'noVNC ready: native WebSockets, ' + rmode
);
244 Util
.Debug("<< RFB.constructor");
250 connect: function (host
, port
, password
, path
) {
251 this._rfb_host
= host
;
252 this._rfb_port
= port
;
253 this._rfb_password
= (password
!== undefined) ? password
: "";
254 this._rfb_path
= (path
!== undefined) ? path
: "";
256 if (!this._rfb_host
|| !this._rfb_port
) {
257 return this._fail("Must set host and port");
260 this._updateState('connect');
264 disconnect: function () {
265 this._updateState('disconnect', 'Disconnecting');
266 this._sock
.off('error');
267 this._sock
.off('message');
268 this._sock
.off('open');
271 sendPassword: function (passwd
) {
272 this._rfb_password
= passwd
;
273 setTimeout(this._init_msg
.bind(this), 0);
276 sendCtrlAltDel: function () {
277 if (this._rfb_state
!== 'normal' || this._view_only
) { return false; }
278 Util
.Info("Sending Ctrl-Alt-Del");
280 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 1);
281 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 1);
282 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 1);
283 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 0);
284 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 0);
285 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 0);
289 xvpOp: function (ver
, op
) {
290 if (this._rfb_xvp_ver
< ver
) { return false; }
291 Util
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
292 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
296 xvpShutdown: function () {
297 return this.xvpOp(1, 2);
300 xvpReboot: function () {
301 return this.xvpOp(1, 3);
304 xvpReset: function () {
305 return this.xvpOp(1, 4);
308 // Send a key press. If 'down' is not specified then send a down key
309 // followed by an up key.
310 sendKey: function (code
, down
) {
311 if (this._rfb_state
!== "normal" || this._view_only
) { return false; }
312 if (typeof down
!== 'undefined') {
313 Util
.Info("Sending key code (" + (down
? "down" : "up") + "): " + code
);
314 RFB
.messages
.keyEvent(this._sock
, code
, down
? 1 : 0);
316 Util
.Info("Sending key code (down + up): " + code
);
317 RFB
.messages
.keyEvent(this._sock
, code
, 1);
318 RFB
.messages
.keyEvent(this._sock
, code
, 0);
323 clipboardPasteFrom: function (text
) {
324 if (this._rfb_state
!== 'normal') { return; }
325 RFB
.messages
.clientCutText(this._sock
, text
);
328 // Requests a change of remote desktop size. This message is an extension
329 // and may only be sent if we have received an ExtendedDesktopSize message
330 requestDesktopSize: function (width
, height
) {
331 if (this._rfb_state
!== "normal") { return; }
333 if (this._supportsSetDesktopSize
) {
334 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
335 this._screen_id
, this._screen_flags
);
343 _connect: function () {
344 Util
.Debug(">> RFB.connect");
347 if (typeof UsingSocketIO
!== 'undefined') {
350 uri
= this._encrypt
? 'wss' : 'ws';
353 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
354 Util
.Info("connecting to " + uri
);
356 this._sock
.open(uri
, this._wsProtocols
);
358 Util
.Debug("<< RFB.connect");
361 _init_vars: function () {
364 this._FBU
.subrects
= 0; // RRE and HEXTILE
365 this._FBU
.lines
= 0; // RAW
366 this._FBU
.tiles
= 0; // HEXTILE
367 this._FBU
.zlibs
= []; // TIGHT zlib encoders
368 this._mouse_buttonMask
= 0;
369 this._mouse_arr
= [];
370 this._rfb_tightvnc
= false;
372 // Clear the per connection encoding stats
374 for (i
= 0; i
< this._encodings
.length
; i
++) {
375 this._encStats
[this._encodings
[i
][1]][0] = 0;
378 for (i
= 0; i
< 4; i
++) {
379 this._FBU
.zlibs
[i
] = new Inflator
.Inflate();
383 _print_stats: function () {
384 Util
.Info("Encoding stats for this connection:");
386 for (i
= 0; i
< this._encodings
.length
; i
++) {
387 s
= this._encStats
[this._encodings
[i
][1]];
388 if (s
[0] + s
[1] > 0) {
389 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
393 Util
.Info("Encoding stats since page load:");
394 for (i
= 0; i
< this._encodings
.length
; i
++) {
395 s
= this._encStats
[this._encodings
[i
][1]];
396 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
400 _cleanupSocket: function (state
) {
401 if (this._msgTimer
) {
402 clearInterval(this._msgTimer
);
403 this._msgTimer
= null;
406 if (this._display
&& this._display
.get_context()) {
407 this._keyboard
.ungrab();
408 this._mouse
.ungrab();
409 if (state
!== 'connect' && state
!== 'loaded') {
410 this._display
.defaultCursor();
412 if (Util
.get_logging() !== 'debug' || state
=== 'loaded') {
413 // Show noVNC logo on load and when disconnected, unless in
415 this._display
.clear();
424 * loaded - page load, equivalent to disconnected
425 * disconnected - idle state
426 * connect - starting to connect (to ProtocolVersion)
428 * disconnect - starting to disconnect
429 * failed - abnormal disconnect
430 * fatal - failed to load page, or fatal error
432 * RFB protocol initialization states:
437 * ClientInitialization - not triggered by server message
438 * ServerInitialization (to normal)
440 _updateState: function (state
, statusMsg
) {
441 var oldstate
= this._rfb_state
;
443 if (state
=== oldstate
) {
444 // Already here, ignore
445 Util
.Debug("Already in state '" + state
+ "', ignoring");
450 * These are disconnected states. A previous connect may
451 * asynchronously cause a connection so make sure we are closed.
453 if (state
in {'disconnected': 1, 'loaded': 1, 'connect': 1,
454 'disconnect': 1, 'failed': 1, 'fatal': 1}) {
455 this._cleanupSocket(state
);
458 if (oldstate
=== 'fatal') {
459 Util
.Error('Fatal error, cannot continue');
462 var cmsg
= typeof(statusMsg
) !== 'undefined' ? (" Msg: " + statusMsg
) : "";
463 var fullmsg
= "New state '" + state
+ "', was '" + oldstate
+ "'." + cmsg
;
464 if (state
=== 'failed' || state
=== 'fatal') {
470 if (oldstate
=== 'failed' && state
=== 'disconnected') {
471 // do disconnect action, but stay in failed state
472 this._rfb_state
= 'failed';
474 this._rfb_state
= state
;
477 if (this._disconnTimer
&& this._rfb_state
!== 'disconnect') {
478 Util
.Debug("Clearing disconnect timer");
479 clearTimeout(this._disconnTimer
);
480 this._disconnTimer
= null;
481 this._sock
.off('close'); // make sure we don't get a double event
486 if (oldstate
=== 'disconnected' || oldstate
=== 'failed') {
487 Util
.Error("Invalid transition from 'disconnected' or 'failed' to 'normal'");
494 // WebSocket.onopen transitions to 'ProtocolVersion'
498 this._disconnTimer
= setTimeout(function () {
499 this._fail("Disconnect timeout");
500 }.bind(this), this._disconnectTimeout
* 1000);
504 // WebSocket.onclose transitions to 'disconnected'
508 if (oldstate
=== 'disconnected') {
509 Util
.Error("Invalid transition from 'disconnected' to 'failed'");
510 } else if (oldstate
=== 'normal') {
511 Util
.Error("Error while connected.");
512 } else if (oldstate
=== 'init') {
513 Util
.Error("Error while initializing.");
516 // Make sure we transition to disconnected
517 setTimeout(function () {
518 this._updateState('disconnected');
524 // No state change action to take
527 if (oldstate
=== 'failed' && state
=== 'disconnected') {
528 this._onUpdateState(this, state
, oldstate
);
530 this._onUpdateState(this, state
, oldstate
, statusMsg
);
534 _fail: function (msg
) {
535 this._updateState('failed', msg
);
540 * Send a notification to the UI. Valid levels are:
541 * 'normal'|'warn'|'error'
543 * NOTE: Options could be added in the future.
544 * NOTE: If this function is called multiple times, remember that the
545 * interface could be only showing the latest notification.
547 _notification: function(msg
, level
, options
) {
552 Util
.Debug("Notification[" + level
+ "]:" + msg
);
555 Util
.Error("Invalid notification level: " + level
);
560 this._onNotification(this, msg
, level
, options
);
562 this._onNotification(this, msg
, level
);
566 _handle_message: function () {
567 if (this._sock
.rQlen() === 0) {
568 Util
.Warn("handle_message called on an empty receive queue");
572 switch (this._rfb_state
) {
575 Util
.Error("Got data while disconnected");
578 if (this._normal_msg() && this._sock
.rQlen() > 0) {
579 // true means we can continue processing
580 // Give other events a chance to run
581 if (this._msgTimer
=== null) {
582 Util
.Debug("More data to process, creating timer");
583 this._msgTimer
= setTimeout(function () {
584 this._msgTimer
= null;
585 this._handle_message();
588 Util
.Debug("More data to process, existing timer");
598 _handleKeyPress: function (keyevent
) {
599 if (this._view_only
) { return; } // View only, skip keyboard, events
601 var down
= (keyevent
.type
== 'keydown');
602 if (this._qemuExtKeyEventSupported
) {
603 var scancode
= XtScancode
[keyevent
.code
];
605 var keysym
= keyevent
.keysym
;
606 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
608 Util
.Error('Unable to find a xt scancode for code = ' + keyevent
.code
);
611 keysym
= keyevent
.keysym
.keysym
;
612 RFB
.messages
.keyEvent(this._sock
, keysym
, down
);
616 _handleMouseButton: function (x
, y
, down
, bmask
) {
618 this._mouse_buttonMask
|= bmask
;
620 this._mouse_buttonMask
^= bmask
;
623 if (this._viewportDrag
) {
624 if (down
&& !this._viewportDragging
) {
625 this._viewportDragging
= true;
626 this._viewportDragPos
= {'x': x
, 'y': y
};
628 // Skip sending mouse events
631 this._viewportDragging
= false;
633 // If the viewport didn't actually move, then treat as a mouse click event
634 // Send the button down event here, as the button up event is sent at the end of this function
635 if (!this._viewportHasMoved
&& !this._view_only
) {
636 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
638 this._viewportHasMoved
= false;
642 if (this._view_only
) { return; } // View only, skip mouse events
644 if (this._rfb_state
!== "normal") { return; }
645 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
648 _handleMouseMove: function (x
, y
) {
649 if (this._viewportDragging
) {
650 var deltaX
= this._viewportDragPos
.x
- x
;
651 var deltaY
= this._viewportDragPos
.y
- y
;
653 // The goal is to trigger on a certain physical width, the
654 // devicePixelRatio brings us a bit closer but is not optimal.
655 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
657 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
658 Math
.abs(deltaY
) > dragThreshold
)) {
659 this._viewportHasMoved
= true;
661 this._viewportDragPos
= {'x': x
, 'y': y
};
662 this._display
.viewportChangePos(deltaX
, deltaY
);
665 // Skip sending mouse events
669 if (this._view_only
) { return; } // View only, skip mouse events
671 if (this._rfb_state
!== "normal") { return; }
672 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
677 _negotiate_protocol_version: function () {
678 if (this._sock
.rQlen() < 12) {
679 return this._fail("Incomplete protocol version");
682 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
683 Util
.Info("Server ProtocolVersion: " + sversion
);
686 case "000.000": // UltraVNC repeater
690 case "003.006": // UltraVNC
691 case "003.889": // Apple Remote Desktop
692 this._rfb_version
= 3.3;
695 this._rfb_version
= 3.7;
698 case "004.000": // Intel AMT KVM
699 case "004.001": // RealVNC 4.6
700 case "005.000": // RealVNC 5.3
701 this._rfb_version
= 3.8;
704 return this._fail("Invalid server version " + sversion
);
708 var repeaterID
= this._repeaterID
;
709 while (repeaterID
.length
< 250) {
712 this._sock
.send_string(repeaterID
);
716 if (this._rfb_version
> this._rfb_max_version
) {
717 this._rfb_version
= this._rfb_max_version
;
720 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
721 ".00" + ((this._rfb_version
* 10) % 10);
722 this._sock
.send_string("RFB " + cversion
+ "\n");
723 this._updateState('Security', 'Sent ProtocolVersion: ' + cversion
);
726 _negotiate_security: function () {
727 if (this._rfb_version
>= 3.7) {
728 // Server sends supported list, client decides
729 var num_types
= this._sock
.rQshift8();
730 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
732 if (num_types
=== 0) {
733 var strlen
= this._sock
.rQshift32();
734 var reason
= this._sock
.rQshiftStr(strlen
);
735 return this._fail("Security failure: " + reason
);
738 this._rfb_auth_scheme
= 0;
739 var types
= this._sock
.rQshiftBytes(num_types
);
740 Util
.Debug("Server security types: " + types
);
741 for (var i
= 0; i
< types
.length
; i
++) {
744 case 2: // VNC Authentication
747 if (types
[i
] > this._rfb_auth_scheme
) {
748 this._rfb_auth_scheme
= types
[i
];
756 if (this._rfb_auth_scheme
=== 0) {
757 return this._fail("Unsupported security types: " + types
);
760 this._sock
.send([this._rfb_auth_scheme
]);
763 if (this._sock
.rQwait("security scheme", 4)) { return false; }
764 this._rfb_auth_scheme
= this._sock
.rQshift32();
767 this._updateState('Authentication', 'Authenticating using scheme: ' + this._rfb_auth_scheme
);
768 return this._init_msg(); // jump to authentication
772 _negotiate_xvp_auth: function () {
773 var xvp_sep
= this._xvp_password_sep
;
774 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
775 if (xvp_auth
.length
< 3) {
776 var msg
= 'XVP credentials required (user' + xvp_sep
+
777 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
778 this._onPasswordRequired(this, msg
);
782 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
783 String
.fromCharCode(xvp_auth
[1].length
) +
786 this._sock
.send_string(xvp_auth_str
);
787 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
788 this._rfb_auth_scheme
= 2;
789 return this._negotiate_authentication();
792 _negotiate_std_vnc_auth: function () {
793 if (this._rfb_password
.length
=== 0) {
794 this._onPasswordRequired(this);
798 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
800 // TODO(directxman12): make genDES not require an Array
801 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
802 var response
= RFB
.genDES(this._rfb_password
, challenge
);
803 this._sock
.send(response
);
804 this._updateState("SecurityResult");
808 _negotiate_tight_tunnels: function (numTunnels
) {
809 var clientSupportedTunnelTypes
= {
810 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
812 var serverSupportedTunnelTypes
= {};
813 // receive tunnel capabilities
814 for (var i
= 0; i
< numTunnels
; i
++) {
815 var cap_code
= this._sock
.rQshift32();
816 var cap_vendor
= this._sock
.rQshiftStr(4);
817 var cap_signature
= this._sock
.rQshiftStr(8);
818 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
821 // choose the notunnel type
822 if (serverSupportedTunnelTypes
[0]) {
823 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
824 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
825 return this._fail("Client's tunnel type had the incorrect vendor or signature");
827 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
828 return false; // wait until we receive the sub auth count to continue
830 return this._fail("Server wanted tunnels, but doesn't support the notunnel type");
834 _negotiate_tight_auth: function () {
835 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
836 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
837 var numTunnels
= this._sock
.rQshift32();
838 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
840 this._rfb_tightvnc
= true;
842 if (numTunnels
> 0) {
843 this._negotiate_tight_tunnels(numTunnels
);
844 return false; // wait until we receive the sub auth to continue
848 // second pass, do the sub-auth negotiation
849 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
850 var subAuthCount
= this._sock
.rQshift32();
851 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
852 this._updateState('SecurityResult');
856 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
858 var clientSupportedTypes
= {
863 var serverSupportedTypes
= [];
865 for (var i
= 0; i
< subAuthCount
; i
++) {
866 var capNum
= this._sock
.rQshift32();
867 var capabilities
= this._sock
.rQshiftStr(12);
868 serverSupportedTypes
.push(capabilities
);
871 for (var authType
in clientSupportedTypes
) {
872 if (serverSupportedTypes
.indexOf(authType
) != -1) {
873 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
876 case 'STDVNOAUTH__': // no auth
877 this._updateState('SecurityResult');
879 case 'STDVVNCAUTH_': // VNC auth
880 this._rfb_auth_scheme
= 2;
881 return this._init_msg();
883 return this._fail("Unsupported tiny auth scheme: " + authType
);
888 return this._fail("No supported sub-auth types!");
891 _negotiate_authentication: function () {
892 switch (this._rfb_auth_scheme
) {
893 case 0: // connection failed
894 if (this._sock
.rQwait("auth reason", 4)) { return false; }
895 var strlen
= this._sock
.rQshift32();
896 var reason
= this._sock
.rQshiftStr(strlen
);
897 return this._fail("Auth failure: " + reason
);
900 if (this._rfb_version
>= 3.8) {
901 this._updateState('SecurityResult');
904 this._updateState('ClientInitialisation', "No auth required");
905 return this._init_msg();
908 return this._negotiate_xvp_auth();
910 case 2: // VNC authentication
911 return this._negotiate_std_vnc_auth();
913 case 16: // TightVNC Security Type
914 return this._negotiate_tight_auth();
917 return this._fail("Unsupported auth scheme: " + this._rfb_auth_scheme
);
921 _handle_security_result: function () {
922 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
923 switch (this._sock
.rQshift32()) {
925 this._updateState('ClientInitialisation', 'Authentication OK');
926 return this._init_msg();
928 if (this._rfb_version
>= 3.8) {
929 var length
= this._sock
.rQshift32();
930 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
931 var reason
= this._sock
.rQshiftStr(length
);
932 return this._fail(reason
);
934 return this._fail("Authentication failure");
938 return this._fail("Too many auth attempts");
940 return this._fail("Unknown SecurityResult");
944 _negotiate_server_init: function () {
945 if (this._sock
.rQwait("server initialization", 24)) { return false; }
948 this._fb_width
= this._sock
.rQshift16();
949 this._fb_height
= this._sock
.rQshift16();
950 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
953 var bpp
= this._sock
.rQshift8();
954 var depth
= this._sock
.rQshift8();
955 var big_endian
= this._sock
.rQshift8();
956 var true_color
= this._sock
.rQshift8();
958 var red_max
= this._sock
.rQshift16();
959 var green_max
= this._sock
.rQshift16();
960 var blue_max
= this._sock
.rQshift16();
961 var red_shift
= this._sock
.rQshift8();
962 var green_shift
= this._sock
.rQshift8();
963 var blue_shift
= this._sock
.rQshift8();
964 this._sock
.rQskipBytes(3); // padding
966 // NB(directxman12): we don't want to call any callbacks or print messages until
967 // *after* we're past the point where we could backtrack
969 /* Connection name/title */
970 var name_length = this._sock.rQshift32();
971 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
972 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
974 if (this._rfb_tightvnc) {
975 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
976 // In TightVNC mode, ServerInit message is extended
977 var numServerMessages = this._sock.rQshift16();
978 var numClientMessages = this._sock.rQshift16();
979 var numEncodings = this._sock.rQshift16();
980 this._sock.rQskipBytes(2); // padding
982 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
983 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
985 // we don't actually do anything with the capability information that TIGHT sends,
986 // so we just skip the all of this.
988 // TIGHT server message capabilities
989 this._sock.rQskipBytes(16 * numServerMessages);
991 // TIGHT client message capabilities
992 this._sock.rQskipBytes(16 * numClientMessages);
994 // TIGHT encoding capabilities
995 this._sock.rQskipBytes(16 * numEncodings);
998 // NB(directxman12): these are down here so that we don't run them multiple times
1000 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1001 ", bpp: " + bpp + ", depth: " + depth +
1002 ", big_endian: " + big_endian +
1003 ", true_color: " + true_color +
1004 ", red_max: " + red_max +
1005 ", green_max: " + green_max +
1006 ", blue_max: " + blue_max +
1007 ", red_shift: " + red_shift +
1008 ", green_shift: " + green_shift +
1009 ", blue_shift: " + blue_shift);
1011 if (big_endian !== 0) {
1012 Util.Warn("Server native endian is not little endian");
1015 if (red_shift !== 16) {
1016 Util.Warn("Server native red-shift is not 16");
1019 if (blue_shift !== 0) {
1020 Util.Warn("Server native blue-shift is not 0");
1023 // we're past the point where we could backtrack, so it's safe to call this
1024 this._onDesktopName(this, this._fb_name);
1026 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1027 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1028 this._true_color = false;
1031 this._display.set_true_color(this._true_color);
1032 this._display.resize(this._fb_width, this._fb_height);
1033 this._onFBResize(this, this._fb_width, this._fb_height);
1034 this._keyboard.grab();
1037 if (this._true_color) {
1045 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1046 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1047 RFB.messages.fbUpdateRequests(this._sock, false, this._display.getCleanDirtyReset(), this._fb_width, this._fb_height);
1049 this._timing.fbu_rt_start = (new Date()).getTime();
1050 this._timing.pixels = 0;
1052 if (this._encrypt) {
1053 this._updateState('normal', 'Connected (encrypted) to: ' + this._fb_name);
1055 this._updateState('normal', 'Connected (unencrypted) to: ' + this._fb_name);
1060 _init_msg: function () {
1061 switch (this._rfb_state) {
1062 case 'ProtocolVersion':
1063 return this._negotiate_protocol_version();
1066 return this._negotiate_security();
1068 case 'Authentication':
1069 return this._negotiate_authentication();
1071 case 'SecurityResult':
1072 return this._handle_security_result();
1074 case 'ClientInitialisation':
1075 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1076 this._updateState('ServerInitialisation', "Authentication OK");
1079 case 'ServerInitialisation':
1080 return this._negotiate_server_init();
1083 return this._fail("Unknown state: " + this._rfb_state);
1087 _handle_set_colour_map_msg: function () {
1088 Util.Debug("SetColorMapEntries");
1089 this._sock.rQskip8(); // Padding
1091 var first_colour = this._sock.rQshift16();
1092 var num_colours = this._sock.rQshift16();
1093 if (this._sock.rQwait('SetColorMapEntries', num_colours * 6, 6)) { return false; }
1095 for (var c = 0; c < num_colours; c++) {
1096 var red = parseInt(this._sock.rQshift16() / 256, 10);
1097 var green = parseInt(this._sock.rQshift16() / 256, 10);
1098 var blue = parseInt(this._sock.rQshift16() / 256, 10);
1099 this._display.set_colourMap([blue, green, red], first_colour + c);
1101 Util.Debug("colourMap: " + this._display.get_colourMap());
1102 Util.Info("Registered " + num_colours + " colourMap entries");
1107 _handle_server_cut_text: function () {
1108 Util.Debug("ServerCutText");
1109 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1110 this._sock.rQskipBytes(3); // Padding
1111 var length = this._sock.rQshift32();
1112 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
1114 var text = this._sock.rQshiftStr(length);
1115 this._onClipboard(this, text);
1120 _handle_server_fence_msg: function() {
1121 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1122 this._sock.rQskipBytes(3); // Padding
1123 var flags = this._sock.rQshift32();
1124 var length = this._sock.rQshift8();
1126 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
1129 Util.Warn("Bad payload length (" + length + ") in fence response");
1133 var payload = this._sock.rQshiftStr(length);
1135 this._supportsFence = true;
1140 * (1<<0) - BlockBefore
1141 * (1<<1) - BlockAfter
1146 if (!(flags
& (1<<31))) {
1147 return this._fail("Unexpected fence response");
1150 // Filter out unsupported flags
1151 // FIXME: support syncNext
1152 flags
&= (1<<0) | (1<<1);
1154 // BlockBefore and BlockAfter are automatically handled by
1155 // the fact that we process each incoming message
1157 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1162 _handle_xvp_msg: function () {
1163 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1164 this._sock
.rQskip8(); // Padding
1165 var xvp_ver
= this._sock
.rQshift8();
1166 var xvp_msg
= this._sock
.rQshift8();
1170 Util
.Error("Operation Failed");
1171 this._notification("XVP Operation Failed", 'error');
1174 this._rfb_xvp_ver
= xvp_ver
;
1175 Util
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1176 this._onXvpInit(this._rfb_xvp_ver
);
1179 this._fail("Disconnected: illegal server XVP message " + xvp_msg
);
1186 _normal_msg: function () {
1189 if (this._FBU
.rects
> 0) {
1192 msg_type
= this._sock
.rQshift8();
1196 case 0: // FramebufferUpdate
1197 var ret
= this._framebufferUpdate();
1199 RFB
.messages
.fbUpdateRequests(this._sock
,
1200 this._enabledContinuousUpdates
,
1201 this._display
.getCleanDirtyReset(),
1202 this._fb_width
, this._fb_height
);
1206 case 1: // SetColorMapEntries
1207 return this._handle_set_colour_map_msg();
1214 case 3: // ServerCutText
1215 return this._handle_server_cut_text();
1217 case 150: // EndOfContinuousUpdates
1218 var first
= !(this._supportsContinuousUpdates
);
1219 this._supportsContinuousUpdates
= true;
1220 this._enabledContinuousUpdates
= false;
1222 this._enabledContinuousUpdates
= true;
1223 this._updateContinuousUpdates();
1224 Util
.Info("Enabling continuous updates.");
1226 // FIXME: We need to send a framebufferupdaterequest here
1227 // if we add support for turning off continuous updates
1231 case 248: // ServerFence
1232 return this._handle_server_fence_msg();
1235 return this._handle_xvp_msg();
1238 this._fail("Disconnected: illegal server message type " + msg_type
);
1239 Util
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1244 _framebufferUpdate: function () {
1248 if (this._FBU
.rects
=== 0) {
1249 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1250 this._sock
.rQskip8(); // Padding
1251 this._FBU
.rects
= this._sock
.rQshift16();
1252 this._FBU
.bytes
= 0;
1253 this._timing
.cur_fbu
= 0;
1254 if (this._timing
.fbu_rt_start
> 0) {
1255 now
= (new Date()).getTime();
1256 Util
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1260 while (this._FBU
.rects
> 0) {
1261 if (this._rfb_state
!== "normal") { return false; }
1263 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1264 if (this._FBU
.bytes
=== 0) {
1265 if (this._sock
.rQwait("rect header", 12)) { return false; }
1266 /* New FramebufferUpdate */
1268 var hdr
= this._sock
.rQshiftBytes(12);
1269 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1270 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1271 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1272 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1273 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1274 (hdr
[10] << 8) + hdr
[11], 10);
1276 this._onFBUReceive(this,
1277 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1278 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1279 'encoding': this._FBU
.encoding
,
1280 'encodingName': this._encNames
[this._FBU
.encoding
]});
1282 if (!this._encNames
[this._FBU
.encoding
]) {
1283 this._fail("Disconnected: unsupported encoding " +
1284 this._FBU
.encoding
);
1289 this._timing
.last_fbu
= (new Date()).getTime();
1291 ret
= this._encHandlers
[this._FBU
.encoding
]();
1293 now
= (new Date()).getTime();
1294 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1297 this._encStats
[this._FBU
.encoding
][0]++;
1298 this._encStats
[this._FBU
.encoding
][1]++;
1299 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1302 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1303 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1304 this._timing
.fbu_rt_start
> 0) {
1305 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1306 this._timing
.full_fbu_cnt
++;
1307 Util
.Info("Timing of full FBU, curr: " +
1308 this._timing
.cur_fbu
+ ", total: " +
1309 this._timing
.full_fbu_total
+ ", cnt: " +
1310 this._timing
.full_fbu_cnt
+ ", avg: " +
1311 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1314 if (this._timing
.fbu_rt_start
> 0) {
1315 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1316 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1317 this._timing
.fbu_rt_cnt
++;
1318 Util
.Info("full FBU round-trip, cur: " +
1319 fbu_rt_diff
+ ", total: " +
1320 this._timing
.fbu_rt_total
+ ", cnt: " +
1321 this._timing
.fbu_rt_cnt
+ ", avg: " +
1322 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1323 this._timing
.fbu_rt_start
= 0;
1327 if (!ret
) { return ret
; } // need more data
1330 this._onFBUComplete(this,
1331 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1332 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1333 'encoding': this._FBU
.encoding
,
1334 'encodingName': this._encNames
[this._FBU
.encoding
]});
1336 return true; // We finished this FBU
1339 _updateContinuousUpdates: function() {
1340 if (!this._enabledContinuousUpdates
) { return; }
1342 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1343 this._fb_width
, this._fb_height
);
1347 Util
.make_properties(RFB
, [
1348 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1349 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1350 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1351 ['true_color', 'rw', 'bool'], // Request true color pixel data
1352 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1353 ['shared', 'rw', 'bool'], // Request shared mode
1354 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1355 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1356 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1357 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1358 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1359 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1361 // Callback functions
1362 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate, statusMsg): RFB state update/change
1363 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1364 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1365 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1366 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1367 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1368 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1369 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1370 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1371 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1374 RFB
.prototype.set_local_cursor = function (cursor
) {
1375 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1376 this._local_cursor
= false;
1377 this._display
.disableLocalCursor(); //Only show server-side cursor
1379 if (this._display
.get_cursor_uri()) {
1380 this._local_cursor
= true;
1382 Util
.Warn("Browser does not support local cursor");
1383 this._display
.disableLocalCursor();
1388 RFB
.prototype.get_display = function () { return this._display
; };
1389 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1390 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1394 keyEvent: function (sock
, keysym
, down
) {
1395 var buff
= sock
._sQ
;
1396 var offset
= sock
._sQlen
;
1398 buff
[offset
] = 4; // msg-type
1399 buff
[offset
+ 1] = down
;
1401 buff
[offset
+ 2] = 0;
1402 buff
[offset
+ 3] = 0;
1404 buff
[offset
+ 4] = (keysym
>> 24);
1405 buff
[offset
+ 5] = (keysym
>> 16);
1406 buff
[offset
+ 6] = (keysym
>> 8);
1407 buff
[offset
+ 7] = keysym
;
1413 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1414 function getRFBkeycode(xt_scancode
) {
1415 var upperByte
= (keycode
>> 8);
1416 var lowerByte
= (keycode
& 0x00ff);
1417 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1418 lowerByte
= lowerByte
| 0x80;
1424 var buff
= sock
._sQ
;
1425 var offset
= sock
._sQlen
;
1427 buff
[offset
] = 255; // msg-type
1428 buff
[offset
+ 1] = 0; // sub msg-type
1430 buff
[offset
+ 2] = (down
>> 8);
1431 buff
[offset
+ 3] = down
;
1433 buff
[offset
+ 4] = (keysym
>> 24);
1434 buff
[offset
+ 5] = (keysym
>> 16);
1435 buff
[offset
+ 6] = (keysym
>> 8);
1436 buff
[offset
+ 7] = keysym
;
1438 var RFBkeycode
= getRFBkeycode(keycode
);
1440 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1441 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1442 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1443 buff
[offset
+ 11] = RFBkeycode
;
1449 pointerEvent: function (sock
, x
, y
, mask
) {
1450 var buff
= sock
._sQ
;
1451 var offset
= sock
._sQlen
;
1453 buff
[offset
] = 5; // msg-type
1455 buff
[offset
+ 1] = mask
;
1457 buff
[offset
+ 2] = x
>> 8;
1458 buff
[offset
+ 3] = x
;
1460 buff
[offset
+ 4] = y
>> 8;
1461 buff
[offset
+ 5] = y
;
1467 // TODO(directxman12): make this unicode compatible?
1468 clientCutText: function (sock
, text
) {
1469 var buff
= sock
._sQ
;
1470 var offset
= sock
._sQlen
;
1472 buff
[offset
] = 6; // msg-type
1474 buff
[offset
+ 1] = 0; // padding
1475 buff
[offset
+ 2] = 0; // padding
1476 buff
[offset
+ 3] = 0; // padding
1478 var n
= text
.length
;
1480 buff
[offset
+ 4] = n
>> 24;
1481 buff
[offset
+ 5] = n
>> 16;
1482 buff
[offset
+ 6] = n
>> 8;
1483 buff
[offset
+ 7] = n
;
1485 for (var i
= 0; i
< n
; i
++) {
1486 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1489 sock
._sQlen
+= 8 + n
;
1493 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1494 var buff
= sock
._sQ
;
1495 var offset
= sock
._sQlen
;
1497 buff
[offset
] = 251; // msg-type
1498 buff
[offset
+ 1] = 0; // padding
1499 buff
[offset
+ 2] = width
>> 8; // width
1500 buff
[offset
+ 3] = width
;
1501 buff
[offset
+ 4] = height
>> 8; // height
1502 buff
[offset
+ 5] = height
;
1504 buff
[offset
+ 6] = 1; // number-of-screens
1505 buff
[offset
+ 7] = 0; // padding
1508 buff
[offset
+ 8] = id
>> 24; // id
1509 buff
[offset
+ 9] = id
>> 16;
1510 buff
[offset
+ 10] = id
>> 8;
1511 buff
[offset
+ 11] = id
;
1512 buff
[offset
+ 12] = 0; // x-position
1513 buff
[offset
+ 13] = 0;
1514 buff
[offset
+ 14] = 0; // y-position
1515 buff
[offset
+ 15] = 0;
1516 buff
[offset
+ 16] = width
>> 8; // width
1517 buff
[offset
+ 17] = width
;
1518 buff
[offset
+ 18] = height
>> 8; // height
1519 buff
[offset
+ 19] = height
;
1520 buff
[offset
+ 20] = flags
>> 24; // flags
1521 buff
[offset
+ 21] = flags
>> 16;
1522 buff
[offset
+ 22] = flags
>> 8;
1523 buff
[offset
+ 23] = flags
;
1529 clientFence: function (sock
, flags
, payload
) {
1530 var buff
= sock
._sQ
;
1531 var offset
= sock
._sQlen
;
1533 buff
[offset
] = 248; // msg-type
1535 buff
[offset
+ 1] = 0; // padding
1536 buff
[offset
+ 2] = 0; // padding
1537 buff
[offset
+ 3] = 0; // padding
1539 buff
[offset
+ 4] = flags
>> 24; // flags
1540 buff
[offset
+ 5] = flags
>> 16;
1541 buff
[offset
+ 6] = flags
>> 8;
1542 buff
[offset
+ 7] = flags
;
1544 var n
= payload
.length
;
1546 buff
[offset
+ 8] = n
; // length
1548 for (var i
= 0; i
< n
; i
++) {
1549 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1552 sock
._sQlen
+= 9 + n
;
1556 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1557 var buff
= sock
._sQ
;
1558 var offset
= sock
._sQlen
;
1560 buff
[offset
] = 150; // msg-type
1561 buff
[offset
+ 1] = enable
; // enable-flag
1563 buff
[offset
+ 2] = x
>> 8; // x
1564 buff
[offset
+ 3] = x
;
1565 buff
[offset
+ 4] = y
>> 8; // y
1566 buff
[offset
+ 5] = y
;
1567 buff
[offset
+ 6] = width
>> 8; // width
1568 buff
[offset
+ 7] = width
;
1569 buff
[offset
+ 8] = height
>> 8; // height
1570 buff
[offset
+ 9] = height
;
1576 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1577 var buff
= sock
._sQ
;
1578 var offset
= sock
._sQlen
;
1580 buff
[offset
] = 0; // msg-type
1582 buff
[offset
+ 1] = 0; // padding
1583 buff
[offset
+ 2] = 0; // padding
1584 buff
[offset
+ 3] = 0; // padding
1586 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1587 buff
[offset
+ 5] = depth
* 8; // depth
1588 buff
[offset
+ 6] = 0; // little-endian
1589 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1591 buff
[offset
+ 8] = 0; // red-max
1592 buff
[offset
+ 9] = 255; // red-max
1594 buff
[offset
+ 10] = 0; // green-max
1595 buff
[offset
+ 11] = 255; // green-max
1597 buff
[offset
+ 12] = 0; // blue-max
1598 buff
[offset
+ 13] = 255; // blue-max
1600 buff
[offset
+ 14] = 16; // red-shift
1601 buff
[offset
+ 15] = 8; // green-shift
1602 buff
[offset
+ 16] = 0; // blue-shift
1604 buff
[offset
+ 17] = 0; // padding
1605 buff
[offset
+ 18] = 0; // padding
1606 buff
[offset
+ 19] = 0; // padding
1612 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1613 var buff
= sock
._sQ
;
1614 var offset
= sock
._sQlen
;
1616 buff
[offset
] = 2; // msg-type
1617 buff
[offset
+ 1] = 0; // padding
1619 // offset + 2 and offset + 3 are encoding count
1621 var i
, j
= offset
+ 4, cnt
= 0;
1622 for (i
= 0; i
< encodings
.length
; i
++) {
1623 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1624 Util
.Debug("Skipping Cursor pseudo-encoding");
1625 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1626 // TODO: remove this when we have tight+non-true-color
1627 Util
.Warn("Skipping tight as it is only supported with true color");
1629 var enc
= encodings
[i
][1];
1630 buff
[j
] = enc
>> 24;
1631 buff
[j
+ 1] = enc
>> 16;
1632 buff
[j
+ 2] = enc
>> 8;
1640 buff
[offset
+ 2] = cnt
>> 8;
1641 buff
[offset
+ 3] = cnt
;
1643 sock
._sQlen
+= j
- offset
;
1647 fbUpdateRequests: function (sock
, onlyNonInc
, cleanDirty
, fb_width
, fb_height
) {
1648 var offsetIncrement
= 0;
1650 var cb
= cleanDirty
.cleanBox
;
1652 if (!onlyNonInc
&& (cb
.w
> 0 && cb
.h
> 0)) {
1653 w
= typeof cb
.w
=== "undefined" ? fb_width
: cb
.w
;
1654 h
= typeof cb
.h
=== "undefined" ? fb_height
: cb
.h
;
1655 // Request incremental for clean box
1656 RFB
.messages
.fbUpdateRequest(sock
, 1, cb
.x
, cb
.y
, w
, h
);
1659 for (var i
= 0; i
< cleanDirty
.dirtyBoxes
.length
; i
++) {
1660 var db
= cleanDirty
.dirtyBoxes
[i
];
1661 // Force all (non-incremental) for dirty box
1662 w
= typeof db
.w
=== "undefined" ? fb_width
: db
.w
;
1663 h
= typeof db
.h
=== "undefined" ? fb_height
: db
.h
;
1664 RFB
.messages
.fbUpdateRequest(sock
, 0, db
.x
, db
.y
, w
, h
);
1668 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1669 var buff
= sock
._sQ
;
1670 var offset
= sock
._sQlen
;
1672 if (typeof(x
) === "undefined") { x
= 0; }
1673 if (typeof(y
) === "undefined") { y
= 0; }
1675 buff
[offset
] = 3; // msg-type
1676 buff
[offset
+ 1] = incremental
;
1678 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1679 buff
[offset
+ 3] = x
& 0xFF;
1681 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1682 buff
[offset
+ 5] = y
& 0xFF;
1684 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1685 buff
[offset
+ 7] = w
& 0xFF;
1687 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1688 buff
[offset
+ 9] = h
& 0xFF;
1695 RFB
.genDES = function (password
, challenge
) {
1697 for (var i
= 0; i
< password
.length
; i
++) {
1698 passwd
.push(password
.charCodeAt(i
));
1700 return (new DES(passwd
)).encrypt(challenge
);
1703 RFB
.extract_data_uri = function (arr
) {
1704 return ";base64," + Base64
.encode(arr
);
1707 RFB
.encodingHandlers
= {
1709 if (this._FBU
.lines
=== 0) {
1710 this._FBU
.lines
= this._FBU
.height
;
1713 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1714 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1715 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1716 var curr_height
= Math
.min(this._FBU
.lines
,
1717 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1718 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1719 curr_height
, this._sock
.get_rQ(),
1720 this._sock
.get_rQi());
1721 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1722 this._FBU
.lines
-= curr_height
;
1724 if (this._FBU
.lines
> 0) {
1725 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1728 this._FBU
.bytes
= 0;
1734 COPYRECT: function () {
1735 this._FBU
.bytes
= 4;
1736 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1737 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1738 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1742 this._FBU
.bytes
= 0;
1748 if (this._FBU
.subrects
=== 0) {
1749 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1750 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1751 this._FBU
.subrects
= this._sock
.rQshift32();
1752 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1753 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1756 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1757 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1758 var x
= this._sock
.rQshift16();
1759 var y
= this._sock
.rQshift16();
1760 var width
= this._sock
.rQshift16();
1761 var height
= this._sock
.rQshift16();
1762 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1763 this._FBU
.subrects
--;
1766 if (this._FBU
.subrects
> 0) {
1767 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1768 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1771 this._FBU
.bytes
= 0;
1777 HEXTILE: function () {
1778 var rQ
= this._sock
.get_rQ();
1779 var rQi
= this._sock
.get_rQi();
1781 if (this._FBU
.tiles
=== 0) {
1782 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1783 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1784 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1785 this._FBU
.tiles
= this._FBU
.total_tiles
;
1788 while (this._FBU
.tiles
> 0) {
1789 this._FBU
.bytes
= 1;
1790 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1791 var subencoding
= rQ
[rQi
]; // Peek
1792 if (subencoding
> 30) { // Raw
1793 this._fail("Disconnected: illegal hextile subencoding " + subencoding
);
1798 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1799 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1800 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1801 var x
= this._FBU
.x
+ tile_x
* 16;
1802 var y
= this._FBU
.y
+ tile_y
* 16;
1803 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1804 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1806 // Figure out how much we are expecting
1807 if (subencoding
& 0x01) { // Raw
1808 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1810 if (subencoding
& 0x02) { // Background
1811 this._FBU
.bytes
+= this._fb_Bpp
;
1813 if (subencoding
& 0x04) { // Foreground
1814 this._FBU
.bytes
+= this._fb_Bpp
;
1816 if (subencoding
& 0x08) { // AnySubrects
1817 this._FBU
.bytes
++; // Since we aren't shifting it off
1818 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1819 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1820 if (subencoding
& 0x10) { // SubrectsColoured
1821 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1823 this._FBU
.bytes
+= subrects
* 2;
1828 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1830 // We know the encoding and have a whole tile
1831 this._FBU
.subencoding
= rQ
[rQi
];
1833 if (this._FBU
.subencoding
=== 0) {
1834 if (this._FBU
.lastsubencoding
& 0x01) {
1835 // Weird: ignore blanks are RAW
1836 Util
.Debug(" Ignoring blank after RAW");
1838 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1840 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1841 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1842 rQi
+= this._FBU
.bytes
- 1;
1844 if (this._FBU
.subencoding
& 0x02) { // Background
1845 if (this._fb_Bpp
== 1) {
1846 this._FBU
.background
= rQ
[rQi
];
1849 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1851 rQi
+= this._fb_Bpp
;
1853 if (this._FBU
.subencoding
& 0x04) { // Foreground
1854 if (this._fb_Bpp
== 1) {
1855 this._FBU
.foreground
= rQ
[rQi
];
1857 // this._fb_Bpp is 4
1858 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1860 rQi
+= this._fb_Bpp
;
1863 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1864 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1868 for (var s
= 0; s
< subrects
; s
++) {
1870 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1871 if (this._fb_Bpp
=== 1) {
1875 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1877 rQi
+= this._fb_Bpp
;
1879 color
= this._FBU
.foreground
;
1884 var sy
= (xy
& 0x0f);
1888 var sw
= (wh
>> 4) + 1;
1889 var sh
= (wh
& 0x0f) + 1;
1891 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1894 this._display
.finishTile();
1896 this._sock
.set_rQi(rQi
);
1897 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1898 this._FBU
.bytes
= 0;
1902 if (this._FBU
.tiles
=== 0) {
1909 getTightCLength: function (arr
) {
1910 var header
= 1, data
= 0;
1911 data
+= arr
[0] & 0x7f;
1912 if (arr
[0] & 0x80) {
1914 data
+= (arr
[1] & 0x7f) << 7;
1915 if (arr
[1] & 0x80) {
1917 data
+= arr
[2] << 14;
1920 return [header
, data
];
1923 display_tight: function (isTightPNG
) {
1924 if (this._fb_depth
=== 1) {
1925 this._fail("Tight protocol handler only implements true color mode");
1928 this._FBU
.bytes
= 1; // compression-control byte
1929 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1931 var checksum = function (data
) {
1933 for (var i
= 0; i
< data
.length
; i
++) {
1935 if (sum
> 65536) sum
-= 65536;
1940 var resetStreams
= 0;
1942 var decompress = function (data
, expected
) {
1943 for (var i
= 0; i
< 4; i
++) {
1944 if ((resetStreams
>> i
) & 1) {
1945 this._FBU
.zlibs
[i
].reset();
1946 Util
.Info("Reset zlib stream " + i
);
1950 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1951 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
1952 /*if (uncompressed.status !== 0) {
1953 Util.Error("Invalid data in zlib stream");
1956 //return uncompressed.data;
1957 return uncompressed
;
1960 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
1961 // Convert indexed (palette based) image data to RGB
1962 // TODO: reduce number of calculations inside loop
1963 var dest
= this._destBuff
;
1964 var w
= Math
.floor((width
+ 7) / 8);
1965 var w1
= Math
.floor(width
/ 8);
1967 /*for (var y = 0; y < height; y++) {
1969 var yoffset = y * width;
1970 var ybitoffset = y * w;
1971 var xoffset, targetbyte;
1972 for (x = 0; x < w1; x++) {
1973 xoffset = yoffset + x * 8;
1974 targetbyte = data[ybitoffset + x];
1975 for (b = 7; b >= 0; b--) {
1976 dp = (xoffset + 7 - b) * 3;
1977 sp = (targetbyte >> b & 1) * 3;
1978 dest[dp] = palette[sp];
1979 dest[dp + 1] = palette[sp + 1];
1980 dest[dp + 2] = palette[sp + 2];
1984 xoffset = yoffset + x * 8;
1985 targetbyte = data[ybitoffset + x];
1986 for (b = 7; b >= 8 - width % 8; b--) {
1987 dp = (xoffset + 7 - b) * 3;
1988 sp = (targetbyte >> b & 1) * 3;
1989 dest[dp] = palette[sp];
1990 dest[dp + 1] = palette[sp + 1];
1991 dest[dp + 2] = palette[sp + 2];
1995 for (var y
= 0; y
< height
; y
++) {
1997 for (x
= 0; x
< w1
; x
++) {
1998 for (b
= 7; b
>= 0; b
--) {
1999 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2000 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2001 dest
[dp
] = palette
[sp
];
2002 dest
[dp
+ 1] = palette
[sp
+ 1];
2003 dest
[dp
+ 2] = palette
[sp
+ 2];
2008 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2009 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2010 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2011 dest
[dp
] = palette
[sp
];
2012 dest
[dp
+ 1] = palette
[sp
+ 1];
2013 dest
[dp
+ 2] = palette
[sp
+ 2];
2021 var indexedToRGBX = function (data
, palette
, width
, height
) {
2022 // Convert indexed (palette based) image data to RGB
2023 var dest
= this._destBuff
;
2024 var total
= width
* height
* 4;
2025 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2026 var sp
= data
[j
] * 3;
2027 dest
[i
] = palette
[sp
];
2028 dest
[i
+ 1] = palette
[sp
+ 1];
2029 dest
[i
+ 2] = palette
[sp
+ 2];
2036 var rQi
= this._sock
.get_rQi();
2037 var rQ
= this._sock
.rQwhole();
2039 var cl_header
, cl_data
;
2041 var handlePalette = function () {
2042 var numColors
= rQ
[rQi
+ 2] + 1;
2043 var paletteSize
= numColors
* this._fb_depth
;
2044 this._FBU
.bytes
+= paletteSize
;
2045 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2047 var bpp
= (numColors
<= 2) ? 1 : 8;
2048 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2050 if (rowSize
* this._FBU
.height
< 12) {
2053 cl_data
= rowSize
* this._FBU
.height
;
2054 //clength = [0, rowSize * this._FBU.height];
2056 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2057 var cl_offset
= rQi
+ 3 + paletteSize
;
2060 cl_data
+= rQ
[cl_offset
] & 0x7f;
2061 if (rQ
[cl_offset
] & 0x80) {
2063 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2064 if (rQ
[cl_offset
+ 1] & 0x80) {
2066 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2069 // end inline getTightCLength
2072 this._FBU
.bytes
+= cl_header
+ cl_data
;
2073 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2075 // Shift ctl, filter id, num colors, palette entries, and clength off
2076 this._sock
.rQskipBytes(3);
2077 //var palette = this._sock.rQshiftBytes(paletteSize);
2078 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2079 this._sock
.rQskipBytes(cl_header
);
2082 data
= this._sock
.rQshiftBytes(cl_data
);
2084 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2087 // Convert indexed (palette based) image data to RGB
2089 if (numColors
== 2) {
2090 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2091 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2093 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2094 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2101 var handleCopy = function () {
2103 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2104 if (uncompressedSize
< 12) {
2107 cl_data
= uncompressedSize
;
2109 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2110 var cl_offset
= rQi
+ 1;
2113 cl_data
+= rQ
[cl_offset
] & 0x7f;
2114 if (rQ
[cl_offset
] & 0x80) {
2116 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2117 if (rQ
[cl_offset
+ 1] & 0x80) {
2119 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2122 // end inline getTightCLength
2124 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2125 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2127 // Shift ctl, clength off
2128 this._sock
.rQshiftBytes(1 + cl_header
);
2131 data
= this._sock
.rQshiftBytes(cl_data
);
2133 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2136 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2141 var ctl
= this._sock
.rQpeek8();
2143 // Keep tight reset bits
2144 resetStreams
= ctl
& 0xF;
2146 // Figure out filter
2148 streamId
= ctl
& 0x3;
2150 if (ctl
=== 0x08) cmode
= "fill";
2151 else if (ctl
=== 0x09) cmode
= "jpeg";
2152 else if (ctl
=== 0x0A) cmode
= "png";
2153 else if (ctl
& 0x04) cmode
= "filter";
2154 else if (ctl
< 0x04) cmode
= "copy";
2155 else return this._fail("Illegal tight compression received, ctl: " + ctl
);
2157 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2158 return this._fail("filter/copy received in tightPNG mode");
2162 // fill use fb_depth because TPIXELs drop the padding byte
2163 case "fill": // TPIXEL
2164 this._FBU
.bytes
+= this._fb_depth
;
2166 case "jpeg": // max clength
2167 this._FBU
.bytes
+= 3;
2169 case "png": // max clength
2170 this._FBU
.bytes
+= 3;
2172 case "filter": // filter id + num colors if palette
2173 this._FBU
.bytes
+= 2;
2179 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2181 // Determine FBU.bytes
2185 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);
2186 this._sock
.rQskipBytes(4);
2190 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2191 var cl_offset
= rQi
+ 1;
2194 cl_data
+= rQ
[cl_offset
] & 0x7f;
2195 if (rQ
[cl_offset
] & 0x80) {
2197 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2198 if (rQ
[cl_offset
+ 1] & 0x80) {
2200 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2203 // end inline getTightCLength
2204 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2205 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2207 // We have everything, render it
2208 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2209 var img
= new Image();
2210 img
.src
= "data: image/" + cmode
+
2211 RFB
.extract_data_uri(this._sock
.rQshiftBytes(cl_data
));
2212 this._display
.renderQ_push({
2221 var filterId
= rQ
[rQi
+ 1];
2222 if (filterId
=== 1) {
2223 if (!handlePalette()) { return false; }
2225 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2226 // Filter 2, Gradient is valid but not use if jpeg is enabled
2227 this._fail("Unsupported tight subencoding received, filter: " + filterId
);
2231 if (!handleCopy()) { return false; }
2236 this._FBU
.bytes
= 0;
2242 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2243 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2245 last_rect: function () {
2246 this._FBU
.rects
= 0;
2250 handle_FB_resize: function () {
2251 this._fb_width
= this._FBU
.width
;
2252 this._fb_height
= this._FBU
.height
;
2253 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2254 this._display
.resize(this._fb_width
, this._fb_height
);
2255 this._onFBResize(this, this._fb_width
, this._fb_height
);
2256 this._timing
.fbu_rt_start
= (new Date()).getTime();
2257 this._updateContinuousUpdates();
2259 this._FBU
.bytes
= 0;
2260 this._FBU
.rects
-= 1;
2264 ExtendedDesktopSize: function () {
2265 this._FBU
.bytes
= 1;
2266 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2268 this._supportsSetDesktopSize
= true;
2269 var number_of_screens
= this._sock
.rQpeek8();
2271 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2272 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2274 this._sock
.rQskipBytes(1); // number-of-screens
2275 this._sock
.rQskipBytes(3); // padding
2277 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2278 // Save the id and flags of the first screen
2280 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2281 this._sock
.rQskipBytes(2); // x-position
2282 this._sock
.rQskipBytes(2); // y-position
2283 this._sock
.rQskipBytes(2); // width
2284 this._sock
.rQskipBytes(2); // height
2285 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2287 this._sock
.rQskipBytes(16);
2292 * The x-position indicates the reason for the change:
2294 * 0 - server resized on its own
2295 * 1 - this client requested the resize
2296 * 2 - another client requested the resize
2299 // We need to handle errors when we requested the resize.
2300 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2302 // The y-position indicates the status code from the server
2303 switch (this._FBU
.y
) {
2305 msg
= "Resize is administratively prohibited";
2308 msg
= "Out of resources";
2311 msg
= "Invalid screen layout";
2314 msg
= "Unknown reason";
2317 this._notification("Server did not accept the resize request: "
2322 this._encHandlers
.handle_FB_resize();
2326 DesktopSize: function () {
2327 this._encHandlers
.handle_FB_resize();
2331 Cursor: function () {
2332 Util
.Debug(">> set_cursor");
2333 var x
= this._FBU
.x
; // hotspot-x
2334 var y
= this._FBU
.y
; // hotspot-y
2335 var w
= this._FBU
.width
;
2336 var h
= this._FBU
.height
;
2338 var pixelslength
= w
* h
* this._fb_Bpp
;
2339 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2341 this._FBU
.bytes
= pixelslength
+ masklength
;
2342 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2344 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2345 this._sock
.rQshiftBytes(masklength
),
2348 this._FBU
.bytes
= 0;
2351 Util
.Debug("<< set_cursor");
2355 QEMUExtendedKeyEvent: function () {
2358 var keyboardEvent
= document
.createEvent("keyboardEvent");
2359 if (keyboardEvent
.code
!== undefined) {
2360 this._qemuExtKeyEventSupported
= true;
2361 this._keyboard
.setQEMUVNCKeyboardHandler();
2365 JPEG_quality_lo: function () {
2366 Util
.Error("Server sent jpeg_quality pseudo-encoding");
2369 compress_lo: function () {
2370 Util
.Error("Server sent compress level pseudo-encoding");