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