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