2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2012 Joel Martin
4 * Copyright (C) 2016 Samuel Mannehed for Cendio AB
5 * Licensed under MPL 2.0 (see LICENSE.txt)
7 * See README.md for usage and integration instructions.
9 * TIGHT decoder portion:
10 * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
13 import * as Log
from './util/logging.js';
14 import _
from './util/localization.js';
15 import { decodeUTF8
} from './util/strings.js';
16 import { set_defaults
, make_properties
} from './util/properties.js';
17 import Display
from "./display.js";
18 import Keyboard
from "./input/keyboard.js";
19 import Mouse
from "./input/mouse.js";
20 import Websock
from "./websock.js";
21 import Base64
from "./base64.js";
22 import DES
from "./des.js";
23 import KeyTable
from "./input/keysym.js";
24 import XtScancode
from "./input/xtscancodes.js";
25 import Inflator
from "./inflator.js";
26 import { encodings
, encodingName
} from "./encodings.js";
28 /*jslint white: false, browser: true */
29 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
31 export default function RFB(defaults
) {
38 this._rfb_port
= 5900;
39 this._rfb_password
= '';
42 this._rfb_connection_state
= '';
43 this._rfb_init_state
= '';
44 this._rfb_version
= 0;
45 this._rfb_max_version
= 3.8;
46 this._rfb_auth_scheme
= '';
47 this._rfb_disconnect_reason
= "";
49 this._rfb_tightvnc
= false;
50 this._rfb_xvp_ver
= 0;
52 this._encHandlers
= {};
55 this._sock
= null; // Websock object
56 this._display
= null; // Display object
57 this._flushing
= false; // Display flushing state
58 this._keyboard
= null; // Keyboard input handler object
59 this._mouse
= null; // Mouse input handler object
60 this._disconnTimer
= null; // disconnection timer
62 this._supportsFence
= false;
64 this._supportsContinuousUpdates
= false;
65 this._enabledContinuousUpdates
= false;
67 // Frame buffer update state
81 zlib
: [] // TIGHT zlib streams
88 this._destBuff
= null;
89 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
91 this._rre_chunk_sz
= 100;
106 this._supportsSetDesktopSize
= false;
108 this._screen_flags
= 0;
111 this._mouse_buttonMask
= 0;
112 this._mouse_arr
= [];
113 this._viewportDragging
= false;
114 this._viewportDragPos
= {};
115 this._viewportHasMoved
= false;
117 // QEMU Extended Key Event support - default to false
118 this._qemuExtKeyEventSupported
= false;
120 // set the default value on user-facing properties
121 set_defaults(this, defaults
, {
122 'target': 'null', // VNC display rendering Canvas object
123 'encrypt': false, // Use TLS/SSL/wss encryption
124 'local_cursor': false, // Request locally rendered cursor
125 'shared': true, // Request shared mode
126 'view_only': false, // Disable client mouse/keyboard
127 'xvp_password_sep': '@', // Separator for XVP password fields
128 'disconnectTimeout': 3, // Time (s) to wait for disconnection
129 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
130 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
131 'viewportDrag': false, // Move the viewport on mouse drags
133 // Callback functions
134 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
135 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
136 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
137 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
138 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
139 'onBell': function () { }, // onBell(rfb): RFB Bell message received
140 'onFBUReceive': function () { }, // onFBUReceive(rfb, rect): RFB FBU rect received but not yet processed
141 'onFBUComplete': function () { }, // onFBUComplete(rfb): RFB FBU received and processed
142 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
143 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
144 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
148 Log
.Debug(">> RFB.constructor");
150 // populate encHandlers with bound versions
151 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
152 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
153 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
154 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
155 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
157 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
158 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
159 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
160 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
161 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
163 // NB: nothing that needs explicit teardown should be done
164 // before this point, since this can throw an exception
166 this._display
= new Display({target
: this._target
,
167 onFlush
: this._onFlush
.bind(this)});
169 Log
.Error("Display exception: " + exc
);
173 this._keyboard
= new Keyboard({target
: this._target
,
174 onKeyEvent
: this._handleKeyEvent
.bind(this)});
176 this._mouse
= new Mouse({target
: this._target
,
177 onMouseButton
: this._handleMouseButton
.bind(this),
178 onMouseMove
: this._handleMouseMove
.bind(this)});
180 this._sock
= new Websock();
181 this._sock
.on('message', this._handle_message
.bind(this));
182 this._sock
.on('open', function () {
183 if ((this._rfb_connection_state
=== 'connecting') &&
184 (this._rfb_init_state
=== '')) {
185 this._rfb_init_state
= 'ProtocolVersion';
186 Log
.Debug("Starting VNC handshake");
188 this._fail("Unexpected server connection");
191 this._sock
.on('close', function (e
) {
192 Log
.Warn("WebSocket on-close event");
195 msg
= " (code: " + e
.code
;
197 msg
+= ", reason: " + e
.reason
;
201 switch (this._rfb_connection_state
) {
202 case 'disconnecting':
203 this._updateConnectionState('disconnected');
206 this._fail('Failed to connect to server', msg
);
209 // Handle disconnects that were initiated server-side
210 this._updateConnectionState('disconnecting');
211 this._updateConnectionState('disconnected');
214 this._fail("Unexpected server disconnect",
215 "Already disconnected: " + msg
);
218 this._fail("Unexpected server disconnect",
219 "Not in any state yet: " + msg
);
222 this._sock
.off('close');
224 this._sock
.on('error', function (e
) {
225 Log
.Warn("WebSocket on-error event");
231 var rmode
= this._display
.get_render_mode();
232 Log
.Info("Using native WebSockets, render mode: " + rmode
);
234 Log
.Debug("<< RFB.constructor");
239 connect: function (host
, port
, password
, path
) {
240 this._rfb_host
= host
;
241 this._rfb_port
= port
;
242 this._rfb_password
= (password
!== undefined) ? password
: "";
243 this._rfb_path
= (path
!== undefined) ? path
: "";
245 if (!this._rfb_host
) {
250 this._rfb_init_state
= '';
251 this._updateConnectionState('connecting');
255 disconnect: function () {
256 this._updateConnectionState('disconnecting');
257 this._sock
.off('error');
258 this._sock
.off('message');
259 this._sock
.off('open');
262 sendPassword: function (passwd
) {
263 this._rfb_password
= passwd
;
264 setTimeout(this._init_msg
.bind(this), 0);
267 sendCtrlAltDel: function () {
268 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
269 Log
.Info("Sending Ctrl-Alt-Del");
271 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
272 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
273 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
274 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
275 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
276 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
281 xvpOp: function (ver
, op
) {
282 if (this._rfb_xvp_ver
< ver
) { return false; }
283 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
284 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
288 xvpShutdown: function () {
289 return this.xvpOp(1, 2);
292 xvpReboot: function () {
293 return this.xvpOp(1, 3);
296 xvpReset: function () {
297 return this.xvpOp(1, 4);
300 // Send a key press. If 'down' is not specified then send a down key
301 // followed by an up key.
302 sendKey: function (keysym
, code
, down
) {
303 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
305 if (down
=== undefined) {
306 this.sendKey(keysym
, code
, true);
307 this.sendKey(keysym
, code
, false);
311 var scancode
= XtScancode
[code
];
313 if (this._qemuExtKeyEventSupported
&& scancode
) {
315 keysym
= keysym
|| 0;
317 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
319 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
324 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
325 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
331 clipboardPasteFrom: function (text
) {
332 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
333 RFB
.messages
.clientCutText(this._sock
, text
);
336 // Requests a change of remote desktop size. This message is an extension
337 // and may only be sent if we have received an ExtendedDesktopSize message
338 requestDesktopSize: function (width
, height
) {
339 if (this._rfb_connection_state
!== 'connected' ||
344 if (this._supportsSetDesktopSize
) {
345 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
346 this._screen_id
, this._screen_flags
);
357 _connect: function () {
358 Log
.Debug(">> RFB.connect");
362 if (typeof UsingSocketIO
!== 'undefined') {
365 uri
= this._encrypt
? 'wss' : 'ws';
368 uri
+= '://' + this._rfb_host
;
370 uri
+= ':' + this._rfb_port
;
372 uri
+= '/' + this._rfb_path
;
374 Log
.Info("connecting to " + uri
);
377 // WebSocket.onopen transitions to the RFB init states
378 this._sock
.open(uri
, this._wsProtocols
);
380 if (e
.name
=== 'SyntaxError') {
381 this._fail("Invalid host or port value given", e
);
383 this._fail("Error while connecting", e
);
387 // Always grab focus on some kind of click event
388 this._target
.addEventListener("mousedown", this._focusCanvas
);
389 this._target
.addEventListener("touchstart", this._focusCanvas
);
391 Log
.Debug("<< RFB.connect");
394 _disconnect: function () {
395 Log
.Debug(">> RFB.disconnect");
396 this._target
.removeEventListener("mousedown", this._focusCanvas
);
397 this._target
.removeEventListener("touchstart", this._focusCanvas
);
401 Log
.Debug("<< RFB.disconnect");
404 _init_vars: function () {
407 this._FBU
.subrects
= 0; // RRE and HEXTILE
408 this._FBU
.lines
= 0; // RAW
409 this._FBU
.tiles
= 0; // HEXTILE
410 this._FBU
.zlibs
= []; // TIGHT zlib encoders
411 this._mouse_buttonMask
= 0;
412 this._mouse_arr
= [];
413 this._rfb_tightvnc
= false;
415 // Clear the per connection encoding stats
416 var stats
= this._encStats
;
417 Object
.keys(stats
).forEach(function (key
) {
422 for (i
= 0; i
< 4; i
++) {
423 this._FBU
.zlibs
[i
] = new Inflator();
427 _print_stats: function () {
428 var stats
= this._encStats
;
430 Log
.Info("Encoding stats for this connection:");
431 Object
.keys(stats
).forEach(function (key
) {
433 if (s
[0] + s
[1] > 0) {
434 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
438 Log
.Info("Encoding stats since page load:");
439 Object
.keys(stats
).forEach(function (key
) {
441 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
445 _cleanup: function () {
446 if (!this._view_only
) { this._keyboard
.ungrab(); }
447 if (!this._view_only
) { this._mouse
.ungrab(); }
448 this._display
.defaultCursor();
449 if (Log
.get_logging() !== 'debug') {
450 // Show noVNC logo on load and when disconnected, unless in
452 this._display
.clear();
456 // Event handler for canvas so this points to the canvas element
457 _focusCanvas: function(event
) {
458 // Respect earlier handlers' request to not do side-effects
459 if (!event
.defaultPrevented
)
468 * disconnected - permanent state
470 _updateConnectionState: function (state
) {
471 var oldstate
= this._rfb_connection_state
;
473 if (state
=== oldstate
) {
474 Log
.Debug("Already in state '" + state
+ "', ignoring");
478 // The 'disconnected' state is permanent for each RFB object
479 if (oldstate
=== 'disconnected') {
480 Log
.Error("Tried changing state of a disconnected RFB object");
484 // Ensure proper transitions before doing anything
487 if (oldstate
!== 'connecting') {
488 Log
.Error("Bad transition to connected state, " +
489 "previous connection state: " + oldstate
);
495 if (oldstate
!== 'disconnecting') {
496 Log
.Error("Bad transition to disconnected state, " +
497 "previous connection state: " + oldstate
);
503 if (oldstate
!== '') {
504 Log
.Error("Bad transition to connecting state, " +
505 "previous connection state: " + oldstate
);
510 case 'disconnecting':
511 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
512 Log
.Error("Bad transition to disconnecting state, " +
513 "previous connection state: " + oldstate
);
519 Log
.Error("Unknown connection state: " + state
);
523 // State change actions
525 this._rfb_connection_state
= state
;
526 this._onUpdateState(this, state
, oldstate
);
528 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
531 if (this._disconnTimer
&& state
!== 'disconnecting') {
532 Log
.Debug("Clearing disconnect timer");
533 clearTimeout(this._disconnTimer
);
534 this._disconnTimer
= null;
536 // make sure we don't get a double event
537 this._sock
.off('close');
542 // Call onDisconnected callback after onUpdateState since
543 // we don't know if the UI only displays the latest message
544 if (this._rfb_disconnect_reason
!== "") {
545 this._onDisconnected(this, this._rfb_disconnect_reason
);
547 // No reason means clean disconnect
548 this._onDisconnected(this);
556 case 'disconnecting':
559 this._disconnTimer
= setTimeout(function () {
560 this._rfb_disconnect_reason
= _("Disconnect timeout");
561 this._updateConnectionState('disconnected');
562 }.bind(this), this._disconnectTimeout
* 1000);
567 /* Print errors and disconnect
569 * The optional parameter 'details' is used for information that
570 * should be logged but not sent to the user interface.
572 _fail: function (msg
, details
) {
574 if (typeof details
!== 'undefined') {
575 fullmsg
= msg
+ " (" + details
+ ")";
577 switch (this._rfb_connection_state
) {
578 case 'disconnecting':
579 Log
.Error("Failed when disconnecting: " + fullmsg
);
582 Log
.Error("Failed while connected: " + fullmsg
);
585 Log
.Error("Failed when connecting: " + fullmsg
);
588 Log
.Error("RFB failure: " + fullmsg
);
591 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
593 // Transition to disconnected without waiting for socket to close
594 this._updateConnectionState('disconnecting');
595 this._updateConnectionState('disconnected');
601 * Send a notification to the UI. Valid levels are:
602 * 'normal'|'warn'|'error'
604 * NOTE: Options could be added in the future.
605 * NOTE: If this function is called multiple times, remember that the
606 * interface could be only showing the latest notification.
608 _notification: function(msg
, level
, options
) {
613 Log
.Debug("Notification[" + level
+ "]:" + msg
);
616 Log
.Error("Invalid notification level: " + level
);
621 this._onNotification(this, msg
, level
, options
);
623 this._onNotification(this, msg
, level
);
627 _handle_message: function () {
628 if (this._sock
.rQlen() === 0) {
629 Log
.Warn("handle_message called on an empty receive queue");
633 switch (this._rfb_connection_state
) {
635 Log
.Error("Got data while disconnected");
639 if (this._flushing
) {
642 if (!this._normal_msg()) {
645 if (this._sock
.rQlen() === 0) {
656 _handleKeyEvent: function (keysym
, code
, down
) {
657 this.sendKey(keysym
, code
, down
);
660 _handleMouseButton: function (x
, y
, down
, bmask
) {
662 this._mouse_buttonMask
|= bmask
;
664 this._mouse_buttonMask
&= ~bmask
;
667 if (this._viewportDrag
) {
668 if (down
&& !this._viewportDragging
) {
669 this._viewportDragging
= true;
670 this._viewportDragPos
= {'x': x
, 'y': y
};
672 // Skip sending mouse events
675 this._viewportDragging
= false;
677 // If the viewport didn't actually move, then treat as a mouse click event
678 // Send the button down event here, as the button up event is sent at the end of this function
679 if (!this._viewportHasMoved
&& !this._view_only
) {
680 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
682 this._viewportHasMoved
= false;
686 if (this._view_only
) { return; } // View only, skip mouse events
688 if (this._rfb_connection_state
!== 'connected') { return; }
689 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
692 _handleMouseMove: function (x
, y
) {
693 if (this._viewportDragging
) {
694 var deltaX
= this._viewportDragPos
.x
- x
;
695 var deltaY
= this._viewportDragPos
.y
- y
;
697 // The goal is to trigger on a certain physical width, the
698 // devicePixelRatio brings us a bit closer but is not optimal.
699 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
701 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
702 Math
.abs(deltaY
) > dragThreshold
)) {
703 this._viewportHasMoved
= true;
705 this._viewportDragPos
= {'x': x
, 'y': y
};
706 this._display
.viewportChangePos(deltaX
, deltaY
);
709 // Skip sending mouse events
713 if (this._view_only
) { return; } // View only, skip mouse events
715 if (this._rfb_connection_state
!== 'connected') { return; }
716 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
721 _negotiate_protocol_version: function () {
722 if (this._sock
.rQlen() < 12) {
723 return this._fail("Error while negotiating with server",
724 "Incomplete protocol version");
727 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
728 Log
.Info("Server ProtocolVersion: " + sversion
);
731 case "000.000": // UltraVNC repeater
735 case "003.006": // UltraVNC
736 case "003.889": // Apple Remote Desktop
737 this._rfb_version
= 3.3;
740 this._rfb_version
= 3.7;
743 case "004.000": // Intel AMT KVM
744 case "004.001": // RealVNC 4.6
745 case "005.000": // RealVNC 5.3
746 this._rfb_version
= 3.8;
749 return this._fail("Unsupported server",
750 "Invalid server version: " + sversion
);
754 var repeaterID
= this._repeaterID
;
755 while (repeaterID
.length
< 250) {
758 this._sock
.send_string(repeaterID
);
762 if (this._rfb_version
> this._rfb_max_version
) {
763 this._rfb_version
= this._rfb_max_version
;
766 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
767 ".00" + ((this._rfb_version
* 10) % 10);
768 this._sock
.send_string("RFB " + cversion
+ "\n");
769 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
771 this._rfb_init_state
= 'Security';
774 _negotiate_security: function () {
775 // Polyfill since IE and PhantomJS doesn't have
776 // TypedArray.includes()
777 function includes(item
, array
) {
778 for (var i
= 0; i
< array
.length
; i
++) {
779 if (array
[i
] === item
) {
786 if (this._rfb_version
>= 3.7) {
787 // Server sends supported list, client decides
788 var num_types
= this._sock
.rQshift8();
789 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
791 if (num_types
=== 0) {
792 var strlen
= this._sock
.rQshift32();
793 var reason
= this._sock
.rQshiftStr(strlen
);
794 return this._fail("Error while negotiating with server",
795 "Security failure: " + reason
);
798 var types
= this._sock
.rQshiftBytes(num_types
);
799 Log
.Debug("Server security types: " + types
);
801 // Look for each auth in preferred order
802 this._rfb_auth_scheme
= 0;
803 if (includes(1, types
)) {
804 this._rfb_auth_scheme
= 1; // None
805 } else if (includes(22, types
)) {
806 this._rfb_auth_scheme
= 22; // XVP
807 } else if (includes(16, types
)) {
808 this._rfb_auth_scheme
= 16; // Tight
809 } else if (includes(2, types
)) {
810 this._rfb_auth_scheme
= 2; // VNC Auth
812 return this._fail("Unsupported server",
813 "Unsupported security types: " + types
);
816 this._sock
.send([this._rfb_auth_scheme
]);
819 if (this._sock
.rQwait("security scheme", 4)) { return false; }
820 this._rfb_auth_scheme
= this._sock
.rQshift32();
823 this._rfb_init_state
= 'Authentication';
824 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
826 return this._init_msg(); // jump to authentication
830 _negotiate_xvp_auth: function () {
831 var xvp_sep
= this._xvp_password_sep
;
832 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
833 if (xvp_auth
.length
< 3) {
834 var msg
= 'XVP credentials required (user' + xvp_sep
+
835 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
836 this._onPasswordRequired(this, msg
);
840 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
841 String
.fromCharCode(xvp_auth
[1].length
) +
844 this._sock
.send_string(xvp_auth_str
);
845 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
846 this._rfb_auth_scheme
= 2;
847 return this._negotiate_authentication();
850 _negotiate_std_vnc_auth: function () {
851 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
853 if (this._rfb_password
.length
=== 0) {
854 this._onPasswordRequired(this);
858 // TODO(directxman12): make genDES not require an Array
859 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
860 var response
= RFB
.genDES(this._rfb_password
, challenge
);
861 this._sock
.send(response
);
862 this._rfb_init_state
= "SecurityResult";
866 _negotiate_tight_tunnels: function (numTunnels
) {
867 var clientSupportedTunnelTypes
= {
868 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
870 var serverSupportedTunnelTypes
= {};
871 // receive tunnel capabilities
872 for (var i
= 0; i
< numTunnels
; i
++) {
873 var cap_code
= this._sock
.rQshift32();
874 var cap_vendor
= this._sock
.rQshiftStr(4);
875 var cap_signature
= this._sock
.rQshiftStr(8);
876 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
879 // choose the notunnel type
880 if (serverSupportedTunnelTypes
[0]) {
881 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
882 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
883 return this._fail("Unsupported server",
884 "Client's tunnel type had the incorrect " +
885 "vendor or signature");
887 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
888 return false; // wait until we receive the sub auth count to continue
890 return this._fail("Unsupported server",
891 "Server wanted tunnels, but doesn't support " +
892 "the notunnel type");
896 _negotiate_tight_auth: function () {
897 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
898 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
899 var numTunnels
= this._sock
.rQshift32();
900 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
902 this._rfb_tightvnc
= true;
904 if (numTunnels
> 0) {
905 this._negotiate_tight_tunnels(numTunnels
);
906 return false; // wait until we receive the sub auth to continue
910 // second pass, do the sub-auth negotiation
911 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
912 var subAuthCount
= this._sock
.rQshift32();
913 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
914 this._rfb_init_state
= 'SecurityResult';
918 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
920 var clientSupportedTypes
= {
925 var serverSupportedTypes
= [];
927 for (var i
= 0; i
< subAuthCount
; i
++) {
928 var capNum
= this._sock
.rQshift32();
929 var capabilities
= this._sock
.rQshiftStr(12);
930 serverSupportedTypes
.push(capabilities
);
933 for (var authType
in clientSupportedTypes
) {
934 if (serverSupportedTypes
.indexOf(authType
) != -1) {
935 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
938 case 'STDVNOAUTH__': // no auth
939 this._rfb_init_state
= 'SecurityResult';
941 case 'STDVVNCAUTH_': // VNC auth
942 this._rfb_auth_scheme
= 2;
943 return this._init_msg();
945 return this._fail("Unsupported server",
946 "Unsupported tiny auth scheme: " +
952 return this._fail("Unsupported server",
953 "No supported sub-auth types!");
956 _negotiate_authentication: function () {
957 switch (this._rfb_auth_scheme
) {
958 case 0: // connection failed
959 if (this._sock
.rQwait("auth reason", 4)) { return false; }
960 var strlen
= this._sock
.rQshift32();
961 var reason
= this._sock
.rQshiftStr(strlen
);
962 return this._fail("Authentication failure", reason
);
965 if (this._rfb_version
>= 3.8) {
966 this._rfb_init_state
= 'SecurityResult';
969 this._rfb_init_state
= 'ClientInitialisation';
970 return this._init_msg();
973 return this._negotiate_xvp_auth();
975 case 2: // VNC authentication
976 return this._negotiate_std_vnc_auth();
978 case 16: // TightVNC Security Type
979 return this._negotiate_tight_auth();
982 return this._fail("Unsupported server",
983 "Unsupported auth scheme: " +
984 this._rfb_auth_scheme
);
988 _handle_security_result: function () {
989 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
990 switch (this._sock
.rQshift32()) {
992 this._rfb_init_state
= 'ClientInitialisation';
993 Log
.Debug('Authentication OK');
994 return this._init_msg();
996 if (this._rfb_version
>= 3.8) {
997 var length
= this._sock
.rQshift32();
998 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
999 var reason
= this._sock
.rQshiftStr(length
);
1000 return this._fail("Authentication failure", reason
);
1002 return this._fail("Authentication failure");
1005 return this._fail("Too many authentication attempts");
1007 return this._fail("Unsupported server",
1008 "Unknown SecurityResult");
1012 _negotiate_server_init: function () {
1013 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1016 var width
= this._sock
.rQshift16();
1017 var height
= this._sock
.rQshift16();
1020 var bpp
= this._sock
.rQshift8();
1021 var depth
= this._sock
.rQshift8();
1022 var big_endian
= this._sock
.rQshift8();
1023 var true_color
= this._sock
.rQshift8();
1025 var red_max
= this._sock
.rQshift16();
1026 var green_max
= this._sock
.rQshift16();
1027 var blue_max
= this._sock
.rQshift16();
1028 var red_shift
= this._sock
.rQshift8();
1029 var green_shift
= this._sock
.rQshift8();
1030 var blue_shift
= this._sock
.rQshift8();
1031 this._sock
.rQskipBytes(3); // padding
1033 // NB(directxman12): we don't want to call any callbacks or print messages until
1034 // *after* we're past the point where we could backtrack
1036 /* Connection name/title */
1037 var name_length = this._sock.rQshift32();
1038 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1039 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1041 if (this._rfb_tightvnc) {
1042 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1043 // In TightVNC mode, ServerInit message is extended
1044 var numServerMessages = this._sock.rQshift16();
1045 var numClientMessages = this._sock.rQshift16();
1046 var numEncodings = this._sock.rQshift16();
1047 this._sock.rQskipBytes(2); // padding
1049 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1050 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1052 // we don't actually do anything with the capability information that TIGHT sends,
1053 // so we just skip the all of this.
1055 // TIGHT server message capabilities
1056 this._sock.rQskipBytes(16 * numServerMessages);
1058 // TIGHT client message capabilities
1059 this._sock.rQskipBytes(16 * numClientMessages);
1061 // TIGHT encoding capabilities
1062 this._sock.rQskipBytes(16 * numEncodings);
1065 // NB(directxman12): these are down here so that we don't run them multiple times
1067 Log.Info("Screen: " + width + "x" + height +
1068 ", bpp: " + bpp + ", depth: " + depth +
1069 ", big_endian: " + big_endian +
1070 ", true_color: " + true_color +
1071 ", red_max: " + red_max +
1072 ", green_max: " + green_max +
1073 ", blue_max: " + blue_max +
1074 ", red_shift: " + red_shift +
1075 ", green_shift: " + green_shift +
1076 ", blue_shift: " + blue_shift);
1078 if (big_endian !== 0) {
1079 Log.Warn("Server native endian is not little endian");
1082 if (red_shift !== 16) {
1083 Log.Warn("Server native red-shift is not 16");
1086 if (blue_shift !== 0) {
1087 Log.Warn("Server native blue-shift is not 0");
1090 // we're past the point where we could backtrack, so it's safe to call this
1091 this._onDesktopName(this, this._fb_name);
1093 this._resize(width, height);
1095 if (!this._view_only) { this._keyboard.grab(); }
1096 if (!this._view_only) { this._mouse.grab(); }
1098 this._fb_depth = 24;
1100 if (this._fb_name === "Intel(r) AMT KVM") {
1101 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1105 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1106 this._sendEncodings();
1107 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1109 this._timing.fbu_rt_start = (new Date()).getTime();
1110 this._timing.pixels = 0;
1112 // Cursor will be server side until the server decides to honor
1113 // our request and send over the cursor image
1114 this._display.disableLocalCursor();
1116 this._updateConnectionState('connected');
1120 _sendEncodings: function () {
1123 // In preference order
1124 encs.push(encodings.encodingCopyRect);
1125 // Only supported with full depth support
1126 if (this._fb_depth == 24) {
1127 encs.push(encodings.encodingTight);
1128 encs.push(encodings.encodingHextile);
1129 encs.push(encodings.encodingRRE);
1131 encs.push(encodings.encodingRaw);
1133 // Psuedo-encoding settings
1134 encs.push(encodings.pseudoEncodingTightPNG);
1135 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1136 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1138 encs.push(encodings.pseudoEncodingDesktopSize);
1139 encs.push(encodings.pseudoEncodingLastRect);
1140 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1141 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1142 encs.push(encodings.pseudoEncodingXvp);
1143 encs.push(encodings.pseudoEncodingFence);
1144 encs.push(encodings.pseudoEncodingContinuousUpdates);
1146 if (this._local_cursor && this._fb_depth == 24) {
1147 encs.push(encodings.pseudoEncodingCursor);
1150 RFB.messages.clientEncodings(this._sock, encs);
1153 /* RFB protocol initialization states:
1158 * ClientInitialization - not triggered by server message
1159 * ServerInitialization
1161 _init_msg: function () {
1162 switch (this._rfb_init_state
) {
1163 case 'ProtocolVersion':
1164 return this._negotiate_protocol_version();
1167 return this._negotiate_security();
1169 case 'Authentication':
1170 return this._negotiate_authentication();
1172 case 'SecurityResult':
1173 return this._handle_security_result();
1175 case 'ClientInitialisation':
1176 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1177 this._rfb_init_state
= 'ServerInitialisation';
1180 case 'ServerInitialisation':
1181 return this._negotiate_server_init();
1184 return this._fail("Internal error", "Unknown init state: " +
1185 this._rfb_init_state
);
1189 _handle_set_colour_map_msg: function () {
1190 Log
.Debug("SetColorMapEntries");
1192 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1195 _handle_server_cut_text: function () {
1196 Log
.Debug("ServerCutText");
1198 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1199 this._sock
.rQskipBytes(3); // Padding
1200 var length
= this._sock
.rQshift32();
1201 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1203 var text
= this._sock
.rQshiftStr(length
);
1205 if (this._view_only
) { return true; }
1207 this._onClipboard(this, text
);
1212 _handle_server_fence_msg: function() {
1213 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1214 this._sock
.rQskipBytes(3); // Padding
1215 var flags
= this._sock
.rQshift32();
1216 var length
= this._sock
.rQshift8();
1218 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1221 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1225 var payload
= this._sock
.rQshiftStr(length
);
1227 this._supportsFence
= true;
1232 * (1<<0) - BlockBefore
1233 * (1<<1) - BlockAfter
1238 if (!(flags
& (1<<31))) {
1239 return this._fail("Internal error",
1240 "Unexpected fence response");
1243 // Filter out unsupported flags
1244 // FIXME: support syncNext
1245 flags
&= (1<<0) | (1<<1);
1247 // BlockBefore and BlockAfter are automatically handled by
1248 // the fact that we process each incoming message
1250 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1255 _handle_xvp_msg: function () {
1256 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1257 this._sock
.rQskip8(); // Padding
1258 var xvp_ver
= this._sock
.rQshift8();
1259 var xvp_msg
= this._sock
.rQshift8();
1263 Log
.Error("Operation Failed");
1264 this._notification("XVP Operation Failed", 'error');
1267 this._rfb_xvp_ver
= xvp_ver
;
1268 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1269 this._onXvpInit(this._rfb_xvp_ver
);
1272 this._fail("Unexpected server message",
1273 "Illegal server XVP message " + xvp_msg
);
1280 _normal_msg: function () {
1283 if (this._FBU
.rects
> 0) {
1286 msg_type
= this._sock
.rQshift8();
1290 case 0: // FramebufferUpdate
1291 var ret
= this._framebufferUpdate();
1292 if (ret
&& !this._enabledContinuousUpdates
) {
1293 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1294 this._fb_width
, this._fb_height
);
1298 case 1: // SetColorMapEntries
1299 return this._handle_set_colour_map_msg();
1306 case 3: // ServerCutText
1307 return this._handle_server_cut_text();
1309 case 150: // EndOfContinuousUpdates
1310 var first
= !(this._supportsContinuousUpdates
);
1311 this._supportsContinuousUpdates
= true;
1312 this._enabledContinuousUpdates
= false;
1314 this._enabledContinuousUpdates
= true;
1315 this._updateContinuousUpdates();
1316 Log
.Info("Enabling continuous updates.");
1318 // FIXME: We need to send a framebufferupdaterequest here
1319 // if we add support for turning off continuous updates
1323 case 248: // ServerFence
1324 return this._handle_server_fence_msg();
1327 return this._handle_xvp_msg();
1330 this._fail("Unexpected server message", "Type:" + msg_type
);
1331 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1336 _onFlush: function() {
1337 this._flushing
= false;
1338 // Resume processing
1339 if (this._sock
.rQlen() > 0) {
1340 this._handle_message();
1344 _framebufferUpdate: function () {
1348 if (this._FBU
.rects
=== 0) {
1349 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1350 this._sock
.rQskip8(); // Padding
1351 this._FBU
.rects
= this._sock
.rQshift16();
1352 this._FBU
.bytes
= 0;
1353 this._timing
.cur_fbu
= 0;
1354 if (this._timing
.fbu_rt_start
> 0) {
1355 now
= (new Date()).getTime();
1356 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1359 // Make sure the previous frame is fully rendered first
1360 // to avoid building up an excessive queue
1361 if (this._display
.pending()) {
1362 this._flushing
= true;
1363 this._display
.flush();
1368 while (this._FBU
.rects
> 0) {
1369 if (this._rfb_connection_state
!== 'connected') { return false; }
1371 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1372 if (this._FBU
.bytes
=== 0) {
1373 if (this._sock
.rQwait("rect header", 12)) { return false; }
1374 /* New FramebufferUpdate */
1376 var hdr
= this._sock
.rQshiftBytes(12);
1377 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1378 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1379 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1380 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1381 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1382 (hdr
[10] << 8) + hdr
[11], 10);
1384 this._onFBUReceive(this,
1385 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1386 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1387 'encoding': this._FBU
.encoding
,
1388 'encodingName': encodingName(this._FBU
.encoding
)});
1390 if (!this._encHandlers
[this._FBU
.encoding
]) {
1391 this._fail("Unexpected server message",
1392 "Unsupported encoding " +
1393 this._FBU
.encoding
);
1398 this._timing
.last_fbu
= (new Date()).getTime();
1400 ret
= this._encHandlers
[this._FBU
.encoding
]();
1402 now
= (new Date()).getTime();
1403 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1406 if (!(this._FBU
.encoding
in this._encStats
)) {
1407 this._encStats
[this._FBU
.encoding
] = [0, 0];
1409 this._encStats
[this._FBU
.encoding
][0]++;
1410 this._encStats
[this._FBU
.encoding
][1]++;
1411 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1414 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1415 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1416 this._timing
.fbu_rt_start
> 0) {
1417 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1418 this._timing
.full_fbu_cnt
++;
1419 Log
.Info("Timing of full FBU, curr: " +
1420 this._timing
.cur_fbu
+ ", total: " +
1421 this._timing
.full_fbu_total
+ ", cnt: " +
1422 this._timing
.full_fbu_cnt
+ ", avg: " +
1423 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1426 if (this._timing
.fbu_rt_start
> 0) {
1427 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1428 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1429 this._timing
.fbu_rt_cnt
++;
1430 Log
.Info("full FBU round-trip, cur: " +
1431 fbu_rt_diff
+ ", total: " +
1432 this._timing
.fbu_rt_total
+ ", cnt: " +
1433 this._timing
.fbu_rt_cnt
+ ", avg: " +
1434 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1435 this._timing
.fbu_rt_start
= 0;
1439 if (!ret
) { return ret
; } // need more data
1442 this._display
.flip();
1444 this._onFBUComplete(this);
1446 return true; // We finished this FBU
1449 _updateContinuousUpdates: function() {
1450 if (!this._enabledContinuousUpdates
) { return; }
1452 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1453 this._fb_width
, this._fb_height
);
1456 _resize: function(width
, height
) {
1457 this._fb_width
= width
;
1458 this._fb_height
= height
;
1460 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1462 this._display
.resize(this._fb_width
, this._fb_height
);
1463 this._onFBResize(this, this._fb_width
, this._fb_height
);
1465 this._timing
.fbu_rt_start
= (new Date()).getTime();
1466 this._updateContinuousUpdates();
1470 make_properties(RFB
, [
1471 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1472 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1473 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1474 ['shared', 'rw', 'bool'], // Request shared mode
1475 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1476 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1477 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1478 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1479 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1480 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1482 // Callback functions
1483 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1484 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1485 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1486 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1487 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1488 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1489 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1490 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1491 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1492 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1493 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1496 RFB
.prototype.set_local_cursor = function (cursor
) {
1497 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1498 this._local_cursor
= false;
1499 this._display
.disableLocalCursor(); //Only show server-side cursor
1501 if (this._display
.get_cursor_uri()) {
1502 this._local_cursor
= true;
1504 Log
.Warn("Browser does not support local cursor");
1505 this._display
.disableLocalCursor();
1509 // Need to send an updated list of encodings if we are connected
1510 if (this._rfb_connection_state
=== "connected") {
1511 this._sendEncodings();
1515 RFB
.prototype.set_view_only = function (view_only
) {
1516 this._view_only
= view_only
;
1518 if (this._rfb_connection_state
=== "connecting" ||
1519 this._rfb_connection_state
=== "connected") {
1521 this._keyboard
.ungrab();
1522 this._mouse
.ungrab();
1524 this._keyboard
.grab();
1530 RFB
.prototype.get_display = function () { return this._display
; };
1531 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1532 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1536 keyEvent: function (sock
, keysym
, down
) {
1537 var buff
= sock
._sQ
;
1538 var offset
= sock
._sQlen
;
1540 buff
[offset
] = 4; // msg-type
1541 buff
[offset
+ 1] = down
;
1543 buff
[offset
+ 2] = 0;
1544 buff
[offset
+ 3] = 0;
1546 buff
[offset
+ 4] = (keysym
>> 24);
1547 buff
[offset
+ 5] = (keysym
>> 16);
1548 buff
[offset
+ 6] = (keysym
>> 8);
1549 buff
[offset
+ 7] = keysym
;
1555 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1556 function getRFBkeycode(xt_scancode
) {
1557 var upperByte
= (keycode
>> 8);
1558 var lowerByte
= (keycode
& 0x00ff);
1559 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1560 lowerByte
= lowerByte
| 0x80;
1566 var buff
= sock
._sQ
;
1567 var offset
= sock
._sQlen
;
1569 buff
[offset
] = 255; // msg-type
1570 buff
[offset
+ 1] = 0; // sub msg-type
1572 buff
[offset
+ 2] = (down
>> 8);
1573 buff
[offset
+ 3] = down
;
1575 buff
[offset
+ 4] = (keysym
>> 24);
1576 buff
[offset
+ 5] = (keysym
>> 16);
1577 buff
[offset
+ 6] = (keysym
>> 8);
1578 buff
[offset
+ 7] = keysym
;
1580 var RFBkeycode
= getRFBkeycode(keycode
);
1582 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1583 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1584 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1585 buff
[offset
+ 11] = RFBkeycode
;
1591 pointerEvent: function (sock
, x
, y
, mask
) {
1592 var buff
= sock
._sQ
;
1593 var offset
= sock
._sQlen
;
1595 buff
[offset
] = 5; // msg-type
1597 buff
[offset
+ 1] = mask
;
1599 buff
[offset
+ 2] = x
>> 8;
1600 buff
[offset
+ 3] = x
;
1602 buff
[offset
+ 4] = y
>> 8;
1603 buff
[offset
+ 5] = y
;
1609 // TODO(directxman12): make this unicode compatible?
1610 clientCutText: function (sock
, text
) {
1611 var buff
= sock
._sQ
;
1612 var offset
= sock
._sQlen
;
1614 buff
[offset
] = 6; // msg-type
1616 buff
[offset
+ 1] = 0; // padding
1617 buff
[offset
+ 2] = 0; // padding
1618 buff
[offset
+ 3] = 0; // padding
1620 var n
= text
.length
;
1622 buff
[offset
+ 4] = n
>> 24;
1623 buff
[offset
+ 5] = n
>> 16;
1624 buff
[offset
+ 6] = n
>> 8;
1625 buff
[offset
+ 7] = n
;
1627 for (var i
= 0; i
< n
; i
++) {
1628 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1631 sock
._sQlen
+= 8 + n
;
1635 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1636 var buff
= sock
._sQ
;
1637 var offset
= sock
._sQlen
;
1639 buff
[offset
] = 251; // msg-type
1640 buff
[offset
+ 1] = 0; // padding
1641 buff
[offset
+ 2] = width
>> 8; // width
1642 buff
[offset
+ 3] = width
;
1643 buff
[offset
+ 4] = height
>> 8; // height
1644 buff
[offset
+ 5] = height
;
1646 buff
[offset
+ 6] = 1; // number-of-screens
1647 buff
[offset
+ 7] = 0; // padding
1650 buff
[offset
+ 8] = id
>> 24; // id
1651 buff
[offset
+ 9] = id
>> 16;
1652 buff
[offset
+ 10] = id
>> 8;
1653 buff
[offset
+ 11] = id
;
1654 buff
[offset
+ 12] = 0; // x-position
1655 buff
[offset
+ 13] = 0;
1656 buff
[offset
+ 14] = 0; // y-position
1657 buff
[offset
+ 15] = 0;
1658 buff
[offset
+ 16] = width
>> 8; // width
1659 buff
[offset
+ 17] = width
;
1660 buff
[offset
+ 18] = height
>> 8; // height
1661 buff
[offset
+ 19] = height
;
1662 buff
[offset
+ 20] = flags
>> 24; // flags
1663 buff
[offset
+ 21] = flags
>> 16;
1664 buff
[offset
+ 22] = flags
>> 8;
1665 buff
[offset
+ 23] = flags
;
1671 clientFence: function (sock
, flags
, payload
) {
1672 var buff
= sock
._sQ
;
1673 var offset
= sock
._sQlen
;
1675 buff
[offset
] = 248; // msg-type
1677 buff
[offset
+ 1] = 0; // padding
1678 buff
[offset
+ 2] = 0; // padding
1679 buff
[offset
+ 3] = 0; // padding
1681 buff
[offset
+ 4] = flags
>> 24; // flags
1682 buff
[offset
+ 5] = flags
>> 16;
1683 buff
[offset
+ 6] = flags
>> 8;
1684 buff
[offset
+ 7] = flags
;
1686 var n
= payload
.length
;
1688 buff
[offset
+ 8] = n
; // length
1690 for (var i
= 0; i
< n
; i
++) {
1691 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1694 sock
._sQlen
+= 9 + n
;
1698 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1699 var buff
= sock
._sQ
;
1700 var offset
= sock
._sQlen
;
1702 buff
[offset
] = 150; // msg-type
1703 buff
[offset
+ 1] = enable
; // enable-flag
1705 buff
[offset
+ 2] = x
>> 8; // x
1706 buff
[offset
+ 3] = x
;
1707 buff
[offset
+ 4] = y
>> 8; // y
1708 buff
[offset
+ 5] = y
;
1709 buff
[offset
+ 6] = width
>> 8; // width
1710 buff
[offset
+ 7] = width
;
1711 buff
[offset
+ 8] = height
>> 8; // height
1712 buff
[offset
+ 9] = height
;
1718 pixelFormat: function (sock
, depth
, true_color
) {
1719 var buff
= sock
._sQ
;
1720 var offset
= sock
._sQlen
;
1726 } else if (depth
> 8) {
1732 bits
= Math
.floor(depth
/3);
1734 buff
[offset
] = 0; // msg-type
1736 buff
[offset
+ 1] = 0; // padding
1737 buff
[offset
+ 2] = 0; // padding
1738 buff
[offset
+ 3] = 0; // padding
1740 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1741 buff
[offset
+ 5] = depth
; // depth
1742 buff
[offset
+ 6] = 0; // little-endian
1743 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1745 buff
[offset
+ 8] = 0; // red-max
1746 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1748 buff
[offset
+ 10] = 0; // green-max
1749 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1751 buff
[offset
+ 12] = 0; // blue-max
1752 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1754 buff
[offset
+ 14] = bits
* 2; // red-shift
1755 buff
[offset
+ 15] = bits
* 1; // green-shift
1756 buff
[offset
+ 16] = bits
* 0; // blue-shift
1758 buff
[offset
+ 17] = 0; // padding
1759 buff
[offset
+ 18] = 0; // padding
1760 buff
[offset
+ 19] = 0; // padding
1766 clientEncodings: function (sock
, encodings
) {
1767 var buff
= sock
._sQ
;
1768 var offset
= sock
._sQlen
;
1770 buff
[offset
] = 2; // msg-type
1771 buff
[offset
+ 1] = 0; // padding
1773 buff
[offset
+ 2] = encodings
.length
>> 8;
1774 buff
[offset
+ 3] = encodings
.length
;
1776 var i
, j
= offset
+ 4;
1777 for (i
= 0; i
< encodings
.length
; i
++) {
1778 var enc
= encodings
[i
];
1779 buff
[j
] = enc
>> 24;
1780 buff
[j
+ 1] = enc
>> 16;
1781 buff
[j
+ 2] = enc
>> 8;
1787 sock
._sQlen
+= j
- offset
;
1791 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1792 var buff
= sock
._sQ
;
1793 var offset
= sock
._sQlen
;
1795 if (typeof(x
) === "undefined") { x
= 0; }
1796 if (typeof(y
) === "undefined") { y
= 0; }
1798 buff
[offset
] = 3; // msg-type
1799 buff
[offset
+ 1] = incremental
? 1 : 0;
1801 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1802 buff
[offset
+ 3] = x
& 0xFF;
1804 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1805 buff
[offset
+ 5] = y
& 0xFF;
1807 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1808 buff
[offset
+ 7] = w
& 0xFF;
1810 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1811 buff
[offset
+ 9] = h
& 0xFF;
1818 RFB
.genDES = function (password
, challenge
) {
1820 for (var i
= 0; i
< password
.length
; i
++) {
1821 passwd
.push(password
.charCodeAt(i
));
1823 return (new DES(passwd
)).encrypt(challenge
);
1826 RFB
.encodingHandlers
= {
1828 if (this._FBU
.lines
=== 0) {
1829 this._FBU
.lines
= this._FBU
.height
;
1832 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1833 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1834 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1835 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1836 var curr_height
= Math
.min(this._FBU
.lines
,
1837 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1838 var data
= this._sock
.get_rQ();
1839 var index
= this._sock
.get_rQi();
1840 if (this._fb_depth
== 8) {
1841 var pixels
= this._FBU
.width
* curr_height
1842 var newdata
= new Uint8Array(pixels
* 4);
1844 for (i
= 0;i
< pixels
;i
++) {
1845 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1846 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1847 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1848 newdata
[i
* 4 + 4] = 0;
1853 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1854 curr_height
, data
, index
);
1855 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1856 this._FBU
.lines
-= curr_height
;
1858 if (this._FBU
.lines
> 0) {
1859 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1862 this._FBU
.bytes
= 0;
1868 COPYRECT: function () {
1869 this._FBU
.bytes
= 4;
1870 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1871 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1872 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1876 this._FBU
.bytes
= 0;
1882 if (this._FBU
.subrects
=== 0) {
1883 this._FBU
.bytes
= 4 + 4;
1884 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1885 this._FBU
.subrects
= this._sock
.rQshift32();
1886 color
= this._sock
.rQshiftBytes(4); // Background
1887 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1890 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1891 color
= this._sock
.rQshiftBytes(4);
1892 var x
= this._sock
.rQshift16();
1893 var y
= this._sock
.rQshift16();
1894 var width
= this._sock
.rQshift16();
1895 var height
= this._sock
.rQshift16();
1896 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1897 this._FBU
.subrects
--;
1900 if (this._FBU
.subrects
> 0) {
1901 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1902 this._FBU
.bytes
= (4 + 8) * chunk
;
1905 this._FBU
.bytes
= 0;
1911 HEXTILE: function () {
1912 var rQ
= this._sock
.get_rQ();
1913 var rQi
= this._sock
.get_rQi();
1915 if (this._FBU
.tiles
=== 0) {
1916 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1917 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1918 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1919 this._FBU
.tiles
= this._FBU
.total_tiles
;
1922 while (this._FBU
.tiles
> 0) {
1923 this._FBU
.bytes
= 1;
1924 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1925 var subencoding
= rQ
[rQi
]; // Peek
1926 if (subencoding
> 30) { // Raw
1927 this._fail("Unexpected server message",
1928 "Illegal hextile subencoding: " + subencoding
);
1933 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1934 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1935 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1936 var x
= this._FBU
.x
+ tile_x
* 16;
1937 var y
= this._FBU
.y
+ tile_y
* 16;
1938 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1939 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1941 // Figure out how much we are expecting
1942 if (subencoding
& 0x01) { // Raw
1943 this._FBU
.bytes
+= w
* h
* 4;
1945 if (subencoding
& 0x02) { // Background
1946 this._FBU
.bytes
+= 4;
1948 if (subencoding
& 0x04) { // Foreground
1949 this._FBU
.bytes
+= 4;
1951 if (subencoding
& 0x08) { // AnySubrects
1952 this._FBU
.bytes
++; // Since we aren't shifting it off
1953 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1954 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1955 if (subencoding
& 0x10) { // SubrectsColoured
1956 this._FBU
.bytes
+= subrects
* (4 + 2);
1958 this._FBU
.bytes
+= subrects
* 2;
1963 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1965 // We know the encoding and have a whole tile
1966 this._FBU
.subencoding
= rQ
[rQi
];
1968 if (this._FBU
.subencoding
=== 0) {
1969 if (this._FBU
.lastsubencoding
& 0x01) {
1970 // Weird: ignore blanks are RAW
1971 Log
.Debug(" Ignoring blank after RAW");
1973 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1975 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1976 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1977 rQi
+= this._FBU
.bytes
- 1;
1979 if (this._FBU
.subencoding
& 0x02) { // Background
1980 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1983 if (this._FBU
.subencoding
& 0x04) { // Foreground
1984 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1988 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1989 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1993 for (var s
= 0; s
< subrects
; s
++) {
1995 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1996 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1999 color
= this._FBU
.foreground
;
2004 var sy
= (xy
& 0x0f);
2008 var sw
= (wh
>> 4) + 1;
2009 var sh
= (wh
& 0x0f) + 1;
2011 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2014 this._display
.finishTile();
2016 this._sock
.set_rQi(rQi
);
2017 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2018 this._FBU
.bytes
= 0;
2022 if (this._FBU
.tiles
=== 0) {
2029 TIGHT: function () {
2030 this._FBU
.bytes
= 1; // compression-control byte
2031 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2033 var checksum = function (data
) {
2035 for (var i
= 0; i
< data
.length
; i
++) {
2037 if (sum
> 65536) sum
-= 65536;
2042 var resetStreams
= 0;
2044 var decompress = function (data
, expected
) {
2045 for (var i
= 0; i
< 4; i
++) {
2046 if ((resetStreams
>> i
) & 1) {
2047 this._FBU
.zlibs
[i
].reset();
2048 Log
.Info("Reset zlib stream " + i
);
2052 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2053 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2054 /*if (uncompressed.status !== 0) {
2055 Log.Error("Invalid data in zlib stream");
2058 //return uncompressed.data;
2059 return uncompressed
;
2062 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2063 // Convert indexed (palette based) image data to RGB
2064 // TODO: reduce number of calculations inside loop
2065 var dest
= this._destBuff
;
2066 var w
= Math
.floor((width
+ 7) / 8);
2067 var w1
= Math
.floor(width
/ 8);
2069 /*for (var y = 0; y < height; y++) {
2071 var yoffset = y * width;
2072 var ybitoffset = y * w;
2073 var xoffset, targetbyte;
2074 for (x = 0; x < w1; x++) {
2075 xoffset = yoffset + x * 8;
2076 targetbyte = data[ybitoffset + x];
2077 for (b = 7; b >= 0; b--) {
2078 dp = (xoffset + 7 - b) * 3;
2079 sp = (targetbyte >> b & 1) * 3;
2080 dest[dp] = palette[sp];
2081 dest[dp + 1] = palette[sp + 1];
2082 dest[dp + 2] = palette[sp + 2];
2086 xoffset = yoffset + x * 8;
2087 targetbyte = data[ybitoffset + x];
2088 for (b = 7; b >= 8 - width % 8; b--) {
2089 dp = (xoffset + 7 - b) * 3;
2090 sp = (targetbyte >> b & 1) * 3;
2091 dest[dp] = palette[sp];
2092 dest[dp + 1] = palette[sp + 1];
2093 dest[dp + 2] = palette[sp + 2];
2097 for (var y
= 0; y
< height
; y
++) {
2099 for (x
= 0; x
< w1
; x
++) {
2100 for (b
= 7; b
>= 0; b
--) {
2101 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2102 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2103 dest
[dp
] = palette
[sp
];
2104 dest
[dp
+ 1] = palette
[sp
+ 1];
2105 dest
[dp
+ 2] = palette
[sp
+ 2];
2110 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2111 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2112 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2113 dest
[dp
] = palette
[sp
];
2114 dest
[dp
+ 1] = palette
[sp
+ 1];
2115 dest
[dp
+ 2] = palette
[sp
+ 2];
2123 var indexedToRGBX = function (data
, palette
, width
, height
) {
2124 // Convert indexed (palette based) image data to RGB
2125 var dest
= this._destBuff
;
2126 var total
= width
* height
* 4;
2127 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2128 var sp
= data
[j
] * 3;
2129 dest
[i
] = palette
[sp
];
2130 dest
[i
+ 1] = palette
[sp
+ 1];
2131 dest
[i
+ 2] = palette
[sp
+ 2];
2138 var rQi
= this._sock
.get_rQi();
2139 var rQ
= this._sock
.rQwhole();
2141 var cl_header
, cl_data
;
2143 var handlePalette = function () {
2144 var numColors
= rQ
[rQi
+ 2] + 1;
2145 var paletteSize
= numColors
* 3;
2146 this._FBU
.bytes
+= paletteSize
;
2147 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2149 var bpp
= (numColors
<= 2) ? 1 : 8;
2150 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2152 if (rowSize
* this._FBU
.height
< 12) {
2155 cl_data
= rowSize
* this._FBU
.height
;
2156 //clength = [0, rowSize * this._FBU.height];
2158 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2159 var cl_offset
= rQi
+ 3 + paletteSize
;
2162 cl_data
+= rQ
[cl_offset
] & 0x7f;
2163 if (rQ
[cl_offset
] & 0x80) {
2165 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2166 if (rQ
[cl_offset
+ 1] & 0x80) {
2168 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2171 // end inline getTightCLength
2174 this._FBU
.bytes
+= cl_header
+ cl_data
;
2175 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2177 // Shift ctl, filter id, num colors, palette entries, and clength off
2178 this._sock
.rQskipBytes(3);
2179 //var palette = this._sock.rQshiftBytes(paletteSize);
2180 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2181 this._sock
.rQskipBytes(cl_header
);
2184 data
= this._sock
.rQshiftBytes(cl_data
);
2186 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2189 // Convert indexed (palette based) image data to RGB
2191 if (numColors
== 2) {
2192 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2193 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2195 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2196 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2203 var handleCopy = function () {
2205 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2206 if (uncompressedSize
< 12) {
2209 cl_data
= uncompressedSize
;
2211 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2212 var cl_offset
= rQi
+ 1;
2215 cl_data
+= rQ
[cl_offset
] & 0x7f;
2216 if (rQ
[cl_offset
] & 0x80) {
2218 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2219 if (rQ
[cl_offset
+ 1] & 0x80) {
2221 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2224 // end inline getTightCLength
2226 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2227 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2229 // Shift ctl, clength off
2230 this._sock
.rQshiftBytes(1 + cl_header
);
2233 data
= this._sock
.rQshiftBytes(cl_data
);
2235 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2238 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2243 var ctl
= this._sock
.rQpeek8();
2245 // Keep tight reset bits
2246 resetStreams
= ctl
& 0xF;
2248 // Figure out filter
2250 streamId
= ctl
& 0x3;
2252 if (ctl
=== 0x08) cmode
= "fill";
2253 else if (ctl
=== 0x09) cmode
= "jpeg";
2254 else if (ctl
=== 0x0A) cmode
= "png";
2255 else if (ctl
& 0x04) cmode
= "filter";
2256 else if (ctl
< 0x04) cmode
= "copy";
2257 else return this._fail("Unexpected server message",
2258 "Illegal tight compression received, " +
2262 // fill use depth because TPIXELs drop the padding byte
2263 case "fill": // TPIXEL
2264 this._FBU
.bytes
+= 3;
2266 case "jpeg": // max clength
2267 this._FBU
.bytes
+= 3;
2269 case "png": // max clength
2270 this._FBU
.bytes
+= 3;
2272 case "filter": // filter id + num colors if palette
2273 this._FBU
.bytes
+= 2;
2279 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2281 // Determine FBU.bytes
2285 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);
2286 this._sock
.rQskipBytes(4);
2290 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2291 var cl_offset
= rQi
+ 1;
2294 cl_data
+= rQ
[cl_offset
] & 0x7f;
2295 if (rQ
[cl_offset
] & 0x80) {
2297 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2298 if (rQ
[cl_offset
+ 1] & 0x80) {
2300 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2303 // end inline getTightCLength
2304 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2305 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2307 // We have everything, render it
2308 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2309 data
= this._sock
.rQshiftBytes(cl_data
);
2310 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2313 var filterId
= rQ
[rQi
+ 1];
2314 if (filterId
=== 1) {
2315 if (!handlePalette()) { return false; }
2317 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2318 // Filter 2, Gradient is valid but not use if jpeg is enabled
2319 this._fail("Unexpected server message",
2320 "Unsupported tight subencoding received, " +
2321 "filter: " + filterId
);
2325 if (!handleCopy()) { return false; }
2330 this._FBU
.bytes
= 0;
2336 last_rect: function () {
2337 this._FBU
.rects
= 0;
2341 ExtendedDesktopSize: function () {
2342 this._FBU
.bytes
= 1;
2343 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2345 this._supportsSetDesktopSize
= true;
2346 var number_of_screens
= this._sock
.rQpeek8();
2348 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2349 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2351 this._sock
.rQskipBytes(1); // number-of-screens
2352 this._sock
.rQskipBytes(3); // padding
2354 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2355 // Save the id and flags of the first screen
2357 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2358 this._sock
.rQskipBytes(2); // x-position
2359 this._sock
.rQskipBytes(2); // y-position
2360 this._sock
.rQskipBytes(2); // width
2361 this._sock
.rQskipBytes(2); // height
2362 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2364 this._sock
.rQskipBytes(16);
2369 * The x-position indicates the reason for the change:
2371 * 0 - server resized on its own
2372 * 1 - this client requested the resize
2373 * 2 - another client requested the resize
2376 // We need to handle errors when we requested the resize.
2377 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2379 // The y-position indicates the status code from the server
2380 switch (this._FBU
.y
) {
2382 msg
= "Resize is administratively prohibited";
2385 msg
= "Out of resources";
2388 msg
= "Invalid screen layout";
2391 msg
= "Unknown reason";
2394 this._notification("Server did not accept the resize request: "
2397 this._resize(this._FBU
.width
, this._FBU
.height
);
2400 this._FBU
.bytes
= 0;
2401 this._FBU
.rects
-= 1;
2405 DesktopSize: function () {
2406 this._resize(this._FBU
.width
, this._FBU
.height
);
2407 this._FBU
.bytes
= 0;
2408 this._FBU
.rects
-= 1;
2412 Cursor: function () {
2413 Log
.Debug(">> set_cursor");
2414 var x
= this._FBU
.x
; // hotspot-x
2415 var y
= this._FBU
.y
; // hotspot-y
2416 var w
= this._FBU
.width
;
2417 var h
= this._FBU
.height
;
2419 var pixelslength
= w
* h
* 4;
2420 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2422 this._FBU
.bytes
= pixelslength
+ masklength
;
2423 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2425 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2426 this._sock
.rQshiftBytes(masklength
),
2429 this._FBU
.bytes
= 0;
2432 Log
.Debug("<< set_cursor");
2436 QEMUExtendedKeyEvent: function () {
2439 // Old Safari doesn't support creating keyboard events
2441 var keyboardEvent
= document
.createEvent("keyboardEvent");
2442 if (keyboardEvent
.code
!== undefined) {
2443 this._qemuExtKeyEventSupported
= true;