]> git.proxmox.com Git - mirror_novnc.git/blob - core/rfb.js
Handle server-side disconnections
[mirror_novnc.git] / core / rfb.js
1 /*
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)
6 *
7 * See README.md for usage and integration instructions.
8 *
9 * TIGHT decoder portion:
10 * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
11 */
12
13 /* [module]
14 * import Util from "./util";
15 * import Display from "./display";
16 * import { Keyboard, Mouse } from "./input/devices"
17 * import Websock from "./websock"
18 * import Base64 from "./base64";
19 * import DES from "./des";
20 * import KeyTable from "./input/keysym";
21 * import XtScancode from "./input/xtscancodes";
22 * import Inflator from "./inflator.mod";
23 */
24 /*jslint white: false, browser: true */
25 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
26
27 /* [module] export default */ function RFB(defaults) {
28 "use strict";
29 if (!defaults) {
30 defaults = {};
31 }
32
33 this._rfb_host = '';
34 this._rfb_port = 5900;
35 this._rfb_password = '';
36 this._rfb_path = '';
37
38 this._rfb_connection_state = '';
39 this._rfb_init_state = '';
40 this._rfb_version = 0;
41 this._rfb_max_version = 3.8;
42 this._rfb_auth_scheme = '';
43 this._rfb_disconnect_reason = "";
44
45 this._rfb_tightvnc = false;
46 this._rfb_xvp_ver = 0;
47
48 // In preference order
49 this._encodings = [
50 ['COPYRECT', 0x01 ],
51 ['TIGHT', 0x07 ],
52 ['TIGHT_PNG', -260 ],
53 ['HEXTILE', 0x05 ],
54 ['RRE', 0x02 ],
55 ['RAW', 0x00 ],
56
57 // Psuedo-encoding settings
58
59 //['JPEG_quality_lo', -32 ],
60 ['JPEG_quality_med', -26 ],
61 //['JPEG_quality_hi', -23 ],
62 //['compress_lo', -255 ],
63 ['compress_hi', -247 ],
64
65 ['DesktopSize', -223 ],
66 ['last_rect', -224 ],
67 ['Cursor', -239 ],
68 ['QEMUExtendedKeyEvent', -258 ],
69 ['ExtendedDesktopSize', -308 ],
70 ['xvp', -309 ],
71 ['Fence', -312 ],
72 ['ContinuousUpdates', -313 ]
73 ];
74
75 this._encHandlers = {};
76 this._encNames = {};
77 this._encStats = {};
78
79 this._sock = null; // Websock object
80 this._display = null; // Display object
81 this._flushing = false; // Display flushing state
82 this._keyboard = null; // Keyboard input handler object
83 this._mouse = null; // Mouse input handler object
84 this._disconnTimer = null; // disconnection timer
85
86 this._supportsFence = false;
87
88 this._supportsContinuousUpdates = false;
89 this._enabledContinuousUpdates = false;
90
91 // Frame buffer update state
92 this._FBU = {
93 rects: 0,
94 subrects: 0, // RRE
95 lines: 0, // RAW
96 tiles: 0, // HEXTILE
97 bytes: 0,
98 x: 0,
99 y: 0,
100 width: 0,
101 height: 0,
102 encoding: 0,
103 subencoding: -1,
104 background: null,
105 zlib: [] // TIGHT zlib streams
106 };
107
108 this._fb_Bpp = 4;
109 this._fb_depth = 3;
110 this._fb_width = 0;
111 this._fb_height = 0;
112 this._fb_name = "";
113
114 this._destBuff = null;
115 this._paletteBuff = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
116
117 this._rre_chunk_sz = 100;
118
119 this._timing = {
120 last_fbu: 0,
121 fbu_total: 0,
122 fbu_total_cnt: 0,
123 full_fbu_total: 0,
124 full_fbu_cnt: 0,
125
126 fbu_rt_start: 0,
127 fbu_rt_total: 0,
128 fbu_rt_cnt: 0,
129 pixels: 0
130 };
131
132 this._supportsSetDesktopSize = false;
133 this._screen_id = 0;
134 this._screen_flags = 0;
135
136 // Mouse state
137 this._mouse_buttonMask = 0;
138 this._mouse_arr = [];
139 this._viewportDragging = false;
140 this._viewportDragPos = {};
141 this._viewportHasMoved = false;
142
143 // QEMU Extended Key Event support - default to false
144 this._qemuExtKeyEventSupported = false;
145
146 // set the default value on user-facing properties
147 Util.set_defaults(this, defaults, {
148 'target': 'null', // VNC display rendering Canvas object
149 'focusContainer': document, // DOM element that captures keyboard input
150 'encrypt': false, // Use TLS/SSL/wss encryption
151 'true_color': true, // Request true color pixel data
152 'local_cursor': false, // Request locally rendered cursor
153 'shared': true, // Request shared mode
154 'view_only': false, // Disable client mouse/keyboard
155 'xvp_password_sep': '@', // Separator for XVP password fields
156 'disconnectTimeout': 3, // Time (s) to wait for disconnection
157 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
158 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
159 'viewportDrag': false, // Move the viewport on mouse drags
160
161 // Callback functions
162 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
163 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
164 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
165 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
166 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
167 'onBell': function () { }, // onBell(rfb): RFB Bell message received
168 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
169 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
170 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
171 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
172 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
173 });
174
175 // main setup
176 Util.Debug(">> RFB.constructor");
177
178 // populate encHandlers with bound versions
179 Object.keys(RFB.encodingHandlers).forEach(function (encName) {
180 this._encHandlers[encName] = RFB.encodingHandlers[encName].bind(this);
181 }.bind(this));
182
183 // Create lookup tables based on encoding number
184 for (var i = 0; i < this._encodings.length; i++) {
185 this._encHandlers[this._encodings[i][1]] = this._encHandlers[this._encodings[i][0]];
186 this._encNames[this._encodings[i][1]] = this._encodings[i][0];
187 this._encStats[this._encodings[i][1]] = [0, 0];
188 }
189
190 // NB: nothing that needs explicit teardown should be done
191 // before this point, since this can throw an exception
192 try {
193 this._display = new Display({target: this._target,
194 onFlush: this._onFlush.bind(this)});
195 } catch (exc) {
196 Util.Error("Display exception: " + exc);
197 throw exc;
198 }
199
200 this._keyboard = new Keyboard({target: this._focusContainer,
201 onKeyPress: this._handleKeyPress.bind(this)});
202
203 this._mouse = new Mouse({target: this._target,
204 onMouseButton: this._handleMouseButton.bind(this),
205 onMouseMove: this._handleMouseMove.bind(this),
206 notify: this._keyboard.sync.bind(this._keyboard)});
207
208 this._sock = new Websock();
209 this._sock.on('message', this._handle_message.bind(this));
210 this._sock.on('open', function () {
211 if ((this._rfb_connection_state === 'connecting') &&
212 (this._rfb_init_state === '')) {
213 this._rfb_init_state = 'ProtocolVersion';
214 Util.Debug("Starting VNC handshake");
215 } else {
216 this._fail("Got unexpected WebSocket connection");
217 }
218 }.bind(this));
219 this._sock.on('close', function (e) {
220 Util.Warn("WebSocket on-close event");
221 var msg = "";
222 if (e.code) {
223 msg = " (code: " + e.code;
224 if (e.reason) {
225 msg += ", reason: " + e.reason;
226 }
227 msg += ")";
228 }
229 switch (this._rfb_connection_state) {
230 case 'disconnecting':
231 this._updateConnectionState('disconnected');
232 break;
233 case 'connecting':
234 this._fail('Failed to connect to server' + msg);
235 break;
236 case 'connected':
237 // Handle disconnects that were initiated server-side
238 this._updateConnectionState('disconnecting');
239 this._updateConnectionState('disconnected');
240 break;
241 case 'disconnected':
242 Util.Error("Received onclose while disconnected" + msg);
243 break;
244 default:
245 this._fail("Unexpected server disconnect" + msg);
246 break;
247 }
248 this._sock.off('close');
249 }.bind(this));
250 this._sock.on('error', function (e) {
251 Util.Warn("WebSocket on-error event");
252 });
253
254 this._init_vars();
255 this._cleanup();
256
257 var rmode = this._display.get_render_mode();
258 Util.Info("Using native WebSockets, render mode: " + rmode);
259
260 Util.Debug("<< RFB.constructor");
261 };
262
263 (function() {
264 RFB.prototype = {
265 // Public methods
266 connect: function (host, port, password, path) {
267 this._rfb_host = host;
268 this._rfb_port = port;
269 this._rfb_password = (password !== undefined) ? password : "";
270 this._rfb_path = (path !== undefined) ? path : "";
271
272 if (!this._rfb_host || !this._rfb_port) {
273 return this._fail(
274 Util.Localisation.get("Must set host and port"));
275 }
276
277 this._rfb_init_state = '';
278 this._updateConnectionState('connecting');
279 return true;
280 },
281
282 disconnect: function () {
283 this._updateConnectionState('disconnecting');
284 this._sock.off('error');
285 this._sock.off('message');
286 this._sock.off('open');
287 },
288
289 sendPassword: function (passwd) {
290 this._rfb_password = passwd;
291 setTimeout(this._init_msg.bind(this), 0);
292 },
293
294 sendCtrlAltDel: function () {
295 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
296 Util.Info("Sending Ctrl-Alt-Del");
297
298 RFB.messages.keyEvent(this._sock, KeyTable.XK_Control_L, 1);
299 RFB.messages.keyEvent(this._sock, KeyTable.XK_Alt_L, 1);
300 RFB.messages.keyEvent(this._sock, KeyTable.XK_Delete, 1);
301 RFB.messages.keyEvent(this._sock, KeyTable.XK_Delete, 0);
302 RFB.messages.keyEvent(this._sock, KeyTable.XK_Alt_L, 0);
303 RFB.messages.keyEvent(this._sock, KeyTable.XK_Control_L, 0);
304 return true;
305 },
306
307 xvpOp: function (ver, op) {
308 if (this._rfb_xvp_ver < ver) { return false; }
309 Util.Info("Sending XVP operation " + op + " (version " + ver + ")");
310 this._sock.send_string("\xFA\x00" + String.fromCharCode(ver) + String.fromCharCode(op));
311 return true;
312 },
313
314 xvpShutdown: function () {
315 return this.xvpOp(1, 2);
316 },
317
318 xvpReboot: function () {
319 return this.xvpOp(1, 3);
320 },
321
322 xvpReset: function () {
323 return this.xvpOp(1, 4);
324 },
325
326 // Send a key press. If 'down' is not specified then send a down key
327 // followed by an up key.
328 sendKey: function (keysym, down) {
329 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
330 if (typeof down !== 'undefined') {
331 Util.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym);
332 RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0);
333 } else {
334 Util.Info("Sending keysym (down + up): " + keysym);
335 RFB.messages.keyEvent(this._sock, keysym, 1);
336 RFB.messages.keyEvent(this._sock, keysym, 0);
337 }
338 return true;
339 },
340
341 clipboardPasteFrom: function (text) {
342 if (this._rfb_connection_state !== 'connected') { return; }
343 RFB.messages.clientCutText(this._sock, text);
344 },
345
346 // Requests a change of remote desktop size. This message is an extension
347 // and may only be sent if we have received an ExtendedDesktopSize message
348 requestDesktopSize: function (width, height) {
349 if (this._rfb_connection_state !== 'connected' ||
350 this._view_only) {
351 return false;
352 }
353
354 if (this._supportsSetDesktopSize) {
355 RFB.messages.setDesktopSize(this._sock, width, height,
356 this._screen_id, this._screen_flags);
357 this._sock.flush();
358 return true;
359 } else {
360 return false;
361 }
362 },
363
364
365 // Private methods
366
367 _connect: function () {
368 Util.Debug(">> RFB.connect");
369 this._init_vars();
370
371 var uri;
372 if (typeof UsingSocketIO !== 'undefined') {
373 uri = 'http';
374 } else {
375 uri = this._encrypt ? 'wss' : 'ws';
376 }
377
378 uri += '://' + this._rfb_host + ':' + this._rfb_port + '/' + this._rfb_path;
379 Util.Info("connecting to " + uri);
380
381 try {
382 // WebSocket.onopen transitions to the RFB init states
383 this._sock.open(uri, this._wsProtocols);
384 } catch (e) {
385 if (e.name === 'SyntaxError') {
386 this._fail("Invalid host or port value given");
387 } else {
388 this._fail("Error while opening websocket (" + e + ")");
389 }
390 }
391
392 Util.Debug("<< RFB.connect");
393 },
394
395 _disconnect: function () {
396 Util.Debug(">> RFB.disconnect");
397 this._cleanup();
398 this._sock.close();
399 this._print_stats();
400 Util.Debug("<< RFB.disconnect");
401 },
402
403 _init_vars: function () {
404 // reset state
405 this._FBU.rects = 0;
406 this._FBU.subrects = 0; // RRE and HEXTILE
407 this._FBU.lines = 0; // RAW
408 this._FBU.tiles = 0; // HEXTILE
409 this._FBU.zlibs = []; // TIGHT zlib encoders
410 this._mouse_buttonMask = 0;
411 this._mouse_arr = [];
412 this._rfb_tightvnc = false;
413
414 // Clear the per connection encoding stats
415 var i;
416 for (i = 0; i < this._encodings.length; i++) {
417 this._encStats[this._encodings[i][1]][0] = 0;
418 }
419
420 for (i = 0; i < 4; i++) {
421 this._FBU.zlibs[i] = new Inflator.Inflate();
422 }
423 },
424
425 _print_stats: function () {
426 Util.Info("Encoding stats for this connection:");
427 var i, s;
428 for (i = 0; i < this._encodings.length; i++) {
429 s = this._encStats[this._encodings[i][1]];
430 if (s[0] + s[1] > 0) {
431 Util.Info(" " + this._encodings[i][0] + ": " + s[0] + " rects");
432 }
433 }
434
435 Util.Info("Encoding stats since page load:");
436 for (i = 0; i < this._encodings.length; i++) {
437 s = this._encStats[this._encodings[i][1]];
438 Util.Info(" " + this._encodings[i][0] + ": " + s[1] + " rects");
439 }
440 },
441
442 _cleanup: function () {
443 if (this._display && this._display.get_context()) {
444 if (!this._view_only) { this._keyboard.ungrab(); }
445 if (!this._view_only) { this._mouse.ungrab(); }
446 this._display.defaultCursor();
447 if (Util.get_logging() !== 'debug') {
448 // Show noVNC logo on load and when disconnected, unless in
449 // debug mode
450 this._display.clear();
451 }
452 }
453 },
454
455 /*
456 * Connection states:
457 * connecting
458 * connected
459 * disconnecting
460 * disconnected - permanent state
461 */
462 _updateConnectionState: function (state) {
463 var oldstate = this._rfb_connection_state;
464
465 if (state === oldstate) {
466 Util.Debug("Already in state '" + state + "', ignoring");
467 return;
468 }
469
470 // The 'disconnected' state is permanent for each RFB object
471 if (oldstate === 'disconnected') {
472 Util.Error("Tried changing state of a disconnected RFB object");
473 return;
474 }
475
476 this._rfb_connection_state = state;
477
478 var smsg = "New state '" + state + "', was '" + oldstate + "'.";
479 Util.Debug(smsg);
480
481 if (this._disconnTimer && state !== 'disconnecting') {
482 Util.Debug("Clearing disconnect timer");
483 clearTimeout(this._disconnTimer);
484 this._disconnTimer = null;
485 this._sock.off('close'); // make sure we don't get a double event
486 }
487
488 this._onUpdateState(this, state, oldstate);
489 switch (state) {
490 case 'connected':
491 if (oldstate !== 'connecting') {
492 Util.Error("Bad transition to connected state, " +
493 "previous connection state: " + oldstate);
494 return;
495 }
496 break;
497
498 case 'disconnected':
499 if (oldstate !== 'disconnecting') {
500 Util.Error("Bad transition to disconnected state, " +
501 "previous connection state: " + oldstate);
502 return;
503 }
504
505 if (this._rfb_disconnect_reason !== "") {
506 this._onDisconnected(this, this._rfb_disconnect_reason);
507 } else {
508 // No reason means clean disconnect
509 this._onDisconnected(this);
510 }
511 break;
512
513 case 'connecting':
514 this._connect();
515 break;
516
517 case 'disconnecting':
518 this._disconnect();
519
520 this._disconnTimer = setTimeout(function () {
521 this._rfb_disconnect_reason = "Disconnect timeout";
522 this._updateConnectionState('disconnected');
523 }.bind(this), this._disconnectTimeout * 1000);
524 break;
525
526 default:
527 Util.Error("Unknown connection state: " + state);
528 return;
529 }
530 },
531
532 _fail: function (msg) {
533 switch (this._rfb_connection_state) {
534 case 'disconnecting':
535 Util.Error("Error while disconnecting: " + msg);
536 break;
537 case 'connected':
538 Util.Error("Error while connected: " + msg);
539 break;
540 case 'connecting':
541 Util.Error("Error while connecting: " + msg);
542 break;
543 default:
544 Util.Error("RFB error: " + msg);
545 break;
546 }
547 this._rfb_disconnect_reason = msg;
548 this._updateConnectionState('disconnecting');
549 return false;
550 },
551
552 /*
553 * Send a notification to the UI. Valid levels are:
554 * 'normal'|'warn'|'error'
555 *
556 * NOTE: Options could be added in the future.
557 * NOTE: If this function is called multiple times, remember that the
558 * interface could be only showing the latest notification.
559 */
560 _notification: function(msg, level, options) {
561 switch (level) {
562 case 'normal':
563 case 'warn':
564 case 'error':
565 Util.Debug("Notification[" + level + "]:" + msg);
566 break;
567 default:
568 Util.Error("Invalid notification level: " + level);
569 return;
570 }
571
572 if (options) {
573 this._onNotification(this, msg, level, options);
574 } else {
575 this._onNotification(this, msg, level);
576 }
577 },
578
579 _handle_message: function () {
580 if (this._sock.rQlen() === 0) {
581 Util.Warn("handle_message called on an empty receive queue");
582 return;
583 }
584
585 switch (this._rfb_connection_state) {
586 case 'disconnected':
587 Util.Error("Got data while disconnected");
588 break;
589 case 'connected':
590 while (true) {
591 if (this._flushing) {
592 break;
593 }
594 if (!this._normal_msg()) {
595 break;
596 }
597 if (this._sock.rQlen() === 0) {
598 break;
599 }
600 }
601 break;
602 default:
603 this._init_msg();
604 break;
605 }
606 },
607
608 _handleKeyPress: function (keyevent) {
609 if (this._view_only) { return; } // View only, skip keyboard, events
610
611 var down = (keyevent.type == 'keydown');
612 if (this._qemuExtKeyEventSupported) {
613 var scancode = XtScancode[keyevent.code];
614 if (scancode) {
615 var keysym = keyevent.keysym;
616 RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode);
617 } else {
618 Util.Error('Unable to find a xt scancode for code = ' + keyevent.code);
619 }
620 } else {
621 keysym = keyevent.keysym.keysym;
622 RFB.messages.keyEvent(this._sock, keysym, down);
623 }
624 },
625
626 _handleMouseButton: function (x, y, down, bmask) {
627 if (down) {
628 this._mouse_buttonMask |= bmask;
629 } else {
630 this._mouse_buttonMask ^= bmask;
631 }
632
633 if (this._viewportDrag) {
634 if (down && !this._viewportDragging) {
635 this._viewportDragging = true;
636 this._viewportDragPos = {'x': x, 'y': y};
637
638 // Skip sending mouse events
639 return;
640 } else {
641 this._viewportDragging = false;
642
643 // If the viewport didn't actually move, then treat as a mouse click event
644 // Send the button down event here, as the button up event is sent at the end of this function
645 if (!this._viewportHasMoved && !this._view_only) {
646 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), bmask);
647 }
648 this._viewportHasMoved = false;
649 }
650 }
651
652 if (this._view_only) { return; } // View only, skip mouse events
653
654 if (this._rfb_connection_state !== 'connected') { return; }
655 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
656 },
657
658 _handleMouseMove: function (x, y) {
659 if (this._viewportDragging) {
660 var deltaX = this._viewportDragPos.x - x;
661 var deltaY = this._viewportDragPos.y - y;
662
663 // The goal is to trigger on a certain physical width, the
664 // devicePixelRatio brings us a bit closer but is not optimal.
665 var dragThreshold = 10 * (window.devicePixelRatio || 1);
666
667 if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
668 Math.abs(deltaY) > dragThreshold)) {
669 this._viewportHasMoved = true;
670
671 this._viewportDragPos = {'x': x, 'y': y};
672 this._display.viewportChangePos(deltaX, deltaY);
673 }
674
675 // Skip sending mouse events
676 return;
677 }
678
679 if (this._view_only) { return; } // View only, skip mouse events
680
681 if (this._rfb_connection_state !== 'connected') { return; }
682 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
683 },
684
685 // Message Handlers
686
687 _negotiate_protocol_version: function () {
688 if (this._sock.rQlen() < 12) {
689 return this._fail("Incomplete protocol version");
690 }
691
692 var sversion = this._sock.rQshiftStr(12).substr(4, 7);
693 Util.Info("Server ProtocolVersion: " + sversion);
694 var is_repeater = 0;
695 switch (sversion) {
696 case "000.000": // UltraVNC repeater
697 is_repeater = 1;
698 break;
699 case "003.003":
700 case "003.006": // UltraVNC
701 case "003.889": // Apple Remote Desktop
702 this._rfb_version = 3.3;
703 break;
704 case "003.007":
705 this._rfb_version = 3.7;
706 break;
707 case "003.008":
708 case "004.000": // Intel AMT KVM
709 case "004.001": // RealVNC 4.6
710 case "005.000": // RealVNC 5.3
711 this._rfb_version = 3.8;
712 break;
713 default:
714 return this._fail("Invalid server version " + sversion);
715 }
716
717 if (is_repeater) {
718 var repeaterID = this._repeaterID;
719 while (repeaterID.length < 250) {
720 repeaterID += "\0";
721 }
722 this._sock.send_string(repeaterID);
723 return true;
724 }
725
726 if (this._rfb_version > this._rfb_max_version) {
727 this._rfb_version = this._rfb_max_version;
728 }
729
730 var cversion = "00" + parseInt(this._rfb_version, 10) +
731 ".00" + ((this._rfb_version * 10) % 10);
732 this._sock.send_string("RFB " + cversion + "\n");
733 Util.Debug('Sent ProtocolVersion: ' + cversion);
734
735 this._rfb_init_state = 'Security';
736 },
737
738 _negotiate_security: function () {
739 if (this._rfb_version >= 3.7) {
740 // Server sends supported list, client decides
741 var num_types = this._sock.rQshift8();
742 if (this._sock.rQwait("security type", num_types, 1)) { return false; }
743
744 if (num_types === 0) {
745 var strlen = this._sock.rQshift32();
746 var reason = this._sock.rQshiftStr(strlen);
747 return this._fail("Security failure: " + reason);
748 }
749
750 this._rfb_auth_scheme = 0;
751 var types = this._sock.rQshiftBytes(num_types);
752 Util.Debug("Server security types: " + types);
753 for (var i = 0; i < types.length; i++) {
754 switch (types[i]) {
755 case 1: // None
756 case 2: // VNC Authentication
757 case 16: // Tight
758 case 22: // XVP
759 if (types[i] > this._rfb_auth_scheme) {
760 this._rfb_auth_scheme = types[i];
761 }
762 break;
763 default:
764 break;
765 }
766 }
767
768 if (this._rfb_auth_scheme === 0) {
769 return this._fail("Unsupported security types: " + types);
770 }
771
772 this._sock.send([this._rfb_auth_scheme]);
773 } else {
774 // Server decides
775 if (this._sock.rQwait("security scheme", 4)) { return false; }
776 this._rfb_auth_scheme = this._sock.rQshift32();
777 }
778
779 this._rfb_init_state = 'Authentication';
780 Util.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme);
781
782 return this._init_msg(); // jump to authentication
783 },
784
785 // authentication
786 _negotiate_xvp_auth: function () {
787 var xvp_sep = this._xvp_password_sep;
788 var xvp_auth = this._rfb_password.split(xvp_sep);
789 if (xvp_auth.length < 3) {
790 var msg = 'XVP credentials required (user' + xvp_sep +
791 'target' + xvp_sep + 'password) -- got only ' + this._rfb_password;
792 this._onPasswordRequired(this, msg);
793 return false;
794 }
795
796 var xvp_auth_str = String.fromCharCode(xvp_auth[0].length) +
797 String.fromCharCode(xvp_auth[1].length) +
798 xvp_auth[0] +
799 xvp_auth[1];
800 this._sock.send_string(xvp_auth_str);
801 this._rfb_password = xvp_auth.slice(2).join(xvp_sep);
802 this._rfb_auth_scheme = 2;
803 return this._negotiate_authentication();
804 },
805
806 _negotiate_std_vnc_auth: function () {
807 if (this._rfb_password.length === 0) {
808 this._onPasswordRequired(this);
809 return false;
810 }
811
812 if (this._sock.rQwait("auth challenge", 16)) { return false; }
813
814 // TODO(directxman12): make genDES not require an Array
815 var challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
816 var response = RFB.genDES(this._rfb_password, challenge);
817 this._sock.send(response);
818 this._rfb_init_state = "SecurityResult";
819 return true;
820 },
821
822 _negotiate_tight_tunnels: function (numTunnels) {
823 var clientSupportedTunnelTypes = {
824 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
825 };
826 var serverSupportedTunnelTypes = {};
827 // receive tunnel capabilities
828 for (var i = 0; i < numTunnels; i++) {
829 var cap_code = this._sock.rQshift32();
830 var cap_vendor = this._sock.rQshiftStr(4);
831 var cap_signature = this._sock.rQshiftStr(8);
832 serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature };
833 }
834
835 // choose the notunnel type
836 if (serverSupportedTunnelTypes[0]) {
837 if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
838 serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
839 return this._fail("Client's tunnel type had the incorrect vendor or signature");
840 }
841 this._sock.send([0, 0, 0, 0]); // use NOTUNNEL
842 return false; // wait until we receive the sub auth count to continue
843 } else {
844 return this._fail("Server wanted tunnels, but doesn't support the notunnel type");
845 }
846 },
847
848 _negotiate_tight_auth: function () {
849 if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation
850 if (this._sock.rQwait("num tunnels", 4)) { return false; }
851 var numTunnels = this._sock.rQshift32();
852 if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
853
854 this._rfb_tightvnc = true;
855
856 if (numTunnels > 0) {
857 this._negotiate_tight_tunnels(numTunnels);
858 return false; // wait until we receive the sub auth to continue
859 }
860 }
861
862 // second pass, do the sub-auth negotiation
863 if (this._sock.rQwait("sub auth count", 4)) { return false; }
864 var subAuthCount = this._sock.rQshift32();
865 if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
866 this._updateState('SecurityResult');
867 return true;
868 }
869
870 if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
871
872 var clientSupportedTypes = {
873 'STDVNOAUTH__': 1,
874 'STDVVNCAUTH_': 2
875 };
876
877 var serverSupportedTypes = [];
878
879 for (var i = 0; i < subAuthCount; i++) {
880 var capNum = this._sock.rQshift32();
881 var capabilities = this._sock.rQshiftStr(12);
882 serverSupportedTypes.push(capabilities);
883 }
884
885 for (var authType in clientSupportedTypes) {
886 if (serverSupportedTypes.indexOf(authType) != -1) {
887 this._sock.send([0, 0, 0, clientSupportedTypes[authType]]);
888
889 switch (authType) {
890 case 'STDVNOAUTH__': // no auth
891 this._rfb_init_state = 'SecurityResult';
892 return true;
893 case 'STDVVNCAUTH_': // VNC auth
894 this._rfb_auth_scheme = 2;
895 return this._init_msg();
896 default:
897 return this._fail("Unsupported tiny auth scheme: " + authType);
898 }
899 }
900 }
901
902 return this._fail("No supported sub-auth types!");
903 },
904
905 _negotiate_authentication: function () {
906 switch (this._rfb_auth_scheme) {
907 case 0: // connection failed
908 if (this._sock.rQwait("auth reason", 4)) { return false; }
909 var strlen = this._sock.rQshift32();
910 var reason = this._sock.rQshiftStr(strlen);
911 return this._fail("Auth failure: " + reason);
912
913 case 1: // no auth
914 if (this._rfb_version >= 3.8) {
915 this._rfb_init_state = 'SecurityResult';
916 return true;
917 }
918 this._rfb_init_state = 'ClientInitialisation';
919 return this._init_msg();
920
921 case 22: // XVP auth
922 return this._negotiate_xvp_auth();
923
924 case 2: // VNC authentication
925 return this._negotiate_std_vnc_auth();
926
927 case 16: // TightVNC Security Type
928 return this._negotiate_tight_auth();
929
930 default:
931 return this._fail("Unsupported auth scheme: " + this._rfb_auth_scheme);
932 }
933 },
934
935 _handle_security_result: function () {
936 if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
937 switch (this._sock.rQshift32()) {
938 case 0: // OK
939 this._rfb_init_state = 'ClientInitialisation';
940 Util.Debug('Authentication OK');
941 return this._init_msg();
942 case 1: // failed
943 if (this._rfb_version >= 3.8) {
944 var length = this._sock.rQshift32();
945 if (this._sock.rQwait("SecurityResult reason", length, 8)) { return false; }
946 var reason = this._sock.rQshiftStr(length);
947 return this._fail(reason);
948 } else {
949 return this._fail("Authentication failure");
950 }
951 return false;
952 case 2:
953 return this._fail("Too many auth attempts");
954 default:
955 return this._fail("Unknown SecurityResult");
956 }
957 },
958
959 _negotiate_server_init: function () {
960 if (this._sock.rQwait("server initialization", 24)) { return false; }
961
962 /* Screen size */
963 this._fb_width = this._sock.rQshift16();
964 this._fb_height = this._sock.rQshift16();
965 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
966
967 /* PIXEL_FORMAT */
968 var bpp = this._sock.rQshift8();
969 var depth = this._sock.rQshift8();
970 var big_endian = this._sock.rQshift8();
971 var true_color = this._sock.rQshift8();
972
973 var red_max = this._sock.rQshift16();
974 var green_max = this._sock.rQshift16();
975 var blue_max = this._sock.rQshift16();
976 var red_shift = this._sock.rQshift8();
977 var green_shift = this._sock.rQshift8();
978 var blue_shift = this._sock.rQshift8();
979 this._sock.rQskipBytes(3); // padding
980
981 // NB(directxman12): we don't want to call any callbacks or print messages until
982 // *after* we're past the point where we could backtrack
983
984 /* Connection name/title */
985 var name_length = this._sock.rQshift32();
986 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
987 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
988
989 if (this._rfb_tightvnc) {
990 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
991 // In TightVNC mode, ServerInit message is extended
992 var numServerMessages = this._sock.rQshift16();
993 var numClientMessages = this._sock.rQshift16();
994 var numEncodings = this._sock.rQshift16();
995 this._sock.rQskipBytes(2); // padding
996
997 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
998 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
999
1000 // we don't actually do anything with the capability information that TIGHT sends,
1001 // so we just skip the all of this.
1002
1003 // TIGHT server message capabilities
1004 this._sock.rQskipBytes(16 * numServerMessages);
1005
1006 // TIGHT client message capabilities
1007 this._sock.rQskipBytes(16 * numClientMessages);
1008
1009 // TIGHT encoding capabilities
1010 this._sock.rQskipBytes(16 * numEncodings);
1011 }
1012
1013 // NB(directxman12): these are down here so that we don't run them multiple times
1014 // if we backtrack
1015 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1016 ", bpp: " + bpp + ", depth: " + depth +
1017 ", big_endian: " + big_endian +
1018 ", true_color: " + true_color +
1019 ", red_max: " + red_max +
1020 ", green_max: " + green_max +
1021 ", blue_max: " + blue_max +
1022 ", red_shift: " + red_shift +
1023 ", green_shift: " + green_shift +
1024 ", blue_shift: " + blue_shift);
1025
1026 if (big_endian !== 0) {
1027 Util.Warn("Server native endian is not little endian");
1028 }
1029
1030 if (red_shift !== 16) {
1031 Util.Warn("Server native red-shift is not 16");
1032 }
1033
1034 if (blue_shift !== 0) {
1035 Util.Warn("Server native blue-shift is not 0");
1036 }
1037
1038 // we're past the point where we could backtrack, so it's safe to call this
1039 this._onDesktopName(this, this._fb_name);
1040
1041 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1042 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1043 this._true_color = false;
1044 }
1045
1046 this._display.set_true_color(this._true_color);
1047 this._display.resize(this._fb_width, this._fb_height);
1048 this._onFBResize(this, this._fb_width, this._fb_height);
1049
1050 if (!this._view_only) { this._keyboard.grab(); }
1051 if (!this._view_only) { this._mouse.grab(); }
1052
1053 if (this._true_color) {
1054 this._fb_Bpp = 4;
1055 this._fb_depth = 3;
1056 } else {
1057 this._fb_Bpp = 1;
1058 this._fb_depth = 1;
1059 }
1060
1061 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1062 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1063 RFB.messages.fbUpdateRequests(this._sock, false, this._display.getCleanDirtyReset(), this._fb_width, this._fb_height);
1064
1065 this._timing.fbu_rt_start = (new Date()).getTime();
1066 this._timing.pixels = 0;
1067
1068 this._updateConnectionState('connected');
1069 return true;
1070 },
1071
1072 /* RFB protocol initialization states:
1073 * ProtocolVersion
1074 * Security
1075 * Authentication
1076 * SecurityResult
1077 * ClientInitialization - not triggered by server message
1078 * ServerInitialization
1079 */
1080 _init_msg: function () {
1081 switch (this._rfb_init_state) {
1082 case 'ProtocolVersion':
1083 return this._negotiate_protocol_version();
1084
1085 case 'Security':
1086 return this._negotiate_security();
1087
1088 case 'Authentication':
1089 return this._negotiate_authentication();
1090
1091 case 'SecurityResult':
1092 return this._handle_security_result();
1093
1094 case 'ClientInitialisation':
1095 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1096 this._rfb_init_state = 'ServerInitialisation';
1097 return true;
1098
1099 case 'ServerInitialisation':
1100 return this._negotiate_server_init();
1101
1102 default:
1103 return this._fail("Unknown init state: " +
1104 this._rfb_init_state);
1105 }
1106 },
1107
1108 _handle_set_colour_map_msg: function () {
1109 Util.Debug("SetColorMapEntries");
1110 this._sock.rQskip8(); // Padding
1111
1112 var first_colour = this._sock.rQshift16();
1113 var num_colours = this._sock.rQshift16();
1114 if (this._sock.rQwait('SetColorMapEntries', num_colours * 6, 6)) { return false; }
1115
1116 for (var c = 0; c < num_colours; c++) {
1117 var red = parseInt(this._sock.rQshift16() / 256, 10);
1118 var green = parseInt(this._sock.rQshift16() / 256, 10);
1119 var blue = parseInt(this._sock.rQshift16() / 256, 10);
1120 this._display.set_colourMap([blue, green, red], first_colour + c);
1121 }
1122 Util.Debug("colourMap: " + this._display.get_colourMap());
1123 Util.Info("Registered " + num_colours + " colourMap entries");
1124
1125 return true;
1126 },
1127
1128 _handle_server_cut_text: function () {
1129 Util.Debug("ServerCutText");
1130 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1131 this._sock.rQskipBytes(3); // Padding
1132 var length = this._sock.rQshift32();
1133 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
1134
1135 var text = this._sock.rQshiftStr(length);
1136 this._onClipboard(this, text);
1137
1138 return true;
1139 },
1140
1141 _handle_server_fence_msg: function() {
1142 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1143 this._sock.rQskipBytes(3); // Padding
1144 var flags = this._sock.rQshift32();
1145 var length = this._sock.rQshift8();
1146
1147 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
1148
1149 if (length > 64) {
1150 Util.Warn("Bad payload length (" + length + ") in fence response");
1151 length = 64;
1152 }
1153
1154 var payload = this._sock.rQshiftStr(length);
1155
1156 this._supportsFence = true;
1157
1158 /*
1159 * Fence flags
1160 *
1161 * (1<<0) - BlockBefore
1162 * (1<<1) - BlockAfter
1163 * (1<<2) - SyncNext
1164 * (1<<31) - Request
1165 */
1166
1167 if (!(flags & (1<<31))) {
1168 return this._fail("Unexpected fence response");
1169 }
1170
1171 // Filter out unsupported flags
1172 // FIXME: support syncNext
1173 flags &= (1<<0) | (1<<1);
1174
1175 // BlockBefore and BlockAfter are automatically handled by
1176 // the fact that we process each incoming message
1177 // synchronuosly.
1178 RFB.messages.clientFence(this._sock, flags, payload);
1179
1180 return true;
1181 },
1182
1183 _handle_xvp_msg: function () {
1184 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
1185 this._sock.rQskip8(); // Padding
1186 var xvp_ver = this._sock.rQshift8();
1187 var xvp_msg = this._sock.rQshift8();
1188
1189 switch (xvp_msg) {
1190 case 0: // XVP_FAIL
1191 Util.Error("Operation Failed");
1192 this._notification("XVP Operation Failed", 'error');
1193 break;
1194 case 1: // XVP_INIT
1195 this._rfb_xvp_ver = xvp_ver;
1196 Util.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
1197 this._onXvpInit(this._rfb_xvp_ver);
1198 break;
1199 default:
1200 this._fail("Disconnected: illegal server XVP message " + xvp_msg);
1201 break;
1202 }
1203
1204 return true;
1205 },
1206
1207 _normal_msg: function () {
1208 var msg_type;
1209
1210 if (this._FBU.rects > 0) {
1211 msg_type = 0;
1212 } else {
1213 msg_type = this._sock.rQshift8();
1214 }
1215
1216 switch (msg_type) {
1217 case 0: // FramebufferUpdate
1218 var ret = this._framebufferUpdate();
1219 if (ret) {
1220 RFB.messages.fbUpdateRequests(this._sock,
1221 this._enabledContinuousUpdates,
1222 this._display.getCleanDirtyReset(),
1223 this._fb_width, this._fb_height);
1224 }
1225 return ret;
1226
1227 case 1: // SetColorMapEntries
1228 return this._handle_set_colour_map_msg();
1229
1230 case 2: // Bell
1231 Util.Debug("Bell");
1232 this._onBell(this);
1233 return true;
1234
1235 case 3: // ServerCutText
1236 return this._handle_server_cut_text();
1237
1238 case 150: // EndOfContinuousUpdates
1239 var first = !(this._supportsContinuousUpdates);
1240 this._supportsContinuousUpdates = true;
1241 this._enabledContinuousUpdates = false;
1242 if (first) {
1243 this._enabledContinuousUpdates = true;
1244 this._updateContinuousUpdates();
1245 Util.Info("Enabling continuous updates.");
1246 } else {
1247 // FIXME: We need to send a framebufferupdaterequest here
1248 // if we add support for turning off continuous updates
1249 }
1250 return true;
1251
1252 case 248: // ServerFence
1253 return this._handle_server_fence_msg();
1254
1255 case 250: // XVP
1256 return this._handle_xvp_msg();
1257
1258 default:
1259 this._fail("Disconnected: illegal server message type " + msg_type);
1260 Util.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1261 return true;
1262 }
1263 },
1264
1265 _onFlush: function() {
1266 this._flushing = false;
1267 // Resume processing
1268 if (this._sock.rQlen() > 0) {
1269 this._handle_message();
1270 }
1271 },
1272
1273 _framebufferUpdate: function () {
1274 var ret = true;
1275 var now;
1276
1277 if (this._FBU.rects === 0) {
1278 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
1279 this._sock.rQskip8(); // Padding
1280 this._FBU.rects = this._sock.rQshift16();
1281 this._FBU.bytes = 0;
1282 this._timing.cur_fbu = 0;
1283 if (this._timing.fbu_rt_start > 0) {
1284 now = (new Date()).getTime();
1285 Util.Info("First FBU latency: " + (now - this._timing.fbu_rt_start));
1286 }
1287
1288 // Make sure the previous frame is fully rendered first
1289 // to avoid building up an excessive queue
1290 if (this._display.pending()) {
1291 this._flushing = true;
1292 this._display.flush();
1293 return false;
1294 }
1295 }
1296
1297 while (this._FBU.rects > 0) {
1298 if (this._rfb_connection_state !== 'connected') { return false; }
1299
1300 if (this._sock.rQwait("FBU", this._FBU.bytes)) { return false; }
1301 if (this._FBU.bytes === 0) {
1302 if (this._sock.rQwait("rect header", 12)) { return false; }
1303 /* New FramebufferUpdate */
1304
1305 var hdr = this._sock.rQshiftBytes(12);
1306 this._FBU.x = (hdr[0] << 8) + hdr[1];
1307 this._FBU.y = (hdr[2] << 8) + hdr[3];
1308 this._FBU.width = (hdr[4] << 8) + hdr[5];
1309 this._FBU.height = (hdr[6] << 8) + hdr[7];
1310 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1311 (hdr[10] << 8) + hdr[11], 10);
1312
1313 this._onFBUReceive(this,
1314 {'x': this._FBU.x, 'y': this._FBU.y,
1315 'width': this._FBU.width, 'height': this._FBU.height,
1316 'encoding': this._FBU.encoding,
1317 'encodingName': this._encNames[this._FBU.encoding]});
1318
1319 if (!this._encNames[this._FBU.encoding]) {
1320 this._fail("Disconnected: unsupported encoding " +
1321 this._FBU.encoding);
1322 return false;
1323 }
1324 }
1325
1326 this._timing.last_fbu = (new Date()).getTime();
1327
1328 ret = this._encHandlers[this._FBU.encoding]();
1329
1330 now = (new Date()).getTime();
1331 this._timing.cur_fbu += (now - this._timing.last_fbu);
1332
1333 if (ret) {
1334 this._encStats[this._FBU.encoding][0]++;
1335 this._encStats[this._FBU.encoding][1]++;
1336 this._timing.pixels += this._FBU.width * this._FBU.height;
1337 }
1338
1339 if (this._timing.pixels >= (this._fb_width * this._fb_height)) {
1340 if ((this._FBU.width === this._fb_width && this._FBU.height === this._fb_height) ||
1341 this._timing.fbu_rt_start > 0) {
1342 this._timing.full_fbu_total += this._timing.cur_fbu;
1343 this._timing.full_fbu_cnt++;
1344 Util.Info("Timing of full FBU, curr: " +
1345 this._timing.cur_fbu + ", total: " +
1346 this._timing.full_fbu_total + ", cnt: " +
1347 this._timing.full_fbu_cnt + ", avg: " +
1348 (this._timing.full_fbu_total / this._timing.full_fbu_cnt));
1349 }
1350
1351 if (this._timing.fbu_rt_start > 0) {
1352 var fbu_rt_diff = now - this._timing.fbu_rt_start;
1353 this._timing.fbu_rt_total += fbu_rt_diff;
1354 this._timing.fbu_rt_cnt++;
1355 Util.Info("full FBU round-trip, cur: " +
1356 fbu_rt_diff + ", total: " +
1357 this._timing.fbu_rt_total + ", cnt: " +
1358 this._timing.fbu_rt_cnt + ", avg: " +
1359 (this._timing.fbu_rt_total / this._timing.fbu_rt_cnt));
1360 this._timing.fbu_rt_start = 0;
1361 }
1362 }
1363
1364 if (!ret) { return ret; } // need more data
1365 }
1366
1367 this._onFBUComplete(this,
1368 {'x': this._FBU.x, 'y': this._FBU.y,
1369 'width': this._FBU.width, 'height': this._FBU.height,
1370 'encoding': this._FBU.encoding,
1371 'encodingName': this._encNames[this._FBU.encoding]});
1372
1373 return true; // We finished this FBU
1374 },
1375
1376 _updateContinuousUpdates: function() {
1377 if (!this._enabledContinuousUpdates) { return; }
1378
1379 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1380 this._fb_width, this._fb_height);
1381 }
1382 };
1383
1384 Util.make_properties(RFB, [
1385 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1386 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1387 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1388 ['true_color', 'rw', 'bool'], // Request true color pixel data
1389 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1390 ['shared', 'rw', 'bool'], // Request shared mode
1391 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1392 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1393 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1394 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1395 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1396 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1397
1398 // Callback functions
1399 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1400 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1401 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1402 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1403 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1404 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1405 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1406 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1407 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1408 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1409 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1410 ]);
1411
1412 RFB.prototype.set_local_cursor = function (cursor) {
1413 if (!cursor || (cursor in {'0': 1, 'no': 1, 'false': 1})) {
1414 this._local_cursor = false;
1415 this._display.disableLocalCursor(); //Only show server-side cursor
1416 } else {
1417 if (this._display.get_cursor_uri()) {
1418 this._local_cursor = true;
1419 } else {
1420 Util.Warn("Browser does not support local cursor");
1421 this._display.disableLocalCursor();
1422 }
1423 }
1424 };
1425
1426 RFB.prototype.get_display = function () { return this._display; };
1427 RFB.prototype.get_keyboard = function () { return this._keyboard; };
1428 RFB.prototype.get_mouse = function () { return this._mouse; };
1429
1430 // Class Methods
1431 RFB.messages = {
1432 keyEvent: function (sock, keysym, down) {
1433 var buff = sock._sQ;
1434 var offset = sock._sQlen;
1435
1436 buff[offset] = 4; // msg-type
1437 buff[offset + 1] = down;
1438
1439 buff[offset + 2] = 0;
1440 buff[offset + 3] = 0;
1441
1442 buff[offset + 4] = (keysym >> 24);
1443 buff[offset + 5] = (keysym >> 16);
1444 buff[offset + 6] = (keysym >> 8);
1445 buff[offset + 7] = keysym;
1446
1447 sock._sQlen += 8;
1448 sock.flush();
1449 },
1450
1451 QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) {
1452 function getRFBkeycode(xt_scancode) {
1453 var upperByte = (keycode >> 8);
1454 var lowerByte = (keycode & 0x00ff);
1455 if (upperByte === 0xe0 && lowerByte < 0x7f) {
1456 lowerByte = lowerByte | 0x80;
1457 return lowerByte;
1458 }
1459 return xt_scancode;
1460 }
1461
1462 var buff = sock._sQ;
1463 var offset = sock._sQlen;
1464
1465 buff[offset] = 255; // msg-type
1466 buff[offset + 1] = 0; // sub msg-type
1467
1468 buff[offset + 2] = (down >> 8);
1469 buff[offset + 3] = down;
1470
1471 buff[offset + 4] = (keysym >> 24);
1472 buff[offset + 5] = (keysym >> 16);
1473 buff[offset + 6] = (keysym >> 8);
1474 buff[offset + 7] = keysym;
1475
1476 var RFBkeycode = getRFBkeycode(keycode);
1477
1478 buff[offset + 8] = (RFBkeycode >> 24);
1479 buff[offset + 9] = (RFBkeycode >> 16);
1480 buff[offset + 10] = (RFBkeycode >> 8);
1481 buff[offset + 11] = RFBkeycode;
1482
1483 sock._sQlen += 12;
1484 sock.flush();
1485 },
1486
1487 pointerEvent: function (sock, x, y, mask) {
1488 var buff = sock._sQ;
1489 var offset = sock._sQlen;
1490
1491 buff[offset] = 5; // msg-type
1492
1493 buff[offset + 1] = mask;
1494
1495 buff[offset + 2] = x >> 8;
1496 buff[offset + 3] = x;
1497
1498 buff[offset + 4] = y >> 8;
1499 buff[offset + 5] = y;
1500
1501 sock._sQlen += 6;
1502 sock.flush();
1503 },
1504
1505 // TODO(directxman12): make this unicode compatible?
1506 clientCutText: function (sock, text) {
1507 var buff = sock._sQ;
1508 var offset = sock._sQlen;
1509
1510 buff[offset] = 6; // msg-type
1511
1512 buff[offset + 1] = 0; // padding
1513 buff[offset + 2] = 0; // padding
1514 buff[offset + 3] = 0; // padding
1515
1516 var n = text.length;
1517
1518 buff[offset + 4] = n >> 24;
1519 buff[offset + 5] = n >> 16;
1520 buff[offset + 6] = n >> 8;
1521 buff[offset + 7] = n;
1522
1523 for (var i = 0; i < n; i++) {
1524 buff[offset + 8 + i] = text.charCodeAt(i);
1525 }
1526
1527 sock._sQlen += 8 + n;
1528 sock.flush();
1529 },
1530
1531 setDesktopSize: function (sock, width, height, id, flags) {
1532 var buff = sock._sQ;
1533 var offset = sock._sQlen;
1534
1535 buff[offset] = 251; // msg-type
1536 buff[offset + 1] = 0; // padding
1537 buff[offset + 2] = width >> 8; // width
1538 buff[offset + 3] = width;
1539 buff[offset + 4] = height >> 8; // height
1540 buff[offset + 5] = height;
1541
1542 buff[offset + 6] = 1; // number-of-screens
1543 buff[offset + 7] = 0; // padding
1544
1545 // screen array
1546 buff[offset + 8] = id >> 24; // id
1547 buff[offset + 9] = id >> 16;
1548 buff[offset + 10] = id >> 8;
1549 buff[offset + 11] = id;
1550 buff[offset + 12] = 0; // x-position
1551 buff[offset + 13] = 0;
1552 buff[offset + 14] = 0; // y-position
1553 buff[offset + 15] = 0;
1554 buff[offset + 16] = width >> 8; // width
1555 buff[offset + 17] = width;
1556 buff[offset + 18] = height >> 8; // height
1557 buff[offset + 19] = height;
1558 buff[offset + 20] = flags >> 24; // flags
1559 buff[offset + 21] = flags >> 16;
1560 buff[offset + 22] = flags >> 8;
1561 buff[offset + 23] = flags;
1562
1563 sock._sQlen += 24;
1564 sock.flush();
1565 },
1566
1567 clientFence: function (sock, flags, payload) {
1568 var buff = sock._sQ;
1569 var offset = sock._sQlen;
1570
1571 buff[offset] = 248; // msg-type
1572
1573 buff[offset + 1] = 0; // padding
1574 buff[offset + 2] = 0; // padding
1575 buff[offset + 3] = 0; // padding
1576
1577 buff[offset + 4] = flags >> 24; // flags
1578 buff[offset + 5] = flags >> 16;
1579 buff[offset + 6] = flags >> 8;
1580 buff[offset + 7] = flags;
1581
1582 var n = payload.length;
1583
1584 buff[offset + 8] = n; // length
1585
1586 for (var i = 0; i < n; i++) {
1587 buff[offset + 9 + i] = payload.charCodeAt(i);
1588 }
1589
1590 sock._sQlen += 9 + n;
1591 sock.flush();
1592 },
1593
1594 enableContinuousUpdates: function (sock, enable, x, y, width, height) {
1595 var buff = sock._sQ;
1596 var offset = sock._sQlen;
1597
1598 buff[offset] = 150; // msg-type
1599 buff[offset + 1] = enable; // enable-flag
1600
1601 buff[offset + 2] = x >> 8; // x
1602 buff[offset + 3] = x;
1603 buff[offset + 4] = y >> 8; // y
1604 buff[offset + 5] = y;
1605 buff[offset + 6] = width >> 8; // width
1606 buff[offset + 7] = width;
1607 buff[offset + 8] = height >> 8; // height
1608 buff[offset + 9] = height;
1609
1610 sock._sQlen += 10;
1611 sock.flush();
1612 },
1613
1614 pixelFormat: function (sock, bpp, depth, true_color) {
1615 var buff = sock._sQ;
1616 var offset = sock._sQlen;
1617
1618 buff[offset] = 0; // msg-type
1619
1620 buff[offset + 1] = 0; // padding
1621 buff[offset + 2] = 0; // padding
1622 buff[offset + 3] = 0; // padding
1623
1624 buff[offset + 4] = bpp * 8; // bits-per-pixel
1625 buff[offset + 5] = depth * 8; // depth
1626 buff[offset + 6] = 0; // little-endian
1627 buff[offset + 7] = true_color ? 1 : 0; // true-color
1628
1629 buff[offset + 8] = 0; // red-max
1630 buff[offset + 9] = 255; // red-max
1631
1632 buff[offset + 10] = 0; // green-max
1633 buff[offset + 11] = 255; // green-max
1634
1635 buff[offset + 12] = 0; // blue-max
1636 buff[offset + 13] = 255; // blue-max
1637
1638 buff[offset + 14] = 16; // red-shift
1639 buff[offset + 15] = 8; // green-shift
1640 buff[offset + 16] = 0; // blue-shift
1641
1642 buff[offset + 17] = 0; // padding
1643 buff[offset + 18] = 0; // padding
1644 buff[offset + 19] = 0; // padding
1645
1646 sock._sQlen += 20;
1647 sock.flush();
1648 },
1649
1650 clientEncodings: function (sock, encodings, local_cursor, true_color) {
1651 var buff = sock._sQ;
1652 var offset = sock._sQlen;
1653
1654 buff[offset] = 2; // msg-type
1655 buff[offset + 1] = 0; // padding
1656
1657 // offset + 2 and offset + 3 are encoding count
1658
1659 var i, j = offset + 4, cnt = 0;
1660 for (i = 0; i < encodings.length; i++) {
1661 if (encodings[i][0] === "Cursor" && !local_cursor) {
1662 Util.Debug("Skipping Cursor pseudo-encoding");
1663 } else if (encodings[i][0] === "TIGHT" && !true_color) {
1664 // TODO: remove this when we have tight+non-true-color
1665 Util.Warn("Skipping tight as it is only supported with true color");
1666 } else {
1667 var enc = encodings[i][1];
1668 buff[j] = enc >> 24;
1669 buff[j + 1] = enc >> 16;
1670 buff[j + 2] = enc >> 8;
1671 buff[j + 3] = enc;
1672
1673 j += 4;
1674 cnt++;
1675 }
1676 }
1677
1678 buff[offset + 2] = cnt >> 8;
1679 buff[offset + 3] = cnt;
1680
1681 sock._sQlen += j - offset;
1682 sock.flush();
1683 },
1684
1685 fbUpdateRequests: function (sock, onlyNonInc, cleanDirty, fb_width, fb_height) {
1686 var offsetIncrement = 0;
1687
1688 var cb = cleanDirty.cleanBox;
1689 var w, h;
1690 if (!onlyNonInc && (cb.w > 0 && cb.h > 0)) {
1691 w = typeof cb.w === "undefined" ? fb_width : cb.w;
1692 h = typeof cb.h === "undefined" ? fb_height : cb.h;
1693 // Request incremental for clean box
1694 RFB.messages.fbUpdateRequest(sock, 1, cb.x, cb.y, w, h);
1695 }
1696
1697 for (var i = 0; i < cleanDirty.dirtyBoxes.length; i++) {
1698 var db = cleanDirty.dirtyBoxes[i];
1699 // Force all (non-incremental) for dirty box
1700 w = typeof db.w === "undefined" ? fb_width : db.w;
1701 h = typeof db.h === "undefined" ? fb_height : db.h;
1702 RFB.messages.fbUpdateRequest(sock, 0, db.x, db.y, w, h);
1703 }
1704 },
1705
1706 fbUpdateRequest: function (sock, incremental, x, y, w, h) {
1707 var buff = sock._sQ;
1708 var offset = sock._sQlen;
1709
1710 if (typeof(x) === "undefined") { x = 0; }
1711 if (typeof(y) === "undefined") { y = 0; }
1712
1713 buff[offset] = 3; // msg-type
1714 buff[offset + 1] = incremental;
1715
1716 buff[offset + 2] = (x >> 8) & 0xFF;
1717 buff[offset + 3] = x & 0xFF;
1718
1719 buff[offset + 4] = (y >> 8) & 0xFF;
1720 buff[offset + 5] = y & 0xFF;
1721
1722 buff[offset + 6] = (w >> 8) & 0xFF;
1723 buff[offset + 7] = w & 0xFF;
1724
1725 buff[offset + 8] = (h >> 8) & 0xFF;
1726 buff[offset + 9] = h & 0xFF;
1727
1728 sock._sQlen += 10;
1729 sock.flush();
1730 }
1731 };
1732
1733 RFB.genDES = function (password, challenge) {
1734 var passwd = [];
1735 for (var i = 0; i < password.length; i++) {
1736 passwd.push(password.charCodeAt(i));
1737 }
1738 return (new DES(passwd)).encrypt(challenge);
1739 };
1740
1741 RFB.encodingHandlers = {
1742 RAW: function () {
1743 if (this._FBU.lines === 0) {
1744 this._FBU.lines = this._FBU.height;
1745 }
1746
1747 this._FBU.bytes = this._FBU.width * this._fb_Bpp; // at least a line
1748 if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; }
1749 var cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines);
1750 var curr_height = Math.min(this._FBU.lines,
1751 Math.floor(this._sock.rQlen() / (this._FBU.width * this._fb_Bpp)));
1752 this._display.blitImage(this._FBU.x, cur_y, this._FBU.width,
1753 curr_height, this._sock.get_rQ(),
1754 this._sock.get_rQi());
1755 this._sock.rQskipBytes(this._FBU.width * curr_height * this._fb_Bpp);
1756 this._FBU.lines -= curr_height;
1757
1758 if (this._FBU.lines > 0) {
1759 this._FBU.bytes = this._FBU.width * this._fb_Bpp; // At least another line
1760 } else {
1761 this._FBU.rects--;
1762 this._FBU.bytes = 0;
1763 }
1764
1765 return true;
1766 },
1767
1768 COPYRECT: function () {
1769 this._FBU.bytes = 4;
1770 if (this._sock.rQwait("COPYRECT", 4)) { return false; }
1771 this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
1772 this._FBU.x, this._FBU.y, this._FBU.width,
1773 this._FBU.height);
1774
1775 this._FBU.rects--;
1776 this._FBU.bytes = 0;
1777 return true;
1778 },
1779
1780 RRE: function () {
1781 var color;
1782 if (this._FBU.subrects === 0) {
1783 this._FBU.bytes = 4 + this._fb_Bpp;
1784 if (this._sock.rQwait("RRE", 4 + this._fb_Bpp)) { return false; }
1785 this._FBU.subrects = this._sock.rQshift32();
1786 color = this._sock.rQshiftBytes(this._fb_Bpp); // Background
1787 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, color);
1788 }
1789
1790 while (this._FBU.subrects > 0 && this._sock.rQlen() >= (this._fb_Bpp + 8)) {
1791 color = this._sock.rQshiftBytes(this._fb_Bpp);
1792 var x = this._sock.rQshift16();
1793 var y = this._sock.rQshift16();
1794 var width = this._sock.rQshift16();
1795 var height = this._sock.rQshift16();
1796 this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color);
1797 this._FBU.subrects--;
1798 }
1799
1800 if (this._FBU.subrects > 0) {
1801 var chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects);
1802 this._FBU.bytes = (this._fb_Bpp + 8) * chunk;
1803 } else {
1804 this._FBU.rects--;
1805 this._FBU.bytes = 0;
1806 }
1807
1808 return true;
1809 },
1810
1811 HEXTILE: function () {
1812 var rQ = this._sock.get_rQ();
1813 var rQi = this._sock.get_rQi();
1814
1815 if (this._FBU.tiles === 0) {
1816 this._FBU.tiles_x = Math.ceil(this._FBU.width / 16);
1817 this._FBU.tiles_y = Math.ceil(this._FBU.height / 16);
1818 this._FBU.total_tiles = this._FBU.tiles_x * this._FBU.tiles_y;
1819 this._FBU.tiles = this._FBU.total_tiles;
1820 }
1821
1822 while (this._FBU.tiles > 0) {
1823 this._FBU.bytes = 1;
1824 if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; }
1825 var subencoding = rQ[rQi]; // Peek
1826 if (subencoding > 30) { // Raw
1827 this._fail("Disconnected: illegal hextile subencoding " + subencoding);
1828 return false;
1829 }
1830
1831 var subrects = 0;
1832 var curr_tile = this._FBU.total_tiles - this._FBU.tiles;
1833 var tile_x = curr_tile % this._FBU.tiles_x;
1834 var tile_y = Math.floor(curr_tile / this._FBU.tiles_x);
1835 var x = this._FBU.x + tile_x * 16;
1836 var y = this._FBU.y + tile_y * 16;
1837 var w = Math.min(16, (this._FBU.x + this._FBU.width) - x);
1838 var h = Math.min(16, (this._FBU.y + this._FBU.height) - y);
1839
1840 // Figure out how much we are expecting
1841 if (subencoding & 0x01) { // Raw
1842 this._FBU.bytes += w * h * this._fb_Bpp;
1843 } else {
1844 if (subencoding & 0x02) { // Background
1845 this._FBU.bytes += this._fb_Bpp;
1846 }
1847 if (subencoding & 0x04) { // Foreground
1848 this._FBU.bytes += this._fb_Bpp;
1849 }
1850 if (subencoding & 0x08) { // AnySubrects
1851 this._FBU.bytes++; // Since we aren't shifting it off
1852 if (this._sock.rQwait("hextile subrects header", this._FBU.bytes)) { return false; }
1853 subrects = rQ[rQi + this._FBU.bytes - 1]; // Peek
1854 if (subencoding & 0x10) { // SubrectsColoured
1855 this._FBU.bytes += subrects * (this._fb_Bpp + 2);
1856 } else {
1857 this._FBU.bytes += subrects * 2;
1858 }
1859 }
1860 }
1861
1862 if (this._sock.rQwait("hextile", this._FBU.bytes)) { return false; }
1863
1864 // We know the encoding and have a whole tile
1865 this._FBU.subencoding = rQ[rQi];
1866 rQi++;
1867 if (this._FBU.subencoding === 0) {
1868 if (this._FBU.lastsubencoding & 0x01) {
1869 // Weird: ignore blanks are RAW
1870 Util.Debug(" Ignoring blank after RAW");
1871 } else {
1872 this._display.fillRect(x, y, w, h, this._FBU.background);
1873 }
1874 } else if (this._FBU.subencoding & 0x01) { // Raw
1875 this._display.blitImage(x, y, w, h, rQ, rQi);
1876 rQi += this._FBU.bytes - 1;
1877 } else {
1878 if (this._FBU.subencoding & 0x02) { // Background
1879 if (this._fb_Bpp == 1) {
1880 this._FBU.background = rQ[rQi];
1881 } else {
1882 // fb_Bpp is 4
1883 this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1884 }
1885 rQi += this._fb_Bpp;
1886 }
1887 if (this._FBU.subencoding & 0x04) { // Foreground
1888 if (this._fb_Bpp == 1) {
1889 this._FBU.foreground = rQ[rQi];
1890 } else {
1891 // this._fb_Bpp is 4
1892 this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1893 }
1894 rQi += this._fb_Bpp;
1895 }
1896
1897 this._display.startTile(x, y, w, h, this._FBU.background);
1898 if (this._FBU.subencoding & 0x08) { // AnySubrects
1899 subrects = rQ[rQi];
1900 rQi++;
1901
1902 for (var s = 0; s < subrects; s++) {
1903 var color;
1904 if (this._FBU.subencoding & 0x10) { // SubrectsColoured
1905 if (this._fb_Bpp === 1) {
1906 color = rQ[rQi];
1907 } else {
1908 // _fb_Bpp is 4
1909 color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1910 }
1911 rQi += this._fb_Bpp;
1912 } else {
1913 color = this._FBU.foreground;
1914 }
1915 var xy = rQ[rQi];
1916 rQi++;
1917 var sx = (xy >> 4);
1918 var sy = (xy & 0x0f);
1919
1920 var wh = rQ[rQi];
1921 rQi++;
1922 var sw = (wh >> 4) + 1;
1923 var sh = (wh & 0x0f) + 1;
1924
1925 this._display.subTile(sx, sy, sw, sh, color);
1926 }
1927 }
1928 this._display.finishTile();
1929 }
1930 this._sock.set_rQi(rQi);
1931 this._FBU.lastsubencoding = this._FBU.subencoding;
1932 this._FBU.bytes = 0;
1933 this._FBU.tiles--;
1934 }
1935
1936 if (this._FBU.tiles === 0) {
1937 this._FBU.rects--;
1938 }
1939
1940 return true;
1941 },
1942
1943 getTightCLength: function (arr) {
1944 var header = 1, data = 0;
1945 data += arr[0] & 0x7f;
1946 if (arr[0] & 0x80) {
1947 header++;
1948 data += (arr[1] & 0x7f) << 7;
1949 if (arr[1] & 0x80) {
1950 header++;
1951 data += arr[2] << 14;
1952 }
1953 }
1954 return [header, data];
1955 },
1956
1957 display_tight: function (isTightPNG) {
1958 if (this._fb_depth === 1) {
1959 this._fail("Tight protocol handler only implements true color mode");
1960 }
1961
1962 this._FBU.bytes = 1; // compression-control byte
1963 if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; }
1964
1965 var checksum = function (data) {
1966 var sum = 0;
1967 for (var i = 0; i < data.length; i++) {
1968 sum += data[i];
1969 if (sum > 65536) sum -= 65536;
1970 }
1971 return sum;
1972 };
1973
1974 var resetStreams = 0;
1975 var streamId = -1;
1976 var decompress = function (data, expected) {
1977 for (var i = 0; i < 4; i++) {
1978 if ((resetStreams >> i) & 1) {
1979 this._FBU.zlibs[i].reset();
1980 Util.Info("Reset zlib stream " + i);
1981 }
1982 }
1983
1984 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1985 var uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected);
1986 /*if (uncompressed.status !== 0) {
1987 Util.Error("Invalid data in zlib stream");
1988 }*/
1989
1990 //return uncompressed.data;
1991 return uncompressed;
1992 }.bind(this);
1993
1994 var indexedToRGBX2Color = function (data, palette, width, height) {
1995 // Convert indexed (palette based) image data to RGB
1996 // TODO: reduce number of calculations inside loop
1997 var dest = this._destBuff;
1998 var w = Math.floor((width + 7) / 8);
1999 var w1 = Math.floor(width / 8);
2000
2001 /*for (var y = 0; y < height; y++) {
2002 var b, x, dp, sp;
2003 var yoffset = y * width;
2004 var ybitoffset = y * w;
2005 var xoffset, targetbyte;
2006 for (x = 0; x < w1; x++) {
2007 xoffset = yoffset + x * 8;
2008 targetbyte = data[ybitoffset + x];
2009 for (b = 7; b >= 0; b--) {
2010 dp = (xoffset + 7 - b) * 3;
2011 sp = (targetbyte >> b & 1) * 3;
2012 dest[dp] = palette[sp];
2013 dest[dp + 1] = palette[sp + 1];
2014 dest[dp + 2] = palette[sp + 2];
2015 }
2016 }
2017
2018 xoffset = yoffset + x * 8;
2019 targetbyte = data[ybitoffset + x];
2020 for (b = 7; b >= 8 - width % 8; b--) {
2021 dp = (xoffset + 7 - b) * 3;
2022 sp = (targetbyte >> b & 1) * 3;
2023 dest[dp] = palette[sp];
2024 dest[dp + 1] = palette[sp + 1];
2025 dest[dp + 2] = palette[sp + 2];
2026 }
2027 }*/
2028
2029 for (var y = 0; y < height; y++) {
2030 var b, x, dp, sp;
2031 for (x = 0; x < w1; x++) {
2032 for (b = 7; b >= 0; b--) {
2033 dp = (y * width + x * 8 + 7 - b) * 4;
2034 sp = (data[y * w + x] >> b & 1) * 3;
2035 dest[dp] = palette[sp];
2036 dest[dp + 1] = palette[sp + 1];
2037 dest[dp + 2] = palette[sp + 2];
2038 dest[dp + 3] = 255;
2039 }
2040 }
2041
2042 for (b = 7; b >= 8 - width % 8; b--) {
2043 dp = (y * width + x * 8 + 7 - b) * 4;
2044 sp = (data[y * w + x] >> b & 1) * 3;
2045 dest[dp] = palette[sp];
2046 dest[dp + 1] = palette[sp + 1];
2047 dest[dp + 2] = palette[sp + 2];
2048 dest[dp + 3] = 255;
2049 }
2050 }
2051
2052 return dest;
2053 }.bind(this);
2054
2055 var indexedToRGBX = function (data, palette, width, height) {
2056 // Convert indexed (palette based) image data to RGB
2057 var dest = this._destBuff;
2058 var total = width * height * 4;
2059 for (var i = 0, j = 0; i < total; i += 4, j++) {
2060 var sp = data[j] * 3;
2061 dest[i] = palette[sp];
2062 dest[i + 1] = palette[sp + 1];
2063 dest[i + 2] = palette[sp + 2];
2064 dest[i + 3] = 255;
2065 }
2066
2067 return dest;
2068 }.bind(this);
2069
2070 var rQi = this._sock.get_rQi();
2071 var rQ = this._sock.rQwhole();
2072 var cmode, data;
2073 var cl_header, cl_data;
2074
2075 var handlePalette = function () {
2076 var numColors = rQ[rQi + 2] + 1;
2077 var paletteSize = numColors * this._fb_depth;
2078 this._FBU.bytes += paletteSize;
2079 if (this._sock.rQwait("TIGHT palette " + cmode, this._FBU.bytes)) { return false; }
2080
2081 var bpp = (numColors <= 2) ? 1 : 8;
2082 var rowSize = Math.floor((this._FBU.width * bpp + 7) / 8);
2083 var raw = false;
2084 if (rowSize * this._FBU.height < 12) {
2085 raw = true;
2086 cl_header = 0;
2087 cl_data = rowSize * this._FBU.height;
2088 //clength = [0, rowSize * this._FBU.height];
2089 } else {
2090 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2091 var cl_offset = rQi + 3 + paletteSize;
2092 cl_header = 1;
2093 cl_data = 0;
2094 cl_data += rQ[cl_offset] & 0x7f;
2095 if (rQ[cl_offset] & 0x80) {
2096 cl_header++;
2097 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2098 if (rQ[cl_offset + 1] & 0x80) {
2099 cl_header++;
2100 cl_data += rQ[cl_offset + 2] << 14;
2101 }
2102 }
2103 // end inline getTightCLength
2104 }
2105
2106 this._FBU.bytes += cl_header + cl_data;
2107 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2108
2109 // Shift ctl, filter id, num colors, palette entries, and clength off
2110 this._sock.rQskipBytes(3);
2111 //var palette = this._sock.rQshiftBytes(paletteSize);
2112 this._sock.rQshiftTo(this._paletteBuff, paletteSize);
2113 this._sock.rQskipBytes(cl_header);
2114
2115 if (raw) {
2116 data = this._sock.rQshiftBytes(cl_data);
2117 } else {
2118 data = decompress(this._sock.rQshiftBytes(cl_data), rowSize * this._FBU.height);
2119 }
2120
2121 // Convert indexed (palette based) image data to RGB
2122 var rgbx;
2123 if (numColors == 2) {
2124 rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2125 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2126 } else {
2127 rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2128 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2129 }
2130
2131
2132 return true;
2133 }.bind(this);
2134
2135 var handleCopy = function () {
2136 var raw = false;
2137 var uncompressedSize = this._FBU.width * this._FBU.height * this._fb_depth;
2138 if (uncompressedSize < 12) {
2139 raw = true;
2140 cl_header = 0;
2141 cl_data = uncompressedSize;
2142 } else {
2143 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2144 var cl_offset = rQi + 1;
2145 cl_header = 1;
2146 cl_data = 0;
2147 cl_data += rQ[cl_offset] & 0x7f;
2148 if (rQ[cl_offset] & 0x80) {
2149 cl_header++;
2150 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2151 if (rQ[cl_offset + 1] & 0x80) {
2152 cl_header++;
2153 cl_data += rQ[cl_offset + 2] << 14;
2154 }
2155 }
2156 // end inline getTightCLength
2157 }
2158 this._FBU.bytes = 1 + cl_header + cl_data;
2159 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2160
2161 // Shift ctl, clength off
2162 this._sock.rQshiftBytes(1 + cl_header);
2163
2164 if (raw) {
2165 data = this._sock.rQshiftBytes(cl_data);
2166 } else {
2167 data = decompress(this._sock.rQshiftBytes(cl_data), uncompressedSize);
2168 }
2169
2170 this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
2171
2172 return true;
2173 }.bind(this);
2174
2175 var ctl = this._sock.rQpeek8();
2176
2177 // Keep tight reset bits
2178 resetStreams = ctl & 0xF;
2179
2180 // Figure out filter
2181 ctl = ctl >> 4;
2182 streamId = ctl & 0x3;
2183
2184 if (ctl === 0x08) cmode = "fill";
2185 else if (ctl === 0x09) cmode = "jpeg";
2186 else if (ctl === 0x0A) cmode = "png";
2187 else if (ctl & 0x04) cmode = "filter";
2188 else if (ctl < 0x04) cmode = "copy";
2189 else return this._fail("Illegal tight compression received, ctl: " + ctl);
2190
2191 if (isTightPNG && (cmode === "filter" || cmode === "copy")) {
2192 return this._fail("filter/copy received in tightPNG mode");
2193 }
2194
2195 switch (cmode) {
2196 // fill use fb_depth because TPIXELs drop the padding byte
2197 case "fill": // TPIXEL
2198 this._FBU.bytes += this._fb_depth;
2199 break;
2200 case "jpeg": // max clength
2201 this._FBU.bytes += 3;
2202 break;
2203 case "png": // max clength
2204 this._FBU.bytes += 3;
2205 break;
2206 case "filter": // filter id + num colors if palette
2207 this._FBU.bytes += 2;
2208 break;
2209 case "copy":
2210 break;
2211 }
2212
2213 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2214
2215 // Determine FBU.bytes
2216 switch (cmode) {
2217 case "fill":
2218 // skip ctl byte
2219 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);
2220 this._sock.rQskipBytes(4);
2221 break;
2222 case "png":
2223 case "jpeg":
2224 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2225 var cl_offset = rQi + 1;
2226 cl_header = 1;
2227 cl_data = 0;
2228 cl_data += rQ[cl_offset] & 0x7f;
2229 if (rQ[cl_offset] & 0x80) {
2230 cl_header++;
2231 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2232 if (rQ[cl_offset + 1] & 0x80) {
2233 cl_header++;
2234 cl_data += rQ[cl_offset + 2] << 14;
2235 }
2236 }
2237 // end inline getTightCLength
2238 this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
2239 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2240
2241 // We have everything, render it
2242 this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
2243 data = this._sock.rQshiftBytes(cl_data);
2244 this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data);
2245 break;
2246 case "filter":
2247 var filterId = rQ[rQi + 1];
2248 if (filterId === 1) {
2249 if (!handlePalette()) { return false; }
2250 } else {
2251 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2252 // Filter 2, Gradient is valid but not use if jpeg is enabled
2253 this._fail("Unsupported tight subencoding received, filter: " + filterId);
2254 }
2255 break;
2256 case "copy":
2257 if (!handleCopy()) { return false; }
2258 break;
2259 }
2260
2261
2262 this._FBU.bytes = 0;
2263 this._FBU.rects--;
2264
2265 return true;
2266 },
2267
2268 TIGHT: function () { return this._encHandlers.display_tight(false); },
2269 TIGHT_PNG: function () { return this._encHandlers.display_tight(true); },
2270
2271 last_rect: function () {
2272 this._FBU.rects = 0;
2273 return true;
2274 },
2275
2276 handle_FB_resize: function () {
2277 this._fb_width = this._FBU.width;
2278 this._fb_height = this._FBU.height;
2279 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
2280 this._display.resize(this._fb_width, this._fb_height);
2281 this._onFBResize(this, this._fb_width, this._fb_height);
2282 this._timing.fbu_rt_start = (new Date()).getTime();
2283 this._updateContinuousUpdates();
2284
2285 this._FBU.bytes = 0;
2286 this._FBU.rects -= 1;
2287 return true;
2288 },
2289
2290 ExtendedDesktopSize: function () {
2291 this._FBU.bytes = 1;
2292 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2293
2294 this._supportsSetDesktopSize = true;
2295 var number_of_screens = this._sock.rQpeek8();
2296
2297 this._FBU.bytes = 4 + (number_of_screens * 16);
2298 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2299
2300 this._sock.rQskipBytes(1); // number-of-screens
2301 this._sock.rQskipBytes(3); // padding
2302
2303 for (var i = 0; i < number_of_screens; i += 1) {
2304 // Save the id and flags of the first screen
2305 if (i === 0) {
2306 this._screen_id = this._sock.rQshiftBytes(4); // id
2307 this._sock.rQskipBytes(2); // x-position
2308 this._sock.rQskipBytes(2); // y-position
2309 this._sock.rQskipBytes(2); // width
2310 this._sock.rQskipBytes(2); // height
2311 this._screen_flags = this._sock.rQshiftBytes(4); // flags
2312 } else {
2313 this._sock.rQskipBytes(16);
2314 }
2315 }
2316
2317 /*
2318 * The x-position indicates the reason for the change:
2319 *
2320 * 0 - server resized on its own
2321 * 1 - this client requested the resize
2322 * 2 - another client requested the resize
2323 */
2324
2325 // We need to handle errors when we requested the resize.
2326 if (this._FBU.x === 1 && this._FBU.y !== 0) {
2327 var msg = "";
2328 // The y-position indicates the status code from the server
2329 switch (this._FBU.y) {
2330 case 1:
2331 msg = "Resize is administratively prohibited";
2332 break;
2333 case 2:
2334 msg = "Out of resources";
2335 break;
2336 case 3:
2337 msg = "Invalid screen layout";
2338 break;
2339 default:
2340 msg = "Unknown reason";
2341 break;
2342 }
2343 this._notification("Server did not accept the resize request: "
2344 + msg, 'normal');
2345 return true;
2346 }
2347
2348 this._encHandlers.handle_FB_resize();
2349 return true;
2350 },
2351
2352 DesktopSize: function () {
2353 this._encHandlers.handle_FB_resize();
2354 return true;
2355 },
2356
2357 Cursor: function () {
2358 Util.Debug(">> set_cursor");
2359 var x = this._FBU.x; // hotspot-x
2360 var y = this._FBU.y; // hotspot-y
2361 var w = this._FBU.width;
2362 var h = this._FBU.height;
2363
2364 var pixelslength = w * h * this._fb_Bpp;
2365 var masklength = Math.floor((w + 7) / 8) * h;
2366
2367 this._FBU.bytes = pixelslength + masklength;
2368 if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
2369
2370 this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
2371 this._sock.rQshiftBytes(masklength),
2372 x, y, w, h);
2373
2374 this._FBU.bytes = 0;
2375 this._FBU.rects--;
2376
2377 Util.Debug("<< set_cursor");
2378 return true;
2379 },
2380
2381 QEMUExtendedKeyEvent: function () {
2382 this._FBU.rects--;
2383
2384 var keyboardEvent = document.createEvent("keyboardEvent");
2385 if (keyboardEvent.code !== undefined) {
2386 this._qemuExtKeyEventSupported = true;
2387 this._keyboard.setQEMUVNCKeyboardHandler();
2388 }
2389 },
2390
2391 JPEG_quality_lo: function () {
2392 Util.Error("Server sent jpeg_quality pseudo-encoding");
2393 },
2394
2395 compress_lo: function () {
2396 Util.Error("Server sent compress level pseudo-encoding");
2397 }
2398 };
2399 })();