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"
17 * import Websock from "./websock"
18 * import Base64 from "./base64";
19 * import DES from "./des";
20 * import KeyTable from "./keysym";
21 * import XtScancode from "./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 'onPasswordRequired': function () { }, // onPasswordRequired(rfb): VNC password is required
162 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
163 'onBell': function () { }, // onBell(rfb): RFB Bell message received
164 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
165 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
166 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
167 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
168 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
172 Util
.Debug(">> RFB.constructor");
174 // populate encHandlers with bound versions
175 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
176 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
179 // Create lookup tables based on encoding number
180 for (var i
= 0; i
< this._encodings
.length
; i
++) {
181 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
182 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
183 this._encStats
[this._encodings
[i
][1]] = [0, 0];
186 // NB: nothing that needs explicit teardown should be done
187 // before this point, since this can throw an exception
189 this._display
= new Display({target
: this._target
});
191 Util
.Error("Display exception: " + exc
);
195 this._keyboard
= new Keyboard({target
: this._focusContainer
,
196 onKeyPress
: this._handleKeyPress
.bind(this)});
198 this._mouse
= new Mouse({target
: this._target
,
199 onMouseButton
: this._handleMouseButton
.bind(this),
200 onMouseMove
: this._handleMouseMove
.bind(this),
201 notify
: this._keyboard
.sync
.bind(this._keyboard
)});
203 this._sock
= new Websock();
204 this._sock
.on('message', this._handle_message
.bind(this));
205 this._sock
.on('open', function () {
206 if (this._rfb_state
=== 'connect') {
207 this._updateState('ProtocolVersion', "Starting VNC handshake");
209 this._fail("Got unexpected WebSocket connection");
212 this._sock
.on('close', function (e
) {
213 Util
.Warn("WebSocket on-close event");
216 msg
= " (code: " + e
.code
;
218 msg
+= ", reason: " + e
.reason
;
222 if (this._rfb_state
=== 'disconnect') {
223 this._updateState('disconnected', 'VNC disconnected' + msg
);
224 } else if (this._rfb_state
=== 'ProtocolVersion') {
225 this._fail('Failed to connect to server' + msg
);
226 } else if (this._rfb_state
in {'failed': 1, 'disconnected': 1}) {
227 Util
.Error("Received onclose while disconnected" + msg
);
229 this._fail("Server disconnected" + msg
);
231 this._sock
.off('close');
233 this._sock
.on('error', function (e
) {
234 Util
.Warn("WebSocket on-error event");
239 var rmode
= this._display
.get_render_mode();
240 Util
.Info("Using native WebSockets");
241 this._updateState('loaded', 'noVNC ready: native WebSockets, ' + rmode
);
243 Util
.Debug("<< RFB.constructor");
249 connect: function (host
, port
, password
, path
) {
250 this._rfb_host
= host
;
251 this._rfb_port
= port
;
252 this._rfb_password
= (password
!== undefined) ? password
: "";
253 this._rfb_path
= (path
!== undefined) ? path
: "";
255 if (!this._rfb_host
|| !this._rfb_port
) {
256 return this._fail("Must set host and port");
259 this._updateState('connect');
263 disconnect: function () {
264 this._updateState('disconnect', 'Disconnecting');
265 this._sock
.off('error');
266 this._sock
.off('message');
267 this._sock
.off('open');
270 sendPassword: function (passwd
) {
271 this._rfb_password
= passwd
;
272 this._rfb_state
= 'Authentication';
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:
436 * password - waiting for password, not part of RFB
438 * ClientInitialization - not triggered by server message
439 * ServerInitialization (to normal)
441 _updateState: function (state
, statusMsg
) {
442 var oldstate
= this._rfb_state
;
444 if (state
=== oldstate
) {
445 // Already here, ignore
446 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
);
539 _handle_message: function () {
540 if (this._sock
.rQlen() === 0) {
541 Util
.Warn("handle_message called on an empty receive queue");
545 switch (this._rfb_state
) {
548 Util
.Error("Got data while disconnected");
551 if (this._normal_msg() && this._sock
.rQlen() > 0) {
552 // true means we can continue processing
553 // Give other events a chance to run
554 if (this._msgTimer
=== null) {
555 Util
.Debug("More data to process, creating timer");
556 this._msgTimer
= setTimeout(function () {
557 this._msgTimer
= null;
558 this._handle_message();
561 Util
.Debug("More data to process, existing timer");
571 _handleKeyPress: function (keyevent
) {
572 if (this._view_only
) { return; } // View only, skip keyboard, events
574 var down
= (keyevent
.type
== 'keydown');
575 if (this._qemuExtKeyEventSupported
) {
576 var scancode
= XtScancode
[keyevent
.code
];
578 var keysym
= keyevent
.keysym
;
579 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
581 Util
.Error('Unable to find a xt scancode for code = ' + keyevent
.code
);
584 keysym
= keyevent
.keysym
.keysym
;
585 RFB
.messages
.keyEvent(this._sock
, keysym
, down
);
589 _handleMouseButton: function (x
, y
, down
, bmask
) {
591 this._mouse_buttonMask
|= bmask
;
593 this._mouse_buttonMask
^= bmask
;
596 if (this._viewportDrag
) {
597 if (down
&& !this._viewportDragging
) {
598 this._viewportDragging
= true;
599 this._viewportDragPos
= {'x': x
, 'y': y
};
601 // Skip sending mouse events
604 this._viewportDragging
= false;
606 // If the viewport didn't actually move, then treat as a mouse click event
607 // Send the button down event here, as the button up event is sent at the end of this function
608 if (!this._viewportHasMoved
&& !this._view_only
) {
609 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
611 this._viewportHasMoved
= false;
615 if (this._view_only
) { return; } // View only, skip mouse events
617 if (this._rfb_state
!== "normal") { return; }
618 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
621 _handleMouseMove: function (x
, y
) {
622 if (this._viewportDragging
) {
623 var deltaX
= this._viewportDragPos
.x
- x
;
624 var deltaY
= this._viewportDragPos
.y
- y
;
626 // The goal is to trigger on a certain physical width, the
627 // devicePixelRatio brings us a bit closer but is not optimal.
628 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
630 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
631 Math
.abs(deltaY
) > dragThreshold
)) {
632 this._viewportHasMoved
= true;
634 this._viewportDragPos
= {'x': x
, 'y': y
};
635 this._display
.viewportChangePos(deltaX
, deltaY
);
638 // Skip sending mouse events
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
);
650 _negotiate_protocol_version: function () {
651 if (this._sock
.rQlen() < 12) {
652 return this._fail("Incomplete protocol version");
655 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
656 Util
.Info("Server ProtocolVersion: " + sversion
);
659 case "000.000": // UltraVNC repeater
663 case "003.006": // UltraVNC
664 case "003.889": // Apple Remote Desktop
665 this._rfb_version
= 3.3;
668 this._rfb_version
= 3.7;
671 case "004.000": // Intel AMT KVM
672 case "004.001": // RealVNC 4.6
673 this._rfb_version
= 3.8;
676 return this._fail("Invalid server version " + sversion
);
680 var repeaterID
= this._repeaterID
;
681 while (repeaterID
.length
< 250) {
684 this._sock
.send_string(repeaterID
);
688 if (this._rfb_version
> this._rfb_max_version
) {
689 this._rfb_version
= this._rfb_max_version
;
692 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
693 ".00" + ((this._rfb_version
* 10) % 10);
694 this._sock
.send_string("RFB " + cversion
+ "\n");
695 this._updateState('Security', 'Sent ProtocolVersion: ' + cversion
);
698 _negotiate_security: function () {
699 if (this._rfb_version
>= 3.7) {
700 // Server sends supported list, client decides
701 var num_types
= this._sock
.rQshift8();
702 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
704 if (num_types
=== 0) {
705 var strlen
= this._sock
.rQshift32();
706 var reason
= this._sock
.rQshiftStr(strlen
);
707 return this._fail("Security failure: " + reason
);
710 this._rfb_auth_scheme
= 0;
711 var types
= this._sock
.rQshiftBytes(num_types
);
712 Util
.Debug("Server security types: " + types
);
713 for (var i
= 0; i
< types
.length
; i
++) {
714 if (types
[i
] > this._rfb_auth_scheme
&& (types
[i
] <= 16 || types
[i
] == 22)) {
715 this._rfb_auth_scheme
= types
[i
];
719 if (this._rfb_auth_scheme
=== 0) {
720 return this._fail("Unsupported security types: " + types
);
723 this._sock
.send([this._rfb_auth_scheme
]);
726 if (this._sock
.rQwait("security scheme", 4)) { return false; }
727 this._rfb_auth_scheme
= this._sock
.rQshift32();
730 this._updateState('Authentication', 'Authenticating using scheme: ' + this._rfb_auth_scheme
);
731 return this._init_msg(); // jump to authentication
735 _negotiate_xvp_auth: function () {
736 var xvp_sep
= this._xvp_password_sep
;
737 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
738 if (xvp_auth
.length
< 3) {
739 this._updateState('password', 'XVP credentials required (user' + xvp_sep
+
740 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
);
741 this._onPasswordRequired(this);
745 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
746 String
.fromCharCode(xvp_auth
[1].length
) +
749 this._sock
.send_string(xvp_auth_str
);
750 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
751 this._rfb_auth_scheme
= 2;
752 return this._negotiate_authentication();
755 _negotiate_std_vnc_auth: function () {
756 if (this._rfb_password
.length
=== 0) {
757 // Notify via both callbacks since it's kind of
758 // an RFB state change and a UI interface issue
759 this._updateState('password', "Password Required");
760 this._onPasswordRequired(this);
764 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
766 // TODO(directxman12): make genDES not require an Array
767 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
768 var response
= RFB
.genDES(this._rfb_password
, challenge
);
769 this._sock
.send(response
);
770 this._updateState("SecurityResult");
774 _negotiate_tight_tunnels: function (numTunnels
) {
775 var clientSupportedTunnelTypes
= {
776 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
778 var serverSupportedTunnelTypes
= {};
779 // receive tunnel capabilities
780 for (var i
= 0; i
< numTunnels
; i
++) {
781 var cap_code
= this._sock
.rQshift32();
782 var cap_vendor
= this._sock
.rQshiftStr(4);
783 var cap_signature
= this._sock
.rQshiftStr(8);
784 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
787 // choose the notunnel type
788 if (serverSupportedTunnelTypes
[0]) {
789 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
790 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
791 return this._fail("Client's tunnel type had the incorrect vendor or signature");
793 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
794 return false; // wait until we receive the sub auth count to continue
796 return this._fail("Server wanted tunnels, but doesn't support the notunnel type");
800 _negotiate_tight_auth: function () {
801 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
802 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
803 var numTunnels
= this._sock
.rQshift32();
804 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
806 this._rfb_tightvnc
= true;
808 if (numTunnels
> 0) {
809 this._negotiate_tight_tunnels(numTunnels
);
810 return false; // wait until we receive the sub auth to continue
814 // second pass, do the sub-auth negotiation
815 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
816 var subAuthCount
= this._sock
.rQshift32();
817 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
819 var clientSupportedTypes
= {
824 var serverSupportedTypes
= [];
826 for (var i
= 0; i
< subAuthCount
; i
++) {
827 var capNum
= this._sock
.rQshift32();
828 var capabilities
= this._sock
.rQshiftStr(12);
829 serverSupportedTypes
.push(capabilities
);
832 for (var authType
in clientSupportedTypes
) {
833 if (serverSupportedTypes
.indexOf(authType
) != -1) {
834 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
837 case 'STDVNOAUTH__': // no auth
838 this._updateState('SecurityResult');
840 case 'STDVVNCAUTH_': // VNC auth
841 this._rfb_auth_scheme
= 2;
842 return this._init_msg();
844 return this._fail("Unsupported tiny auth scheme: " + authType
);
849 return this._fail("No supported sub-auth types!");
852 _negotiate_authentication: function () {
853 switch (this._rfb_auth_scheme
) {
854 case 0: // connection failed
855 if (this._sock
.rQwait("auth reason", 4)) { return false; }
856 var strlen
= this._sock
.rQshift32();
857 var reason
= this._sock
.rQshiftStr(strlen
);
858 return this._fail("Auth failure: " + reason
);
861 if (this._rfb_version
>= 3.8) {
862 this._updateState('SecurityResult');
865 this._updateState('ClientInitialisation', "No auth required");
866 return this._init_msg();
869 return this._negotiate_xvp_auth();
871 case 2: // VNC authentication
872 return this._negotiate_std_vnc_auth();
874 case 16: // TightVNC Security Type
875 return this._negotiate_tight_auth();
878 return this._fail("Unsupported auth scheme: " + this._rfb_auth_scheme
);
882 _handle_security_result: function () {
883 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
884 switch (this._sock
.rQshift32()) {
886 this._updateState('ClientInitialisation', 'Authentication OK');
887 return this._init_msg();
889 if (this._rfb_version
>= 3.8) {
890 var length
= this._sock
.rQshift32();
891 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
892 var reason
= this._sock
.rQshiftStr(length
);
893 return this._fail(reason
);
895 return this._fail("Authentication failure");
899 return this._fail("Too many auth attempts");
901 return this._fail("Unknown SecurityResult");
905 _negotiate_server_init: function () {
906 if (this._sock
.rQwait("server initialization", 24)) { return false; }
909 this._fb_width
= this._sock
.rQshift16();
910 this._fb_height
= this._sock
.rQshift16();
911 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
914 var bpp
= this._sock
.rQshift8();
915 var depth
= this._sock
.rQshift8();
916 var big_endian
= this._sock
.rQshift8();
917 var true_color
= this._sock
.rQshift8();
919 var red_max
= this._sock
.rQshift16();
920 var green_max
= this._sock
.rQshift16();
921 var blue_max
= this._sock
.rQshift16();
922 var red_shift
= this._sock
.rQshift8();
923 var green_shift
= this._sock
.rQshift8();
924 var blue_shift
= this._sock
.rQshift8();
925 this._sock
.rQskipBytes(3); // padding
927 // NB(directxman12): we don't want to call any callbacks or print messages until
928 // *after* we're past the point where we could backtrack
930 /* Connection name/title */
931 var name_length = this._sock.rQshift32();
932 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
933 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
935 if (this._rfb_tightvnc) {
936 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
937 // In TightVNC mode, ServerInit message is extended
938 var numServerMessages = this._sock.rQshift16();
939 var numClientMessages = this._sock.rQshift16();
940 var numEncodings = this._sock.rQshift16();
941 this._sock.rQskipBytes(2); // padding
943 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
944 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
946 // we don't actually do anything with the capability information that TIGHT sends,
947 // so we just skip the all of this.
949 // TIGHT server message capabilities
950 this._sock.rQskipBytes(16 * numServerMessages);
952 // TIGHT client message capabilities
953 this._sock.rQskipBytes(16 * numClientMessages);
955 // TIGHT encoding capabilities
956 this._sock.rQskipBytes(16 * numEncodings);
959 // NB(directxman12): these are down here so that we don't run them multiple times
961 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
962 ", bpp: " + bpp + ", depth: " + depth +
963 ", big_endian: " + big_endian +
964 ", true_color: " + true_color +
965 ", red_max: " + red_max +
966 ", green_max: " + green_max +
967 ", blue_max: " + blue_max +
968 ", red_shift: " + red_shift +
969 ", green_shift: " + green_shift +
970 ", blue_shift: " + blue_shift);
972 if (big_endian !== 0) {
973 Util.Warn("Server native endian is not little endian");
976 if (red_shift !== 16) {
977 Util.Warn("Server native red-shift is not 16");
980 if (blue_shift !== 0) {
981 Util.Warn("Server native blue-shift is not 0");
984 // we're past the point where we could backtrack, so it's safe to call this
985 this._onDesktopName(this, this._fb_name);
987 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
988 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
989 this._true_color = false;
992 this._display.set_true_color(this._true_color);
993 this._display.resize(this._fb_width, this._fb_height);
994 this._onFBResize(this, this._fb_width, this._fb_height);
995 this._keyboard.grab();
998 if (this._true_color) {
1006 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1007 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1008 RFB.messages.fbUpdateRequests(this._sock, false, this._display.getCleanDirtyReset(), this._fb_width, this._fb_height);
1010 this._timing.fbu_rt_start = (new Date()).getTime();
1011 this._timing.pixels = 0;
1013 if (this._encrypt) {
1014 this._updateState('normal', 'Connected (encrypted) to: ' + this._fb_name);
1016 this._updateState('normal', 'Connected (unencrypted) to: ' + this._fb_name);
1021 _init_msg: function () {
1022 switch (this._rfb_state) {
1023 case 'ProtocolVersion':
1024 return this._negotiate_protocol_version();
1027 return this._negotiate_security();
1029 case 'Authentication':
1030 return this._negotiate_authentication();
1032 case 'SecurityResult':
1033 return this._handle_security_result();
1035 case 'ClientInitialisation':
1036 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1037 this._updateState('ServerInitialisation', "Authentication OK");
1040 case 'ServerInitialisation':
1041 return this._negotiate_server_init();
1044 return this._fail("Unknown state: " + this._rfb_state);
1048 _handle_set_colour_map_msg: function () {
1049 Util.Debug("SetColorMapEntries");
1050 this._sock.rQskip8(); // Padding
1052 var first_colour = this._sock.rQshift16();
1053 var num_colours = this._sock.rQshift16();
1054 if (this._sock.rQwait('SetColorMapEntries', num_colours * 6, 6)) { return false; }
1056 for (var c = 0; c < num_colours; c++) {
1057 var red = parseInt(this._sock.rQshift16() / 256, 10);
1058 var green = parseInt(this._sock.rQshift16() / 256, 10);
1059 var blue = parseInt(this._sock.rQshift16() / 256, 10);
1060 this._display.set_colourMap([blue, green, red], first_colour + c);
1062 Util.Debug("colourMap: " + this._display.get_colourMap());
1063 Util.Info("Registered " + num_colours + " colourMap entries");
1068 _handle_server_cut_text: function () {
1069 Util.Debug("ServerCutText");
1070 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1071 this._sock.rQskipBytes(3); // Padding
1072 var length = this._sock.rQshift32();
1073 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
1075 var text = this._sock.rQshiftStr(length);
1076 this._onClipboard(this, text);
1081 _handle_server_fence_msg: function() {
1082 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1083 this._sock.rQskipBytes(3); // Padding
1084 var flags = this._sock.rQshift32();
1085 var length = this._sock.rQshift8();
1087 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
1090 Util.Warn("Bad payload length (" + length + ") in fence response");
1094 var payload = this._sock.rQshiftStr(length);
1096 this._supportsFence = true;
1101 * (1<<0) - BlockBefore
1102 * (1<<1) - BlockAfter
1107 if (!(flags
& (1<<31))) {
1108 return this._fail("Unexpected fence response");
1111 // Filter out unsupported flags
1112 // FIXME: support syncNext
1113 flags
&= (1<<0) | (1<<1);
1115 // BlockBefore and BlockAfter are automatically handled by
1116 // the fact that we process each incoming message
1118 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1123 _handle_xvp_msg: function () {
1124 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1125 this._sock
.rQskip8(); // Padding
1126 var xvp_ver
= this._sock
.rQshift8();
1127 var xvp_msg
= this._sock
.rQshift8();
1131 this._updateState(this._rfb_state
, "Operation Failed");
1134 this._rfb_xvp_ver
= xvp_ver
;
1135 Util
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1136 this._onXvpInit(this._rfb_xvp_ver
);
1139 this._fail("Disconnected: illegal server XVP message " + xvp_msg
);
1146 _normal_msg: function () {
1149 if (this._FBU
.rects
> 0) {
1152 msg_type
= this._sock
.rQshift8();
1156 case 0: // FramebufferUpdate
1157 var ret
= this._framebufferUpdate();
1159 RFB
.messages
.fbUpdateRequests(this._sock
,
1160 this._enabledContinuousUpdates
,
1161 this._display
.getCleanDirtyReset(),
1162 this._fb_width
, this._fb_height
);
1166 case 1: // SetColorMapEntries
1167 return this._handle_set_colour_map_msg();
1174 case 3: // ServerCutText
1175 return this._handle_server_cut_text();
1177 case 150: // EndOfContinuousUpdates
1178 var first
= !(this._supportsContinuousUpdates
);
1179 this._supportsContinuousUpdates
= true;
1180 this._enabledContinuousUpdates
= false;
1182 this._enabledContinuousUpdates
= true;
1183 this._updateContinuousUpdates();
1184 Util
.Info("Enabling continuous updates.");
1186 // FIXME: We need to send a framebufferupdaterequest here
1187 // if we add support for turning off continuous updates
1191 case 248: // ServerFence
1192 return this._handle_server_fence_msg();
1195 return this._handle_xvp_msg();
1198 this._fail("Disconnected: illegal server message type " + msg_type
);
1199 Util
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1204 _framebufferUpdate: function () {
1208 if (this._FBU
.rects
=== 0) {
1209 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1210 this._sock
.rQskip8(); // Padding
1211 this._FBU
.rects
= this._sock
.rQshift16();
1212 this._FBU
.bytes
= 0;
1213 this._timing
.cur_fbu
= 0;
1214 if (this._timing
.fbu_rt_start
> 0) {
1215 now
= (new Date()).getTime();
1216 Util
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1220 while (this._FBU
.rects
> 0) {
1221 if (this._rfb_state
!== "normal") { return false; }
1223 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1224 if (this._FBU
.bytes
=== 0) {
1225 if (this._sock
.rQwait("rect header", 12)) { return false; }
1226 /* New FramebufferUpdate */
1228 var hdr
= this._sock
.rQshiftBytes(12);
1229 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1230 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1231 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1232 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1233 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1234 (hdr
[10] << 8) + hdr
[11], 10);
1236 this._onFBUReceive(this,
1237 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1238 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1239 'encoding': this._FBU
.encoding
,
1240 'encodingName': this._encNames
[this._FBU
.encoding
]});
1242 if (!this._encNames
[this._FBU
.encoding
]) {
1243 this._fail("Disconnected: unsupported encoding " +
1244 this._FBU
.encoding
);
1249 this._timing
.last_fbu
= (new Date()).getTime();
1251 ret
= this._encHandlers
[this._FBU
.encoding
]();
1253 now
= (new Date()).getTime();
1254 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1257 this._encStats
[this._FBU
.encoding
][0]++;
1258 this._encStats
[this._FBU
.encoding
][1]++;
1259 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1262 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1263 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1264 this._timing
.fbu_rt_start
> 0) {
1265 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1266 this._timing
.full_fbu_cnt
++;
1267 Util
.Info("Timing of full FBU, curr: " +
1268 this._timing
.cur_fbu
+ ", total: " +
1269 this._timing
.full_fbu_total
+ ", cnt: " +
1270 this._timing
.full_fbu_cnt
+ ", avg: " +
1271 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1274 if (this._timing
.fbu_rt_start
> 0) {
1275 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1276 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1277 this._timing
.fbu_rt_cnt
++;
1278 Util
.Info("full FBU round-trip, cur: " +
1279 fbu_rt_diff
+ ", total: " +
1280 this._timing
.fbu_rt_total
+ ", cnt: " +
1281 this._timing
.fbu_rt_cnt
+ ", avg: " +
1282 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1283 this._timing
.fbu_rt_start
= 0;
1287 if (!ret
) { return ret
; } // need more data
1290 this._onFBUComplete(this,
1291 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1292 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1293 'encoding': this._FBU
.encoding
,
1294 'encodingName': this._encNames
[this._FBU
.encoding
]});
1296 return true; // We finished this FBU
1299 _updateContinuousUpdates: function() {
1300 if (!this._enabledContinuousUpdates
) { return; }
1302 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1303 this._fb_width
, this._fb_height
);
1307 Util
.make_properties(RFB
, [
1308 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1309 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1310 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1311 ['true_color', 'rw', 'bool'], // Request true color pixel data
1312 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1313 ['shared', 'rw', 'bool'], // Request shared mode
1314 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1315 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1316 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1317 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1318 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1319 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1321 // Callback functions
1322 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate, statusMsg): RFB state update/change
1323 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb): VNC password is required
1324 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1325 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1326 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1327 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1328 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1329 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1330 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1333 RFB
.prototype.set_local_cursor = function (cursor
) {
1334 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1335 this._local_cursor
= false;
1336 this._display
.disableLocalCursor(); //Only show server-side cursor
1338 if (this._display
.get_cursor_uri()) {
1339 this._local_cursor
= true;
1341 Util
.Warn("Browser does not support local cursor");
1342 this._display
.disableLocalCursor();
1347 RFB
.prototype.get_display = function () { return this._display
; };
1348 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1349 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1353 keyEvent: function (sock
, keysym
, down
) {
1354 var buff
= sock
._sQ
;
1355 var offset
= sock
._sQlen
;
1357 buff
[offset
] = 4; // msg-type
1358 buff
[offset
+ 1] = down
;
1360 buff
[offset
+ 2] = 0;
1361 buff
[offset
+ 3] = 0;
1363 buff
[offset
+ 4] = (keysym
>> 24);
1364 buff
[offset
+ 5] = (keysym
>> 16);
1365 buff
[offset
+ 6] = (keysym
>> 8);
1366 buff
[offset
+ 7] = keysym
;
1372 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1373 function getRFBkeycode(xt_scancode
) {
1374 var upperByte
= (keycode
>> 8);
1375 var lowerByte
= (keycode
& 0x00ff);
1376 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1377 lowerByte
= lowerByte
| 0x80;
1383 var buff
= sock
._sQ
;
1384 var offset
= sock
._sQlen
;
1386 buff
[offset
] = 255; // msg-type
1387 buff
[offset
+ 1] = 0; // sub msg-type
1389 buff
[offset
+ 2] = (down
>> 8);
1390 buff
[offset
+ 3] = down
;
1392 buff
[offset
+ 4] = (keysym
>> 24);
1393 buff
[offset
+ 5] = (keysym
>> 16);
1394 buff
[offset
+ 6] = (keysym
>> 8);
1395 buff
[offset
+ 7] = keysym
;
1397 var RFBkeycode
= getRFBkeycode(keycode
);
1399 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1400 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1401 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1402 buff
[offset
+ 11] = RFBkeycode
;
1408 pointerEvent: function (sock
, x
, y
, mask
) {
1409 var buff
= sock
._sQ
;
1410 var offset
= sock
._sQlen
;
1412 buff
[offset
] = 5; // msg-type
1414 buff
[offset
+ 1] = mask
;
1416 buff
[offset
+ 2] = x
>> 8;
1417 buff
[offset
+ 3] = x
;
1419 buff
[offset
+ 4] = y
>> 8;
1420 buff
[offset
+ 5] = y
;
1426 // TODO(directxman12): make this unicode compatible?
1427 clientCutText: function (sock
, text
) {
1428 var buff
= sock
._sQ
;
1429 var offset
= sock
._sQlen
;
1431 buff
[offset
] = 6; // msg-type
1433 buff
[offset
+ 1] = 0; // padding
1434 buff
[offset
+ 2] = 0; // padding
1435 buff
[offset
+ 3] = 0; // padding
1437 var n
= text
.length
;
1439 buff
[offset
+ 4] = n
>> 24;
1440 buff
[offset
+ 5] = n
>> 16;
1441 buff
[offset
+ 6] = n
>> 8;
1442 buff
[offset
+ 7] = n
;
1444 for (var i
= 0; i
< n
; i
++) {
1445 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1448 sock
._sQlen
+= 8 + n
;
1452 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1453 var buff
= sock
._sQ
;
1454 var offset
= sock
._sQlen
;
1456 buff
[offset
] = 251; // msg-type
1457 buff
[offset
+ 1] = 0; // padding
1458 buff
[offset
+ 2] = width
>> 8; // width
1459 buff
[offset
+ 3] = width
;
1460 buff
[offset
+ 4] = height
>> 8; // height
1461 buff
[offset
+ 5] = height
;
1463 buff
[offset
+ 6] = 1; // number-of-screens
1464 buff
[offset
+ 7] = 0; // padding
1467 buff
[offset
+ 8] = id
>> 24; // id
1468 buff
[offset
+ 9] = id
>> 16;
1469 buff
[offset
+ 10] = id
>> 8;
1470 buff
[offset
+ 11] = id
;
1471 buff
[offset
+ 12] = 0; // x-position
1472 buff
[offset
+ 13] = 0;
1473 buff
[offset
+ 14] = 0; // y-position
1474 buff
[offset
+ 15] = 0;
1475 buff
[offset
+ 16] = width
>> 8; // width
1476 buff
[offset
+ 17] = width
;
1477 buff
[offset
+ 18] = height
>> 8; // height
1478 buff
[offset
+ 19] = height
;
1479 buff
[offset
+ 20] = flags
>> 24; // flags
1480 buff
[offset
+ 21] = flags
>> 16;
1481 buff
[offset
+ 22] = flags
>> 8;
1482 buff
[offset
+ 23] = flags
;
1488 clientFence: function (sock
, flags
, payload
) {
1489 var buff
= sock
._sQ
;
1490 var offset
= sock
._sQlen
;
1492 buff
[offset
] = 248; // msg-type
1494 buff
[offset
+ 1] = 0; // padding
1495 buff
[offset
+ 2] = 0; // padding
1496 buff
[offset
+ 3] = 0; // padding
1498 buff
[offset
+ 4] = flags
>> 24; // flags
1499 buff
[offset
+ 5] = flags
>> 16;
1500 buff
[offset
+ 6] = flags
>> 8;
1501 buff
[offset
+ 7] = flags
;
1503 var n
= payload
.length
;
1505 buff
[offset
+ 8] = n
; // length
1507 for (var i
= 0; i
< n
; i
++) {
1508 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1511 sock
._sQlen
+= 9 + n
;
1515 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1516 var buff
= sock
._sQ
;
1517 var offset
= sock
._sQlen
;
1519 buff
[offset
] = 150; // msg-type
1520 buff
[offset
+ 1] = enable
; // enable-flag
1522 buff
[offset
+ 2] = x
>> 8; // x
1523 buff
[offset
+ 3] = x
;
1524 buff
[offset
+ 4] = y
>> 8; // y
1525 buff
[offset
+ 5] = y
;
1526 buff
[offset
+ 6] = width
>> 8; // width
1527 buff
[offset
+ 7] = width
;
1528 buff
[offset
+ 8] = height
>> 8; // height
1529 buff
[offset
+ 9] = height
;
1535 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1536 var buff
= sock
._sQ
;
1537 var offset
= sock
._sQlen
;
1539 buff
[offset
] = 0; // msg-type
1541 buff
[offset
+ 1] = 0; // padding
1542 buff
[offset
+ 2] = 0; // padding
1543 buff
[offset
+ 3] = 0; // padding
1545 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1546 buff
[offset
+ 5] = depth
* 8; // depth
1547 buff
[offset
+ 6] = 0; // little-endian
1548 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1550 buff
[offset
+ 8] = 0; // red-max
1551 buff
[offset
+ 9] = 255; // red-max
1553 buff
[offset
+ 10] = 0; // green-max
1554 buff
[offset
+ 11] = 255; // green-max
1556 buff
[offset
+ 12] = 0; // blue-max
1557 buff
[offset
+ 13] = 255; // blue-max
1559 buff
[offset
+ 14] = 16; // red-shift
1560 buff
[offset
+ 15] = 8; // green-shift
1561 buff
[offset
+ 16] = 0; // blue-shift
1563 buff
[offset
+ 17] = 0; // padding
1564 buff
[offset
+ 18] = 0; // padding
1565 buff
[offset
+ 19] = 0; // padding
1571 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1572 var buff
= sock
._sQ
;
1573 var offset
= sock
._sQlen
;
1575 buff
[offset
] = 2; // msg-type
1576 buff
[offset
+ 1] = 0; // padding
1578 // offset + 2 and offset + 3 are encoding count
1580 var i
, j
= offset
+ 4, cnt
= 0;
1581 for (i
= 0; i
< encodings
.length
; i
++) {
1582 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1583 Util
.Debug("Skipping Cursor pseudo-encoding");
1584 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1585 // TODO: remove this when we have tight+non-true-color
1586 Util
.Warn("Skipping tight as it is only supported with true color");
1588 var enc
= encodings
[i
][1];
1589 buff
[j
] = enc
>> 24;
1590 buff
[j
+ 1] = enc
>> 16;
1591 buff
[j
+ 2] = enc
>> 8;
1599 buff
[offset
+ 2] = cnt
>> 8;
1600 buff
[offset
+ 3] = cnt
;
1602 sock
._sQlen
+= j
- offset
;
1606 fbUpdateRequests: function (sock
, onlyNonInc
, cleanDirty
, fb_width
, fb_height
) {
1607 var offsetIncrement
= 0;
1609 var cb
= cleanDirty
.cleanBox
;
1611 if (!onlyNonInc
&& (cb
.w
> 0 && cb
.h
> 0)) {
1612 w
= typeof cb
.w
=== "undefined" ? fb_width
: cb
.w
;
1613 h
= typeof cb
.h
=== "undefined" ? fb_height
: cb
.h
;
1614 // Request incremental for clean box
1615 RFB
.messages
.fbUpdateRequest(sock
, 1, cb
.x
, cb
.y
, w
, h
);
1618 for (var i
= 0; i
< cleanDirty
.dirtyBoxes
.length
; i
++) {
1619 var db
= cleanDirty
.dirtyBoxes
[i
];
1620 // Force all (non-incremental) for dirty box
1621 w
= typeof db
.w
=== "undefined" ? fb_width
: db
.w
;
1622 h
= typeof db
.h
=== "undefined" ? fb_height
: db
.h
;
1623 RFB
.messages
.fbUpdateRequest(sock
, 0, db
.x
, db
.y
, w
, h
);
1627 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1628 var buff
= sock
._sQ
;
1629 var offset
= sock
._sQlen
;
1631 if (typeof(x
) === "undefined") { x
= 0; }
1632 if (typeof(y
) === "undefined") { y
= 0; }
1634 buff
[offset
] = 3; // msg-type
1635 buff
[offset
+ 1] = incremental
;
1637 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1638 buff
[offset
+ 3] = x
& 0xFF;
1640 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1641 buff
[offset
+ 5] = y
& 0xFF;
1643 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1644 buff
[offset
+ 7] = w
& 0xFF;
1646 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1647 buff
[offset
+ 9] = h
& 0xFF;
1654 RFB
.genDES = function (password
, challenge
) {
1656 for (var i
= 0; i
< password
.length
; i
++) {
1657 passwd
.push(password
.charCodeAt(i
));
1659 return (new DES(passwd
)).encrypt(challenge
);
1662 RFB
.extract_data_uri = function (arr
) {
1663 return ";base64," + Base64
.encode(arr
);
1666 RFB
.encodingHandlers
= {
1668 if (this._FBU
.lines
=== 0) {
1669 this._FBU
.lines
= this._FBU
.height
;
1672 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1673 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1674 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1675 var curr_height
= Math
.min(this._FBU
.lines
,
1676 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1677 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1678 curr_height
, this._sock
.get_rQ(),
1679 this._sock
.get_rQi());
1680 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1681 this._FBU
.lines
-= curr_height
;
1683 if (this._FBU
.lines
> 0) {
1684 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1687 this._FBU
.bytes
= 0;
1693 COPYRECT: function () {
1694 this._FBU
.bytes
= 4;
1695 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1696 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1697 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1701 this._FBU
.bytes
= 0;
1707 if (this._FBU
.subrects
=== 0) {
1708 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1709 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1710 this._FBU
.subrects
= this._sock
.rQshift32();
1711 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1712 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1715 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1716 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1717 var x
= this._sock
.rQshift16();
1718 var y
= this._sock
.rQshift16();
1719 var width
= this._sock
.rQshift16();
1720 var height
= this._sock
.rQshift16();
1721 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1722 this._FBU
.subrects
--;
1725 if (this._FBU
.subrects
> 0) {
1726 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1727 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1730 this._FBU
.bytes
= 0;
1736 HEXTILE: function () {
1737 var rQ
= this._sock
.get_rQ();
1738 var rQi
= this._sock
.get_rQi();
1740 if (this._FBU
.tiles
=== 0) {
1741 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1742 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1743 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1744 this._FBU
.tiles
= this._FBU
.total_tiles
;
1747 while (this._FBU
.tiles
> 0) {
1748 this._FBU
.bytes
= 1;
1749 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1750 var subencoding
= rQ
[rQi
]; // Peek
1751 if (subencoding
> 30) { // Raw
1752 this._fail("Disconnected: illegal hextile subencoding " + subencoding
);
1757 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1758 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1759 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1760 var x
= this._FBU
.x
+ tile_x
* 16;
1761 var y
= this._FBU
.y
+ tile_y
* 16;
1762 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1763 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1765 // Figure out how much we are expecting
1766 if (subencoding
& 0x01) { // Raw
1767 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1769 if (subencoding
& 0x02) { // Background
1770 this._FBU
.bytes
+= this._fb_Bpp
;
1772 if (subencoding
& 0x04) { // Foreground
1773 this._FBU
.bytes
+= this._fb_Bpp
;
1775 if (subencoding
& 0x08) { // AnySubrects
1776 this._FBU
.bytes
++; // Since we aren't shifting it off
1777 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1778 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1779 if (subencoding
& 0x10) { // SubrectsColoured
1780 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1782 this._FBU
.bytes
+= subrects
* 2;
1787 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1789 // We know the encoding and have a whole tile
1790 this._FBU
.subencoding
= rQ
[rQi
];
1792 if (this._FBU
.subencoding
=== 0) {
1793 if (this._FBU
.lastsubencoding
& 0x01) {
1794 // Weird: ignore blanks are RAW
1795 Util
.Debug(" Ignoring blank after RAW");
1797 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1799 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1800 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1801 rQi
+= this._FBU
.bytes
- 1;
1803 if (this._FBU
.subencoding
& 0x02) { // Background
1804 if (this._fb_Bpp
== 1) {
1805 this._FBU
.background
= rQ
[rQi
];
1808 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1810 rQi
+= this._fb_Bpp
;
1812 if (this._FBU
.subencoding
& 0x04) { // Foreground
1813 if (this._fb_Bpp
== 1) {
1814 this._FBU
.foreground
= rQ
[rQi
];
1816 // this._fb_Bpp is 4
1817 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1819 rQi
+= this._fb_Bpp
;
1822 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1823 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1827 for (var s
= 0; s
< subrects
; s
++) {
1829 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1830 if (this._fb_Bpp
=== 1) {
1834 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1836 rQi
+= this._fb_Bpp
;
1838 color
= this._FBU
.foreground
;
1843 var sy
= (xy
& 0x0f);
1847 var sw
= (wh
>> 4) + 1;
1848 var sh
= (wh
& 0x0f) + 1;
1850 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1853 this._display
.finishTile();
1855 this._sock
.set_rQi(rQi
);
1856 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1857 this._FBU
.bytes
= 0;
1861 if (this._FBU
.tiles
=== 0) {
1868 getTightCLength: function (arr
) {
1869 var header
= 1, data
= 0;
1870 data
+= arr
[0] & 0x7f;
1871 if (arr
[0] & 0x80) {
1873 data
+= (arr
[1] & 0x7f) << 7;
1874 if (arr
[1] & 0x80) {
1876 data
+= arr
[2] << 14;
1879 return [header
, data
];
1882 display_tight: function (isTightPNG
) {
1883 if (this._fb_depth
=== 1) {
1884 this._fail("Tight protocol handler only implements true color mode");
1887 this._FBU
.bytes
= 1; // compression-control byte
1888 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1890 var checksum = function (data
) {
1892 for (var i
= 0; i
< data
.length
; i
++) {
1894 if (sum
> 65536) sum
-= 65536;
1899 var resetStreams
= 0;
1901 var decompress = function (data
, expected
) {
1902 for (var i
= 0; i
< 4; i
++) {
1903 if ((resetStreams
>> i
) & 1) {
1904 this._FBU
.zlibs
[i
].reset();
1905 Util
.Info("Reset zlib stream " + i
);
1909 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1910 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
1911 /*if (uncompressed.status !== 0) {
1912 Util.Error("Invalid data in zlib stream");
1915 //return uncompressed.data;
1916 return uncompressed
;
1919 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
1920 // Convert indexed (palette based) image data to RGB
1921 // TODO: reduce number of calculations inside loop
1922 var dest
= this._destBuff
;
1923 var w
= Math
.floor((width
+ 7) / 8);
1924 var w1
= Math
.floor(width
/ 8);
1926 /*for (var y = 0; y < height; y++) {
1928 var yoffset = y * width;
1929 var ybitoffset = y * w;
1930 var xoffset, targetbyte;
1931 for (x = 0; x < w1; x++) {
1932 xoffset = yoffset + x * 8;
1933 targetbyte = data[ybitoffset + x];
1934 for (b = 7; b >= 0; b--) {
1935 dp = (xoffset + 7 - b) * 3;
1936 sp = (targetbyte >> b & 1) * 3;
1937 dest[dp] = palette[sp];
1938 dest[dp + 1] = palette[sp + 1];
1939 dest[dp + 2] = palette[sp + 2];
1943 xoffset = yoffset + x * 8;
1944 targetbyte = data[ybitoffset + x];
1945 for (b = 7; b >= 8 - width % 8; b--) {
1946 dp = (xoffset + 7 - b) * 3;
1947 sp = (targetbyte >> b & 1) * 3;
1948 dest[dp] = palette[sp];
1949 dest[dp + 1] = palette[sp + 1];
1950 dest[dp + 2] = palette[sp + 2];
1954 for (var y
= 0; y
< height
; y
++) {
1956 for (x
= 0; x
< w1
; x
++) {
1957 for (b
= 7; b
>= 0; b
--) {
1958 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
1959 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
1960 dest
[dp
] = palette
[sp
];
1961 dest
[dp
+ 1] = palette
[sp
+ 1];
1962 dest
[dp
+ 2] = palette
[sp
+ 2];
1967 for (b
= 7; b
>= 8 - width
% 8; b
--) {
1968 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
1969 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
1970 dest
[dp
] = palette
[sp
];
1971 dest
[dp
+ 1] = palette
[sp
+ 1];
1972 dest
[dp
+ 2] = palette
[sp
+ 2];
1980 var indexedToRGBX = function (data
, palette
, width
, height
) {
1981 // Convert indexed (palette based) image data to RGB
1982 var dest
= this._destBuff
;
1983 var total
= width
* height
* 4;
1984 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
1985 var sp
= data
[j
] * 3;
1986 dest
[i
] = palette
[sp
];
1987 dest
[i
+ 1] = palette
[sp
+ 1];
1988 dest
[i
+ 2] = palette
[sp
+ 2];
1995 var rQi
= this._sock
.get_rQi();
1996 var rQ
= this._sock
.rQwhole();
1998 var cl_header
, cl_data
;
2000 var handlePalette = function () {
2001 var numColors
= rQ
[rQi
+ 2] + 1;
2002 var paletteSize
= numColors
* this._fb_depth
;
2003 this._FBU
.bytes
+= paletteSize
;
2004 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2006 var bpp
= (numColors
<= 2) ? 1 : 8;
2007 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2009 if (rowSize
* this._FBU
.height
< 12) {
2012 cl_data
= rowSize
* this._FBU
.height
;
2013 //clength = [0, rowSize * this._FBU.height];
2015 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2016 var cl_offset
= rQi
+ 3 + paletteSize
;
2019 cl_data
+= rQ
[cl_offset
] & 0x7f;
2020 if (rQ
[cl_offset
] & 0x80) {
2022 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2023 if (rQ
[cl_offset
+ 1] & 0x80) {
2025 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2028 // end inline getTightCLength
2031 this._FBU
.bytes
+= cl_header
+ cl_data
;
2032 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2034 // Shift ctl, filter id, num colors, palette entries, and clength off
2035 this._sock
.rQskipBytes(3);
2036 //var palette = this._sock.rQshiftBytes(paletteSize);
2037 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2038 this._sock
.rQskipBytes(cl_header
);
2041 data
= this._sock
.rQshiftBytes(cl_data
);
2043 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2046 // Convert indexed (palette based) image data to RGB
2048 if (numColors
== 2) {
2049 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2050 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2052 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2053 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2060 var handleCopy = function () {
2062 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2063 if (uncompressedSize
< 12) {
2066 cl_data
= uncompressedSize
;
2068 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2069 var cl_offset
= rQi
+ 1;
2072 cl_data
+= rQ
[cl_offset
] & 0x7f;
2073 if (rQ
[cl_offset
] & 0x80) {
2075 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2076 if (rQ
[cl_offset
+ 1] & 0x80) {
2078 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2081 // end inline getTightCLength
2083 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2084 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2086 // Shift ctl, clength off
2087 this._sock
.rQshiftBytes(1 + cl_header
);
2090 data
= this._sock
.rQshiftBytes(cl_data
);
2092 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2095 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2100 var ctl
= this._sock
.rQpeek8();
2102 // Keep tight reset bits
2103 resetStreams
= ctl
& 0xF;
2105 // Figure out filter
2107 streamId
= ctl
& 0x3;
2109 if (ctl
=== 0x08) cmode
= "fill";
2110 else if (ctl
=== 0x09) cmode
= "jpeg";
2111 else if (ctl
=== 0x0A) cmode
= "png";
2112 else if (ctl
& 0x04) cmode
= "filter";
2113 else if (ctl
< 0x04) cmode
= "copy";
2114 else return this._fail("Illegal tight compression received, ctl: " + ctl
);
2116 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2117 return this._fail("filter/copy received in tightPNG mode");
2121 // fill use fb_depth because TPIXELs drop the padding byte
2122 case "fill": // TPIXEL
2123 this._FBU
.bytes
+= this._fb_depth
;
2125 case "jpeg": // max clength
2126 this._FBU
.bytes
+= 3;
2128 case "png": // max clength
2129 this._FBU
.bytes
+= 3;
2131 case "filter": // filter id + num colors if palette
2132 this._FBU
.bytes
+= 2;
2138 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2140 // Determine FBU.bytes
2144 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);
2145 this._sock
.rQskipBytes(4);
2149 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2150 var cl_offset
= rQi
+ 1;
2153 cl_data
+= rQ
[cl_offset
] & 0x7f;
2154 if (rQ
[cl_offset
] & 0x80) {
2156 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2157 if (rQ
[cl_offset
+ 1] & 0x80) {
2159 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2162 // end inline getTightCLength
2163 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2164 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2166 // We have everything, render it
2167 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2168 var img
= new Image();
2169 img
.src
= "data: image/" + cmode
+
2170 RFB
.extract_data_uri(this._sock
.rQshiftBytes(cl_data
));
2171 this._display
.renderQ_push({
2180 var filterId
= rQ
[rQi
+ 1];
2181 if (filterId
=== 1) {
2182 if (!handlePalette()) { return false; }
2184 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2185 // Filter 2, Gradient is valid but not use if jpeg is enabled
2186 this._fail("Unsupported tight subencoding received, filter: " + filterId
);
2190 if (!handleCopy()) { return false; }
2195 this._FBU
.bytes
= 0;
2201 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2202 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2204 last_rect: function () {
2205 this._FBU
.rects
= 0;
2209 handle_FB_resize: function () {
2210 this._fb_width
= this._FBU
.width
;
2211 this._fb_height
= this._FBU
.height
;
2212 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2213 this._display
.resize(this._fb_width
, this._fb_height
);
2214 this._onFBResize(this, this._fb_width
, this._fb_height
);
2215 this._timing
.fbu_rt_start
= (new Date()).getTime();
2216 this._updateContinuousUpdates();
2218 this._FBU
.bytes
= 0;
2219 this._FBU
.rects
-= 1;
2223 ExtendedDesktopSize: function () {
2224 this._FBU
.bytes
= 1;
2225 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2227 this._supportsSetDesktopSize
= true;
2228 var number_of_screens
= this._sock
.rQpeek8();
2230 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2231 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2233 this._sock
.rQskipBytes(1); // number-of-screens
2234 this._sock
.rQskipBytes(3); // padding
2236 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2237 // Save the id and flags of the first screen
2239 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2240 this._sock
.rQskipBytes(2); // x-position
2241 this._sock
.rQskipBytes(2); // y-position
2242 this._sock
.rQskipBytes(2); // width
2243 this._sock
.rQskipBytes(2); // height
2244 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2246 this._sock
.rQskipBytes(16);
2251 * The x-position indicates the reason for the change:
2253 * 0 - server resized on its own
2254 * 1 - this client requested the resize
2255 * 2 - another client requested the resize
2258 // We need to handle errors when we requested the resize.
2259 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2261 // The y-position indicates the status code from the server
2262 switch (this._FBU
.y
) {
2264 msg
= "Resize is administratively prohibited";
2267 msg
= "Out of resources";
2270 msg
= "Invalid screen layout";
2273 msg
= "Unknown reason";
2276 Util
.Info("Server did not accept the resize request: " + msg
);
2280 this._encHandlers
.handle_FB_resize();
2284 DesktopSize: function () {
2285 this._encHandlers
.handle_FB_resize();
2289 Cursor: function () {
2290 Util
.Debug(">> set_cursor");
2291 var x
= this._FBU
.x
; // hotspot-x
2292 var y
= this._FBU
.y
; // hotspot-y
2293 var w
= this._FBU
.width
;
2294 var h
= this._FBU
.height
;
2296 var pixelslength
= w
* h
* this._fb_Bpp
;
2297 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2299 this._FBU
.bytes
= pixelslength
+ masklength
;
2300 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2302 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2303 this._sock
.rQshiftBytes(masklength
),
2306 this._FBU
.bytes
= 0;
2309 Util
.Debug("<< set_cursor");
2313 QEMUExtendedKeyEvent: function () {
2316 var keyboardEvent
= document
.createEvent("keyboardEvent");
2317 if (keyboardEvent
.code
!== undefined) {
2318 this._qemuExtKeyEventSupported
= true;
2319 this._keyboard
.setQEMUVNCKeyboardHandler();
2323 JPEG_quality_lo: function () {
2324 Util
.Error("Server sent jpeg_quality pseudo-encoding");
2327 compress_lo: function () {
2328 Util
.Error("Server sent compress level pseudo-encoding");