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