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