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