]> git.proxmox.com Git - mirror_novnc.git/blob - core/rfb.js
Replace updatestate event with connect
[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 _ 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
516 var smsg = "New state '" + state + "', was '" + oldstate + "'.";
517 Log.Debug(smsg);
518
519 if (this._disconnTimer && state !== 'disconnecting') {
520 Log.Debug("Clearing disconnect timer");
521 clearTimeout(this._disconnTimer);
522 this._disconnTimer = null;
523
524 // make sure we don't get a double event
525 this._sock.off('close');
526 }
527
528 switch (state) {
529 case 'connecting':
530 this._connect();
531 break;
532
533 case 'connected':
534 var event = new CustomEvent("connect", { detail: {} });
535 this.dispatchEvent(event);
536 break;
537
538 case 'disconnecting':
539 this._disconnect();
540
541 this._disconnTimer = setTimeout(function () {
542 this._rfb_disconnect_reason = _("Disconnect timeout");
543 this._updateConnectionState('disconnected');
544 }.bind(this), DISCONNECT_TIMEOUT * 1000);
545 break;
546
547 case 'disconnected':
548 if (this._rfb_disconnect_reason !== "") {
549 event = new CustomEvent("disconnect",
550 { detail: { reason: this._rfb_disconnect_reason } });
551 } else {
552 // No reason means clean disconnect
553 event = new CustomEvent("disconnect", { detail: {} });
554 }
555 this.dispatchEvent(event);
556 break;
557 }
558 },
559
560 /* Print errors and disconnect
561 *
562 * The optional parameter 'details' is used for information that
563 * should be logged but not sent to the user interface.
564 */
565 _fail: function (msg, details) {
566 var fullmsg = msg;
567 if (typeof details !== 'undefined') {
568 fullmsg = msg + " (" + details + ")";
569 }
570 switch (this._rfb_connection_state) {
571 case 'disconnecting':
572 Log.Error("Failed when disconnecting: " + fullmsg);
573 break;
574 case 'connected':
575 Log.Error("Failed while connected: " + fullmsg);
576 break;
577 case 'connecting':
578 Log.Error("Failed when connecting: " + fullmsg);
579 break;
580 default:
581 Log.Error("RFB failure: " + fullmsg);
582 break;
583 }
584 this._rfb_disconnect_reason = msg; //This is sent to the UI
585
586 // Transition to disconnected without waiting for socket to close
587 this._updateConnectionState('disconnecting');
588 this._updateConnectionState('disconnected');
589
590 return false;
591 },
592
593 _setCapability: function (cap, val) {
594 this._capabilities[cap] = val;
595 var event = new CustomEvent("capabilities",
596 { detail: { capabilities: this._capabilities } });
597 this.dispatchEvent(event);
598 },
599
600 _handle_message: function () {
601 if (this._sock.rQlen() === 0) {
602 Log.Warn("handle_message called on an empty receive queue");
603 return;
604 }
605
606 switch (this._rfb_connection_state) {
607 case 'disconnected':
608 Log.Error("Got data while disconnected");
609 break;
610 case 'connected':
611 while (true) {
612 if (this._flushing) {
613 break;
614 }
615 if (!this._normal_msg()) {
616 break;
617 }
618 if (this._sock.rQlen() === 0) {
619 break;
620 }
621 }
622 break;
623 default:
624 this._init_msg();
625 break;
626 }
627 },
628
629 _handleKeyEvent: function (keysym, code, down) {
630 this.sendKey(keysym, code, down);
631 },
632
633 _handleMouseButton: function (x, y, down, bmask) {
634 if (down) {
635 this._mouse_buttonMask |= bmask;
636 } else {
637 this._mouse_buttonMask &= ~bmask;
638 }
639
640 if (this.dragViewport) {
641 if (down && !this._viewportDragging) {
642 this._viewportDragging = true;
643 this._viewportDragPos = {'x': x, 'y': y};
644
645 // Skip sending mouse events
646 return;
647 } else {
648 this._viewportDragging = false;
649
650 // If the viewport didn't actually move, then treat as a mouse click event
651 // Send the button down event here, as the button up event is sent at the end of this function
652 if (!this._viewportHasMoved && !this._viewOnly) {
653 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), bmask);
654 }
655 this._viewportHasMoved = false;
656 }
657 }
658
659 if (this._viewOnly) { return; } // View only, skip mouse events
660
661 if (this._rfb_connection_state !== 'connected') { return; }
662 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
663 },
664
665 _handleMouseMove: function (x, y) {
666 if (this._viewportDragging) {
667 var deltaX = this._viewportDragPos.x - x;
668 var deltaY = this._viewportDragPos.y - y;
669
670 // The goal is to trigger on a certain physical width, the
671 // devicePixelRatio brings us a bit closer but is not optimal.
672 var dragThreshold = 10 * (window.devicePixelRatio || 1);
673
674 if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
675 Math.abs(deltaY) > dragThreshold)) {
676 this._viewportHasMoved = true;
677
678 this._viewportDragPos = {'x': x, 'y': y};
679 this._display.viewportChangePos(deltaX, deltaY);
680 }
681
682 // Skip sending mouse events
683 return;
684 }
685
686 if (this._viewOnly) { return; } // View only, skip mouse events
687
688 if (this._rfb_connection_state !== 'connected') { return; }
689 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
690 },
691
692 // Message Handlers
693
694 _negotiate_protocol_version: function () {
695 if (this._sock.rQlen() < 12) {
696 return this._fail("Error while negotiating with server",
697 "Incomplete protocol version");
698 }
699
700 var sversion = this._sock.rQshiftStr(12).substr(4, 7);
701 Log.Info("Server ProtocolVersion: " + sversion);
702 var is_repeater = 0;
703 switch (sversion) {
704 case "000.000": // UltraVNC repeater
705 is_repeater = 1;
706 break;
707 case "003.003":
708 case "003.006": // UltraVNC
709 case "003.889": // Apple Remote Desktop
710 this._rfb_version = 3.3;
711 break;
712 case "003.007":
713 this._rfb_version = 3.7;
714 break;
715 case "003.008":
716 case "004.000": // Intel AMT KVM
717 case "004.001": // RealVNC 4.6
718 case "005.000": // RealVNC 5.3
719 this._rfb_version = 3.8;
720 break;
721 default:
722 return this._fail("Unsupported server",
723 "Invalid server version: " + sversion);
724 }
725
726 if (is_repeater) {
727 var repeaterID = "ID:" + this._repeaterID;
728 while (repeaterID.length < 250) {
729 repeaterID += "\0";
730 }
731 this._sock.send_string(repeaterID);
732 return true;
733 }
734
735 if (this._rfb_version > this._rfb_max_version) {
736 this._rfb_version = this._rfb_max_version;
737 }
738
739 var cversion = "00" + parseInt(this._rfb_version, 10) +
740 ".00" + ((this._rfb_version * 10) % 10);
741 this._sock.send_string("RFB " + cversion + "\n");
742 Log.Debug('Sent ProtocolVersion: ' + cversion);
743
744 this._rfb_init_state = 'Security';
745 },
746
747 _negotiate_security: function () {
748 // Polyfill since IE and PhantomJS doesn't have
749 // TypedArray.includes()
750 function includes(item, array) {
751 for (var i = 0; i < array.length; i++) {
752 if (array[i] === item) {
753 return true;
754 }
755 }
756 return false;
757 }
758
759 if (this._rfb_version >= 3.7) {
760 // Server sends supported list, client decides
761 var num_types = this._sock.rQshift8();
762 if (this._sock.rQwait("security type", num_types, 1)) { return false; }
763
764 if (num_types === 0) {
765 var strlen = this._sock.rQshift32();
766 var reason = this._sock.rQshiftStr(strlen);
767 return this._fail("Error while negotiating with server",
768 "Security failure: " + reason);
769 }
770
771 var types = this._sock.rQshiftBytes(num_types);
772 Log.Debug("Server security types: " + types);
773
774 // Look for each auth in preferred order
775 this._rfb_auth_scheme = 0;
776 if (includes(1, types)) {
777 this._rfb_auth_scheme = 1; // None
778 } else if (includes(22, types)) {
779 this._rfb_auth_scheme = 22; // XVP
780 } else if (includes(16, types)) {
781 this._rfb_auth_scheme = 16; // Tight
782 } else if (includes(2, types)) {
783 this._rfb_auth_scheme = 2; // VNC Auth
784 } else {
785 return this._fail("Unsupported server",
786 "Unsupported security types: " + types);
787 }
788
789 this._sock.send([this._rfb_auth_scheme]);
790 } else {
791 // Server decides
792 if (this._sock.rQwait("security scheme", 4)) { return false; }
793 this._rfb_auth_scheme = this._sock.rQshift32();
794 }
795
796 this._rfb_init_state = 'Authentication';
797 Log.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme);
798
799 return this._init_msg(); // jump to authentication
800 },
801
802 // authentication
803 _negotiate_xvp_auth: function () {
804 if (!this._rfb_credentials.username ||
805 !this._rfb_credentials.password ||
806 !this._rfb_credentials.target) {
807 var event = new CustomEvent("credentialsrequired",
808 { detail: { types: ["username", "password", "target"] } });
809 this.dispatchEvent(event);
810 return false;
811 }
812
813 var xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) +
814 String.fromCharCode(this._rfb_credentials.target.length) +
815 this._rfb_credentials.username +
816 this._rfb_credentials.target;
817 this._sock.send_string(xvp_auth_str);
818 this._rfb_auth_scheme = 2;
819 return this._negotiate_authentication();
820 },
821
822 _negotiate_std_vnc_auth: function () {
823 if (this._sock.rQwait("auth challenge", 16)) { return false; }
824
825 if (!this._rfb_credentials.password) {
826 var event = new CustomEvent("credentialsrequired",
827 { detail: { types: ["password"] } });
828 this.dispatchEvent(event);
829 return false;
830 }
831
832 // TODO(directxman12): make genDES not require an Array
833 var challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
834 var response = RFB.genDES(this._rfb_credentials.password, challenge);
835 this._sock.send(response);
836 this._rfb_init_state = "SecurityResult";
837 return true;
838 },
839
840 _negotiate_tight_tunnels: function (numTunnels) {
841 var clientSupportedTunnelTypes = {
842 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
843 };
844 var serverSupportedTunnelTypes = {};
845 // receive tunnel capabilities
846 for (var i = 0; i < numTunnels; i++) {
847 var cap_code = this._sock.rQshift32();
848 var cap_vendor = this._sock.rQshiftStr(4);
849 var cap_signature = this._sock.rQshiftStr(8);
850 serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature };
851 }
852
853 // choose the notunnel type
854 if (serverSupportedTunnelTypes[0]) {
855 if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
856 serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
857 return this._fail("Unsupported server",
858 "Client's tunnel type had the incorrect " +
859 "vendor or signature");
860 }
861 this._sock.send([0, 0, 0, 0]); // use NOTUNNEL
862 return false; // wait until we receive the sub auth count to continue
863 } else {
864 return this._fail("Unsupported server",
865 "Server wanted tunnels, but doesn't support " +
866 "the notunnel type");
867 }
868 },
869
870 _negotiate_tight_auth: function () {
871 if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation
872 if (this._sock.rQwait("num tunnels", 4)) { return false; }
873 var numTunnels = this._sock.rQshift32();
874 if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
875
876 this._rfb_tightvnc = true;
877
878 if (numTunnels > 0) {
879 this._negotiate_tight_tunnels(numTunnels);
880 return false; // wait until we receive the sub auth to continue
881 }
882 }
883
884 // second pass, do the sub-auth negotiation
885 if (this._sock.rQwait("sub auth count", 4)) { return false; }
886 var subAuthCount = this._sock.rQshift32();
887 if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
888 this._rfb_init_state = 'SecurityResult';
889 return true;
890 }
891
892 if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
893
894 var clientSupportedTypes = {
895 'STDVNOAUTH__': 1,
896 'STDVVNCAUTH_': 2
897 };
898
899 var serverSupportedTypes = [];
900
901 for (var i = 0; i < subAuthCount; i++) {
902 var capNum = this._sock.rQshift32();
903 var capabilities = this._sock.rQshiftStr(12);
904 serverSupportedTypes.push(capabilities);
905 }
906
907 for (var authType in clientSupportedTypes) {
908 if (serverSupportedTypes.indexOf(authType) != -1) {
909 this._sock.send([0, 0, 0, clientSupportedTypes[authType]]);
910
911 switch (authType) {
912 case 'STDVNOAUTH__': // no auth
913 this._rfb_init_state = 'SecurityResult';
914 return true;
915 case 'STDVVNCAUTH_': // VNC auth
916 this._rfb_auth_scheme = 2;
917 return this._init_msg();
918 default:
919 return this._fail("Unsupported server",
920 "Unsupported tiny auth scheme: " +
921 authType);
922 }
923 }
924 }
925
926 return this._fail("Unsupported server",
927 "No supported sub-auth types!");
928 },
929
930 _negotiate_authentication: function () {
931 switch (this._rfb_auth_scheme) {
932 case 0: // connection failed
933 if (this._sock.rQwait("auth reason", 4)) { return false; }
934 var strlen = this._sock.rQshift32();
935 var reason = this._sock.rQshiftStr(strlen);
936 return this._fail("Authentication failure", reason);
937
938 case 1: // no auth
939 if (this._rfb_version >= 3.8) {
940 this._rfb_init_state = 'SecurityResult';
941 return true;
942 }
943 this._rfb_init_state = 'ClientInitialisation';
944 return this._init_msg();
945
946 case 22: // XVP auth
947 return this._negotiate_xvp_auth();
948
949 case 2: // VNC authentication
950 return this._negotiate_std_vnc_auth();
951
952 case 16: // TightVNC Security Type
953 return this._negotiate_tight_auth();
954
955 default:
956 return this._fail("Unsupported server",
957 "Unsupported auth scheme: " +
958 this._rfb_auth_scheme);
959 }
960 },
961
962 _handle_security_result: function () {
963 if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
964 switch (this._sock.rQshift32()) {
965 case 0: // OK
966 this._rfb_init_state = 'ClientInitialisation';
967 Log.Debug('Authentication OK');
968 return this._init_msg();
969 case 1: // failed
970 if (this._rfb_version >= 3.8) {
971 var length = this._sock.rQshift32();
972 if (this._sock.rQwait("SecurityResult reason", length, 8)) { return false; }
973 var reason = this._sock.rQshiftStr(length);
974 return this._fail("Authentication failure", reason);
975 } else {
976 return this._fail("Authentication failure");
977 }
978 case 2:
979 return this._fail("Too many authentication attempts");
980 default:
981 return this._fail("Unsupported server",
982 "Unknown SecurityResult");
983 }
984 },
985
986 _negotiate_server_init: function () {
987 if (this._sock.rQwait("server initialization", 24)) { return false; }
988
989 /* Screen size */
990 var width = this._sock.rQshift16();
991 var height = this._sock.rQshift16();
992
993 /* PIXEL_FORMAT */
994 var bpp = this._sock.rQshift8();
995 var depth = this._sock.rQshift8();
996 var big_endian = this._sock.rQshift8();
997 var true_color = this._sock.rQshift8();
998
999 var red_max = this._sock.rQshift16();
1000 var green_max = this._sock.rQshift16();
1001 var blue_max = this._sock.rQshift16();
1002 var red_shift = this._sock.rQshift8();
1003 var green_shift = this._sock.rQshift8();
1004 var blue_shift = this._sock.rQshift8();
1005 this._sock.rQskipBytes(3); // padding
1006
1007 // NB(directxman12): we don't want to call any callbacks or print messages until
1008 // *after* we're past the point where we could backtrack
1009
1010 /* Connection name/title */
1011 var name_length = this._sock.rQshift32();
1012 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1013 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1014
1015 if (this._rfb_tightvnc) {
1016 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1017 // In TightVNC mode, ServerInit message is extended
1018 var numServerMessages = this._sock.rQshift16();
1019 var numClientMessages = this._sock.rQshift16();
1020 var numEncodings = this._sock.rQshift16();
1021 this._sock.rQskipBytes(2); // padding
1022
1023 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1024 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1025
1026 // we don't actually do anything with the capability information that TIGHT sends,
1027 // so we just skip the all of this.
1028
1029 // TIGHT server message capabilities
1030 this._sock.rQskipBytes(16 * numServerMessages);
1031
1032 // TIGHT client message capabilities
1033 this._sock.rQskipBytes(16 * numClientMessages);
1034
1035 // TIGHT encoding capabilities
1036 this._sock.rQskipBytes(16 * numEncodings);
1037 }
1038
1039 // NB(directxman12): these are down here so that we don't run them multiple times
1040 // if we backtrack
1041 Log.Info("Screen: " + width + "x" + height +
1042 ", bpp: " + bpp + ", depth: " + depth +
1043 ", big_endian: " + big_endian +
1044 ", true_color: " + true_color +
1045 ", red_max: " + red_max +
1046 ", green_max: " + green_max +
1047 ", blue_max: " + blue_max +
1048 ", red_shift: " + red_shift +
1049 ", green_shift: " + green_shift +
1050 ", blue_shift: " + blue_shift);
1051
1052 if (big_endian !== 0) {
1053 Log.Warn("Server native endian is not little endian");
1054 }
1055
1056 if (red_shift !== 16) {
1057 Log.Warn("Server native red-shift is not 16");
1058 }
1059
1060 if (blue_shift !== 0) {
1061 Log.Warn("Server native blue-shift is not 0");
1062 }
1063
1064 // we're past the point where we could backtrack, so it's safe to call this
1065 var event = new CustomEvent("desktopname",
1066 { detail: { name: this._fb_name } });
1067 this.dispatchEvent(event);
1068
1069 this._resize(width, height);
1070
1071 if (!this._viewOnly) { this._keyboard.grab(); }
1072 if (!this._viewOnly) { this._mouse.grab(); }
1073
1074 this._fb_depth = 24;
1075
1076 if (this._fb_name === "Intel(r) AMT KVM") {
1077 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1078 this._fb_depth = 8;
1079 }
1080
1081 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1082 this._sendEncodings();
1083 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1084
1085 this._timing.fbu_rt_start = (new Date()).getTime();
1086 this._timing.pixels = 0;
1087
1088 // Cursor will be server side until the server decides to honor
1089 // our request and send over the cursor image
1090 this._display.disableLocalCursor();
1091
1092 this._updateConnectionState('connected');
1093 return true;
1094 },
1095
1096 _sendEncodings: function () {
1097 var encs = [];
1098
1099 // In preference order
1100 encs.push(encodings.encodingCopyRect);
1101 // Only supported with full depth support
1102 if (this._fb_depth == 24) {
1103 encs.push(encodings.encodingTight);
1104 encs.push(encodings.encodingHextile);
1105 encs.push(encodings.encodingRRE);
1106 }
1107 encs.push(encodings.encodingRaw);
1108
1109 // Psuedo-encoding settings
1110 encs.push(encodings.pseudoEncodingTightPNG);
1111 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1112 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1113
1114 encs.push(encodings.pseudoEncodingDesktopSize);
1115 encs.push(encodings.pseudoEncodingLastRect);
1116 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1117 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1118 encs.push(encodings.pseudoEncodingXvp);
1119 encs.push(encodings.pseudoEncodingFence);
1120 encs.push(encodings.pseudoEncodingContinuousUpdates);
1121
1122 if (browserSupportsCursorURIs() &&
1123 !isTouchDevice && this._fb_depth == 24) {
1124 encs.push(encodings.pseudoEncodingCursor);
1125 }
1126
1127 RFB.messages.clientEncodings(this._sock, encs);
1128 },
1129
1130 /* RFB protocol initialization states:
1131 * ProtocolVersion
1132 * Security
1133 * Authentication
1134 * SecurityResult
1135 * ClientInitialization - not triggered by server message
1136 * ServerInitialization
1137 */
1138 _init_msg: function () {
1139 switch (this._rfb_init_state) {
1140 case 'ProtocolVersion':
1141 return this._negotiate_protocol_version();
1142
1143 case 'Security':
1144 return this._negotiate_security();
1145
1146 case 'Authentication':
1147 return this._negotiate_authentication();
1148
1149 case 'SecurityResult':
1150 return this._handle_security_result();
1151
1152 case 'ClientInitialisation':
1153 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1154 this._rfb_init_state = 'ServerInitialisation';
1155 return true;
1156
1157 case 'ServerInitialisation':
1158 return this._negotiate_server_init();
1159
1160 default:
1161 return this._fail("Internal error", "Unknown init state: " +
1162 this._rfb_init_state);
1163 }
1164 },
1165
1166 _handle_set_colour_map_msg: function () {
1167 Log.Debug("SetColorMapEntries");
1168
1169 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1170 },
1171
1172 _handle_server_cut_text: function () {
1173 Log.Debug("ServerCutText");
1174
1175 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1176 this._sock.rQskipBytes(3); // Padding
1177 var length = this._sock.rQshift32();
1178 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
1179
1180 var text = this._sock.rQshiftStr(length);
1181
1182 if (this._viewOnly) { return true; }
1183
1184 var event = new CustomEvent("clipboard",
1185 { detail: { text: text } });
1186 this.dispatchEvent(event);
1187
1188 return true;
1189 },
1190
1191 _handle_server_fence_msg: function() {
1192 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1193 this._sock.rQskipBytes(3); // Padding
1194 var flags = this._sock.rQshift32();
1195 var length = this._sock.rQshift8();
1196
1197 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
1198
1199 if (length > 64) {
1200 Log.Warn("Bad payload length (" + length + ") in fence response");
1201 length = 64;
1202 }
1203
1204 var payload = this._sock.rQshiftStr(length);
1205
1206 this._supportsFence = true;
1207
1208 /*
1209 * Fence flags
1210 *
1211 * (1<<0) - BlockBefore
1212 * (1<<1) - BlockAfter
1213 * (1<<2) - SyncNext
1214 * (1<<31) - Request
1215 */
1216
1217 if (!(flags & (1<<31))) {
1218 return this._fail("Internal error",
1219 "Unexpected fence response");
1220 }
1221
1222 // Filter out unsupported flags
1223 // FIXME: support syncNext
1224 flags &= (1<<0) | (1<<1);
1225
1226 // BlockBefore and BlockAfter are automatically handled by
1227 // the fact that we process each incoming message
1228 // synchronuosly.
1229 RFB.messages.clientFence(this._sock, flags, payload);
1230
1231 return true;
1232 },
1233
1234 _handle_xvp_msg: function () {
1235 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
1236 this._sock.rQskip8(); // Padding
1237 var xvp_ver = this._sock.rQshift8();
1238 var xvp_msg = this._sock.rQshift8();
1239
1240 switch (xvp_msg) {
1241 case 0: // XVP_FAIL
1242 Log.Error("XVP Operation Failed");
1243 break;
1244 case 1: // XVP_INIT
1245 this._rfb_xvp_ver = xvp_ver;
1246 Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
1247 this._setCapability("power", true);
1248 break;
1249 default:
1250 this._fail("Unexpected server message",
1251 "Illegal server XVP message " + xvp_msg);
1252 break;
1253 }
1254
1255 return true;
1256 },
1257
1258 _normal_msg: function () {
1259 var msg_type;
1260
1261 if (this._FBU.rects > 0) {
1262 msg_type = 0;
1263 } else {
1264 msg_type = this._sock.rQshift8();
1265 }
1266
1267 switch (msg_type) {
1268 case 0: // FramebufferUpdate
1269 var ret = this._framebufferUpdate();
1270 if (ret && !this._enabledContinuousUpdates) {
1271 RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
1272 this._fb_width, this._fb_height);
1273 }
1274 return ret;
1275
1276 case 1: // SetColorMapEntries
1277 return this._handle_set_colour_map_msg();
1278
1279 case 2: // Bell
1280 Log.Debug("Bell");
1281 var event = new CustomEvent("bell", { detail: {} });
1282 this.dispatchEvent(event);
1283 return true;
1284
1285 case 3: // ServerCutText
1286 return this._handle_server_cut_text();
1287
1288 case 150: // EndOfContinuousUpdates
1289 var first = !(this._supportsContinuousUpdates);
1290 this._supportsContinuousUpdates = true;
1291 this._enabledContinuousUpdates = false;
1292 if (first) {
1293 this._enabledContinuousUpdates = true;
1294 this._updateContinuousUpdates();
1295 Log.Info("Enabling continuous updates.");
1296 } else {
1297 // FIXME: We need to send a framebufferupdaterequest here
1298 // if we add support for turning off continuous updates
1299 }
1300 return true;
1301
1302 case 248: // ServerFence
1303 return this._handle_server_fence_msg();
1304
1305 case 250: // XVP
1306 return this._handle_xvp_msg();
1307
1308 default:
1309 this._fail("Unexpected server message", "Type:" + msg_type);
1310 Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1311 return true;
1312 }
1313 },
1314
1315 _onFlush: function() {
1316 this._flushing = false;
1317 // Resume processing
1318 if (this._sock.rQlen() > 0) {
1319 this._handle_message();
1320 }
1321 },
1322
1323 _framebufferUpdate: function () {
1324 var ret = true;
1325 var now;
1326
1327 if (this._FBU.rects === 0) {
1328 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
1329 this._sock.rQskip8(); // Padding
1330 this._FBU.rects = this._sock.rQshift16();
1331 this._FBU.bytes = 0;
1332 this._timing.cur_fbu = 0;
1333 if (this._timing.fbu_rt_start > 0) {
1334 now = (new Date()).getTime();
1335 Log.Info("First FBU latency: " + (now - this._timing.fbu_rt_start));
1336 }
1337
1338 // Make sure the previous frame is fully rendered first
1339 // to avoid building up an excessive queue
1340 if (this._display.pending()) {
1341 this._flushing = true;
1342 this._display.flush();
1343 return false;
1344 }
1345 }
1346
1347 while (this._FBU.rects > 0) {
1348 if (this._rfb_connection_state !== 'connected') { return false; }
1349
1350 if (this._sock.rQwait("FBU", this._FBU.bytes)) { return false; }
1351 if (this._FBU.bytes === 0) {
1352 if (this._sock.rQwait("rect header", 12)) { return false; }
1353 /* New FramebufferUpdate */
1354
1355 var hdr = this._sock.rQshiftBytes(12);
1356 this._FBU.x = (hdr[0] << 8) + hdr[1];
1357 this._FBU.y = (hdr[2] << 8) + hdr[3];
1358 this._FBU.width = (hdr[4] << 8) + hdr[5];
1359 this._FBU.height = (hdr[6] << 8) + hdr[7];
1360 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1361 (hdr[10] << 8) + hdr[11], 10);
1362
1363 if (!this._encHandlers[this._FBU.encoding]) {
1364 this._fail("Unexpected server message",
1365 "Unsupported encoding " +
1366 this._FBU.encoding);
1367 return false;
1368 }
1369 }
1370
1371 this._timing.last_fbu = (new Date()).getTime();
1372
1373 ret = this._encHandlers[this._FBU.encoding]();
1374
1375 now = (new Date()).getTime();
1376 this._timing.cur_fbu += (now - this._timing.last_fbu);
1377
1378 if (ret) {
1379 if (!(this._FBU.encoding in this._encStats)) {
1380 this._encStats[this._FBU.encoding] = [0, 0];
1381 }
1382 this._encStats[this._FBU.encoding][0]++;
1383 this._encStats[this._FBU.encoding][1]++;
1384 this._timing.pixels += this._FBU.width * this._FBU.height;
1385 }
1386
1387 if (this._timing.pixels >= (this._fb_width * this._fb_height)) {
1388 if ((this._FBU.width === this._fb_width && this._FBU.height === this._fb_height) ||
1389 this._timing.fbu_rt_start > 0) {
1390 this._timing.full_fbu_total += this._timing.cur_fbu;
1391 this._timing.full_fbu_cnt++;
1392 Log.Info("Timing of full FBU, curr: " +
1393 this._timing.cur_fbu + ", total: " +
1394 this._timing.full_fbu_total + ", cnt: " +
1395 this._timing.full_fbu_cnt + ", avg: " +
1396 (this._timing.full_fbu_total / this._timing.full_fbu_cnt));
1397 }
1398
1399 if (this._timing.fbu_rt_start > 0) {
1400 var fbu_rt_diff = now - this._timing.fbu_rt_start;
1401 this._timing.fbu_rt_total += fbu_rt_diff;
1402 this._timing.fbu_rt_cnt++;
1403 Log.Info("full FBU round-trip, cur: " +
1404 fbu_rt_diff + ", total: " +
1405 this._timing.fbu_rt_total + ", cnt: " +
1406 this._timing.fbu_rt_cnt + ", avg: " +
1407 (this._timing.fbu_rt_total / this._timing.fbu_rt_cnt));
1408 this._timing.fbu_rt_start = 0;
1409 }
1410 }
1411
1412 if (!ret) { return ret; } // need more data
1413 }
1414
1415 this._display.flip();
1416
1417 return true; // We finished this FBU
1418 },
1419
1420 _updateContinuousUpdates: function() {
1421 if (!this._enabledContinuousUpdates) { return; }
1422
1423 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1424 this._fb_width, this._fb_height);
1425 },
1426
1427 _resize: function(width, height) {
1428 this._fb_width = width;
1429 this._fb_height = height;
1430
1431 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
1432
1433 this._display.resize(this._fb_width, this._fb_height);
1434
1435 var event = new CustomEvent("fbresize",
1436 { detail: { width: this._fb_width,
1437 height: this._fb_height } });
1438 this.dispatchEvent(event);
1439
1440 this._timing.fbu_rt_start = (new Date()).getTime();
1441 this._updateContinuousUpdates();
1442 },
1443
1444 _xvpOp: function (ver, op) {
1445 if (this._rfb_xvp_ver < ver) { return; }
1446 Log.Info("Sending XVP operation " + op + " (version " + ver + ")");
1447 RFB.messages.xvpOp(this._sock, ver, op);
1448 },
1449 };
1450
1451 Object.assign(RFB.prototype, EventTargetMixin);
1452
1453 // Class Methods
1454 RFB.messages = {
1455 keyEvent: function (sock, keysym, down) {
1456 var buff = sock._sQ;
1457 var offset = sock._sQlen;
1458
1459 buff[offset] = 4; // msg-type
1460 buff[offset + 1] = down;
1461
1462 buff[offset + 2] = 0;
1463 buff[offset + 3] = 0;
1464
1465 buff[offset + 4] = (keysym >> 24);
1466 buff[offset + 5] = (keysym >> 16);
1467 buff[offset + 6] = (keysym >> 8);
1468 buff[offset + 7] = keysym;
1469
1470 sock._sQlen += 8;
1471 sock.flush();
1472 },
1473
1474 QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) {
1475 function getRFBkeycode(xt_scancode) {
1476 var upperByte = (keycode >> 8);
1477 var lowerByte = (keycode & 0x00ff);
1478 if (upperByte === 0xe0 && lowerByte < 0x7f) {
1479 lowerByte = lowerByte | 0x80;
1480 return lowerByte;
1481 }
1482 return xt_scancode;
1483 }
1484
1485 var buff = sock._sQ;
1486 var offset = sock._sQlen;
1487
1488 buff[offset] = 255; // msg-type
1489 buff[offset + 1] = 0; // sub msg-type
1490
1491 buff[offset + 2] = (down >> 8);
1492 buff[offset + 3] = down;
1493
1494 buff[offset + 4] = (keysym >> 24);
1495 buff[offset + 5] = (keysym >> 16);
1496 buff[offset + 6] = (keysym >> 8);
1497 buff[offset + 7] = keysym;
1498
1499 var RFBkeycode = getRFBkeycode(keycode);
1500
1501 buff[offset + 8] = (RFBkeycode >> 24);
1502 buff[offset + 9] = (RFBkeycode >> 16);
1503 buff[offset + 10] = (RFBkeycode >> 8);
1504 buff[offset + 11] = RFBkeycode;
1505
1506 sock._sQlen += 12;
1507 sock.flush();
1508 },
1509
1510 pointerEvent: function (sock, x, y, mask) {
1511 var buff = sock._sQ;
1512 var offset = sock._sQlen;
1513
1514 buff[offset] = 5; // msg-type
1515
1516 buff[offset + 1] = mask;
1517
1518 buff[offset + 2] = x >> 8;
1519 buff[offset + 3] = x;
1520
1521 buff[offset + 4] = y >> 8;
1522 buff[offset + 5] = y;
1523
1524 sock._sQlen += 6;
1525 sock.flush();
1526 },
1527
1528 // TODO(directxman12): make this unicode compatible?
1529 clientCutText: function (sock, text) {
1530 var buff = sock._sQ;
1531 var offset = sock._sQlen;
1532
1533 buff[offset] = 6; // msg-type
1534
1535 buff[offset + 1] = 0; // padding
1536 buff[offset + 2] = 0; // padding
1537 buff[offset + 3] = 0; // padding
1538
1539 var n = text.length;
1540
1541 buff[offset + 4] = n >> 24;
1542 buff[offset + 5] = n >> 16;
1543 buff[offset + 6] = n >> 8;
1544 buff[offset + 7] = n;
1545
1546 for (var i = 0; i < n; i++) {
1547 buff[offset + 8 + i] = text.charCodeAt(i);
1548 }
1549
1550 sock._sQlen += 8 + n;
1551 sock.flush();
1552 },
1553
1554 setDesktopSize: function (sock, width, height, id, flags) {
1555 var buff = sock._sQ;
1556 var offset = sock._sQlen;
1557
1558 buff[offset] = 251; // msg-type
1559 buff[offset + 1] = 0; // padding
1560 buff[offset + 2] = width >> 8; // width
1561 buff[offset + 3] = width;
1562 buff[offset + 4] = height >> 8; // height
1563 buff[offset + 5] = height;
1564
1565 buff[offset + 6] = 1; // number-of-screens
1566 buff[offset + 7] = 0; // padding
1567
1568 // screen array
1569 buff[offset + 8] = id >> 24; // id
1570 buff[offset + 9] = id >> 16;
1571 buff[offset + 10] = id >> 8;
1572 buff[offset + 11] = id;
1573 buff[offset + 12] = 0; // x-position
1574 buff[offset + 13] = 0;
1575 buff[offset + 14] = 0; // y-position
1576 buff[offset + 15] = 0;
1577 buff[offset + 16] = width >> 8; // width
1578 buff[offset + 17] = width;
1579 buff[offset + 18] = height >> 8; // height
1580 buff[offset + 19] = height;
1581 buff[offset + 20] = flags >> 24; // flags
1582 buff[offset + 21] = flags >> 16;
1583 buff[offset + 22] = flags >> 8;
1584 buff[offset + 23] = flags;
1585
1586 sock._sQlen += 24;
1587 sock.flush();
1588 },
1589
1590 clientFence: function (sock, flags, payload) {
1591 var buff = sock._sQ;
1592 var offset = sock._sQlen;
1593
1594 buff[offset] = 248; // msg-type
1595
1596 buff[offset + 1] = 0; // padding
1597 buff[offset + 2] = 0; // padding
1598 buff[offset + 3] = 0; // padding
1599
1600 buff[offset + 4] = flags >> 24; // flags
1601 buff[offset + 5] = flags >> 16;
1602 buff[offset + 6] = flags >> 8;
1603 buff[offset + 7] = flags;
1604
1605 var n = payload.length;
1606
1607 buff[offset + 8] = n; // length
1608
1609 for (var i = 0; i < n; i++) {
1610 buff[offset + 9 + i] = payload.charCodeAt(i);
1611 }
1612
1613 sock._sQlen += 9 + n;
1614 sock.flush();
1615 },
1616
1617 enableContinuousUpdates: function (sock, enable, x, y, width, height) {
1618 var buff = sock._sQ;
1619 var offset = sock._sQlen;
1620
1621 buff[offset] = 150; // msg-type
1622 buff[offset + 1] = enable; // enable-flag
1623
1624 buff[offset + 2] = x >> 8; // x
1625 buff[offset + 3] = x;
1626 buff[offset + 4] = y >> 8; // y
1627 buff[offset + 5] = y;
1628 buff[offset + 6] = width >> 8; // width
1629 buff[offset + 7] = width;
1630 buff[offset + 8] = height >> 8; // height
1631 buff[offset + 9] = height;
1632
1633 sock._sQlen += 10;
1634 sock.flush();
1635 },
1636
1637 pixelFormat: function (sock, depth, true_color) {
1638 var buff = sock._sQ;
1639 var offset = sock._sQlen;
1640
1641 var bpp, bits;
1642
1643 if (depth > 16) {
1644 bpp = 32;
1645 } else if (depth > 8) {
1646 bpp = 16;
1647 } else {
1648 bpp = 8;
1649 }
1650
1651 bits = Math.floor(depth/3);
1652
1653 buff[offset] = 0; // msg-type
1654
1655 buff[offset + 1] = 0; // padding
1656 buff[offset + 2] = 0; // padding
1657 buff[offset + 3] = 0; // padding
1658
1659 buff[offset + 4] = bpp; // bits-per-pixel
1660 buff[offset + 5] = depth; // depth
1661 buff[offset + 6] = 0; // little-endian
1662 buff[offset + 7] = true_color ? 1 : 0; // true-color
1663
1664 buff[offset + 8] = 0; // red-max
1665 buff[offset + 9] = (1 << bits) - 1; // red-max
1666
1667 buff[offset + 10] = 0; // green-max
1668 buff[offset + 11] = (1 << bits) - 1; // green-max
1669
1670 buff[offset + 12] = 0; // blue-max
1671 buff[offset + 13] = (1 << bits) - 1; // blue-max
1672
1673 buff[offset + 14] = bits * 2; // red-shift
1674 buff[offset + 15] = bits * 1; // green-shift
1675 buff[offset + 16] = bits * 0; // blue-shift
1676
1677 buff[offset + 17] = 0; // padding
1678 buff[offset + 18] = 0; // padding
1679 buff[offset + 19] = 0; // padding
1680
1681 sock._sQlen += 20;
1682 sock.flush();
1683 },
1684
1685 clientEncodings: function (sock, encodings) {
1686 var buff = sock._sQ;
1687 var offset = sock._sQlen;
1688
1689 buff[offset] = 2; // msg-type
1690 buff[offset + 1] = 0; // padding
1691
1692 buff[offset + 2] = encodings.length >> 8;
1693 buff[offset + 3] = encodings.length;
1694
1695 var i, j = offset + 4;
1696 for (i = 0; i < encodings.length; i++) {
1697 var enc = encodings[i];
1698 buff[j] = enc >> 24;
1699 buff[j + 1] = enc >> 16;
1700 buff[j + 2] = enc >> 8;
1701 buff[j + 3] = enc;
1702
1703 j += 4;
1704 }
1705
1706 sock._sQlen += j - offset;
1707 sock.flush();
1708 },
1709
1710 fbUpdateRequest: function (sock, incremental, x, y, w, h) {
1711 var buff = sock._sQ;
1712 var offset = sock._sQlen;
1713
1714 if (typeof(x) === "undefined") { x = 0; }
1715 if (typeof(y) === "undefined") { y = 0; }
1716
1717 buff[offset] = 3; // msg-type
1718 buff[offset + 1] = incremental ? 1 : 0;
1719
1720 buff[offset + 2] = (x >> 8) & 0xFF;
1721 buff[offset + 3] = x & 0xFF;
1722
1723 buff[offset + 4] = (y >> 8) & 0xFF;
1724 buff[offset + 5] = y & 0xFF;
1725
1726 buff[offset + 6] = (w >> 8) & 0xFF;
1727 buff[offset + 7] = w & 0xFF;
1728
1729 buff[offset + 8] = (h >> 8) & 0xFF;
1730 buff[offset + 9] = h & 0xFF;
1731
1732 sock._sQlen += 10;
1733 sock.flush();
1734 },
1735
1736 xvpOp: function (sock, ver, op) {
1737 var buff = sock._sQ;
1738 var offset = sock._sQlen;
1739
1740 buff[offset] = 250; // msg-type
1741 buff[offset + 1] = 0; // padding
1742
1743 buff[offset + 2] = ver;
1744 buff[offset + 3] = op;
1745
1746 sock._sQlen += 4;
1747 sock.flush();
1748 },
1749 };
1750
1751 RFB.genDES = function (password, challenge) {
1752 var passwd = [];
1753 for (var i = 0; i < password.length; i++) {
1754 passwd.push(password.charCodeAt(i));
1755 }
1756 return (new DES(passwd)).encrypt(challenge);
1757 };
1758
1759 RFB.encodingHandlers = {
1760 RAW: function () {
1761 if (this._FBU.lines === 0) {
1762 this._FBU.lines = this._FBU.height;
1763 }
1764
1765 var pixelSize = this._fb_depth == 8 ? 1 : 4;
1766 this._FBU.bytes = this._FBU.width * pixelSize; // at least a line
1767 if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; }
1768 var cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines);
1769 var curr_height = Math.min(this._FBU.lines,
1770 Math.floor(this._sock.rQlen() / (this._FBU.width * pixelSize)));
1771 var data = this._sock.get_rQ();
1772 var index = this._sock.get_rQi();
1773 if (this._fb_depth == 8) {
1774 var pixels = this._FBU.width * curr_height
1775 var newdata = new Uint8Array(pixels * 4);
1776 var i;
1777 for (i = 0;i < pixels;i++) {
1778 newdata[i * 4 + 0] = ((data[index + i] >> 0) & 0x3) * 255 / 3;
1779 newdata[i * 4 + 1] = ((data[index + i] >> 2) & 0x3) * 255 / 3;
1780 newdata[i * 4 + 2] = ((data[index + i] >> 4) & 0x3) * 255 / 3;
1781 newdata[i * 4 + 4] = 0;
1782 }
1783 data = newdata;
1784 index = 0;
1785 }
1786 this._display.blitImage(this._FBU.x, cur_y, this._FBU.width,
1787 curr_height, data, index);
1788 this._sock.rQskipBytes(this._FBU.width * curr_height * pixelSize);
1789 this._FBU.lines -= curr_height;
1790
1791 if (this._FBU.lines > 0) {
1792 this._FBU.bytes = this._FBU.width * pixelSize; // At least another line
1793 } else {
1794 this._FBU.rects--;
1795 this._FBU.bytes = 0;
1796 }
1797
1798 return true;
1799 },
1800
1801 COPYRECT: function () {
1802 this._FBU.bytes = 4;
1803 if (this._sock.rQwait("COPYRECT", 4)) { return false; }
1804 this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
1805 this._FBU.x, this._FBU.y, this._FBU.width,
1806 this._FBU.height);
1807
1808 this._FBU.rects--;
1809 this._FBU.bytes = 0;
1810 return true;
1811 },
1812
1813 RRE: function () {
1814 var color;
1815 if (this._FBU.subrects === 0) {
1816 this._FBU.bytes = 4 + 4;
1817 if (this._sock.rQwait("RRE", 4 + 4)) { return false; }
1818 this._FBU.subrects = this._sock.rQshift32();
1819 color = this._sock.rQshiftBytes(4); // Background
1820 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, color);
1821 }
1822
1823 while (this._FBU.subrects > 0 && this._sock.rQlen() >= (4 + 8)) {
1824 color = this._sock.rQshiftBytes(4);
1825 var x = this._sock.rQshift16();
1826 var y = this._sock.rQshift16();
1827 var width = this._sock.rQshift16();
1828 var height = this._sock.rQshift16();
1829 this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color);
1830 this._FBU.subrects--;
1831 }
1832
1833 if (this._FBU.subrects > 0) {
1834 var chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects);
1835 this._FBU.bytes = (4 + 8) * chunk;
1836 } else {
1837 this._FBU.rects--;
1838 this._FBU.bytes = 0;
1839 }
1840
1841 return true;
1842 },
1843
1844 HEXTILE: function () {
1845 var rQ = this._sock.get_rQ();
1846 var rQi = this._sock.get_rQi();
1847
1848 if (this._FBU.tiles === 0) {
1849 this._FBU.tiles_x = Math.ceil(this._FBU.width / 16);
1850 this._FBU.tiles_y = Math.ceil(this._FBU.height / 16);
1851 this._FBU.total_tiles = this._FBU.tiles_x * this._FBU.tiles_y;
1852 this._FBU.tiles = this._FBU.total_tiles;
1853 }
1854
1855 while (this._FBU.tiles > 0) {
1856 this._FBU.bytes = 1;
1857 if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; }
1858 var subencoding = rQ[rQi]; // Peek
1859 if (subencoding > 30) { // Raw
1860 this._fail("Unexpected server message",
1861 "Illegal hextile subencoding: " + subencoding);
1862 return false;
1863 }
1864
1865 var subrects = 0;
1866 var curr_tile = this._FBU.total_tiles - this._FBU.tiles;
1867 var tile_x = curr_tile % this._FBU.tiles_x;
1868 var tile_y = Math.floor(curr_tile / this._FBU.tiles_x);
1869 var x = this._FBU.x + tile_x * 16;
1870 var y = this._FBU.y + tile_y * 16;
1871 var w = Math.min(16, (this._FBU.x + this._FBU.width) - x);
1872 var h = Math.min(16, (this._FBU.y + this._FBU.height) - y);
1873
1874 // Figure out how much we are expecting
1875 if (subencoding & 0x01) { // Raw
1876 this._FBU.bytes += w * h * 4;
1877 } else {
1878 if (subencoding & 0x02) { // Background
1879 this._FBU.bytes += 4;
1880 }
1881 if (subencoding & 0x04) { // Foreground
1882 this._FBU.bytes += 4;
1883 }
1884 if (subencoding & 0x08) { // AnySubrects
1885 this._FBU.bytes++; // Since we aren't shifting it off
1886 if (this._sock.rQwait("hextile subrects header", this._FBU.bytes)) { return false; }
1887 subrects = rQ[rQi + this._FBU.bytes - 1]; // Peek
1888 if (subencoding & 0x10) { // SubrectsColoured
1889 this._FBU.bytes += subrects * (4 + 2);
1890 } else {
1891 this._FBU.bytes += subrects * 2;
1892 }
1893 }
1894 }
1895
1896 if (this._sock.rQwait("hextile", this._FBU.bytes)) { return false; }
1897
1898 // We know the encoding and have a whole tile
1899 this._FBU.subencoding = rQ[rQi];
1900 rQi++;
1901 if (this._FBU.subencoding === 0) {
1902 if (this._FBU.lastsubencoding & 0x01) {
1903 // Weird: ignore blanks are RAW
1904 Log.Debug(" Ignoring blank after RAW");
1905 } else {
1906 this._display.fillRect(x, y, w, h, this._FBU.background);
1907 }
1908 } else if (this._FBU.subencoding & 0x01) { // Raw
1909 this._display.blitImage(x, y, w, h, rQ, rQi);
1910 rQi += this._FBU.bytes - 1;
1911 } else {
1912 if (this._FBU.subencoding & 0x02) { // Background
1913 this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1914 rQi += 4;
1915 }
1916 if (this._FBU.subencoding & 0x04) { // Foreground
1917 this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1918 rQi += 4;
1919 }
1920
1921 this._display.startTile(x, y, w, h, this._FBU.background);
1922 if (this._FBU.subencoding & 0x08) { // AnySubrects
1923 subrects = rQ[rQi];
1924 rQi++;
1925
1926 for (var s = 0; s < subrects; s++) {
1927 var color;
1928 if (this._FBU.subencoding & 0x10) { // SubrectsColoured
1929 color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1930 rQi += 4;
1931 } else {
1932 color = this._FBU.foreground;
1933 }
1934 var xy = rQ[rQi];
1935 rQi++;
1936 var sx = (xy >> 4);
1937 var sy = (xy & 0x0f);
1938
1939 var wh = rQ[rQi];
1940 rQi++;
1941 var sw = (wh >> 4) + 1;
1942 var sh = (wh & 0x0f) + 1;
1943
1944 this._display.subTile(sx, sy, sw, sh, color);
1945 }
1946 }
1947 this._display.finishTile();
1948 }
1949 this._sock.set_rQi(rQi);
1950 this._FBU.lastsubencoding = this._FBU.subencoding;
1951 this._FBU.bytes = 0;
1952 this._FBU.tiles--;
1953 }
1954
1955 if (this._FBU.tiles === 0) {
1956 this._FBU.rects--;
1957 }
1958
1959 return true;
1960 },
1961
1962 TIGHT: function () {
1963 this._FBU.bytes = 1; // compression-control byte
1964 if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; }
1965
1966 var checksum = function (data) {
1967 var sum = 0;
1968 for (var i = 0; i < data.length; i++) {
1969 sum += data[i];
1970 if (sum > 65536) sum -= 65536;
1971 }
1972 return sum;
1973 };
1974
1975 var resetStreams = 0;
1976 var streamId = -1;
1977 var decompress = function (data, expected) {
1978 for (var i = 0; i < 4; i++) {
1979 if ((resetStreams >> i) & 1) {
1980 this._FBU.zlibs[i].reset();
1981 Log.Info("Reset zlib stream " + i);
1982 }
1983 }
1984
1985 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1986 var uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected);
1987 /*if (uncompressed.status !== 0) {
1988 Log.Error("Invalid data in zlib stream");
1989 }*/
1990
1991 //return uncompressed.data;
1992 return uncompressed;
1993 }.bind(this);
1994
1995 var indexedToRGBX2Color = function (data, palette, width, height) {
1996 // Convert indexed (palette based) image data to RGB
1997 // TODO: reduce number of calculations inside loop
1998 var dest = this._destBuff;
1999 var w = Math.floor((width + 7) / 8);
2000 var w1 = Math.floor(width / 8);
2001
2002 /*for (var y = 0; y < height; y++) {
2003 var b, x, dp, sp;
2004 var yoffset = y * width;
2005 var ybitoffset = y * w;
2006 var xoffset, targetbyte;
2007 for (x = 0; x < w1; x++) {
2008 xoffset = yoffset + x * 8;
2009 targetbyte = data[ybitoffset + x];
2010 for (b = 7; b >= 0; b--) {
2011 dp = (xoffset + 7 - b) * 3;
2012 sp = (targetbyte >> b & 1) * 3;
2013 dest[dp] = palette[sp];
2014 dest[dp + 1] = palette[sp + 1];
2015 dest[dp + 2] = palette[sp + 2];
2016 }
2017 }
2018
2019 xoffset = yoffset + x * 8;
2020 targetbyte = data[ybitoffset + x];
2021 for (b = 7; b >= 8 - width % 8; b--) {
2022 dp = (xoffset + 7 - b) * 3;
2023 sp = (targetbyte >> b & 1) * 3;
2024 dest[dp] = palette[sp];
2025 dest[dp + 1] = palette[sp + 1];
2026 dest[dp + 2] = palette[sp + 2];
2027 }
2028 }*/
2029
2030 for (var y = 0; y < height; y++) {
2031 var b, x, dp, sp;
2032 for (x = 0; x < w1; x++) {
2033 for (b = 7; b >= 0; b--) {
2034 dp = (y * width + x * 8 + 7 - b) * 4;
2035 sp = (data[y * w + x] >> b & 1) * 3;
2036 dest[dp] = palette[sp];
2037 dest[dp + 1] = palette[sp + 1];
2038 dest[dp + 2] = palette[sp + 2];
2039 dest[dp + 3] = 255;
2040 }
2041 }
2042
2043 for (b = 7; b >= 8 - width % 8; b--) {
2044 dp = (y * width + x * 8 + 7 - b) * 4;
2045 sp = (data[y * w + x] >> b & 1) * 3;
2046 dest[dp] = palette[sp];
2047 dest[dp + 1] = palette[sp + 1];
2048 dest[dp + 2] = palette[sp + 2];
2049 dest[dp + 3] = 255;
2050 }
2051 }
2052
2053 return dest;
2054 }.bind(this);
2055
2056 var indexedToRGBX = function (data, palette, width, height) {
2057 // Convert indexed (palette based) image data to RGB
2058 var dest = this._destBuff;
2059 var total = width * height * 4;
2060 for (var i = 0, j = 0; i < total; i += 4, j++) {
2061 var sp = data[j] * 3;
2062 dest[i] = palette[sp];
2063 dest[i + 1] = palette[sp + 1];
2064 dest[i + 2] = palette[sp + 2];
2065 dest[i + 3] = 255;
2066 }
2067
2068 return dest;
2069 }.bind(this);
2070
2071 var rQi = this._sock.get_rQi();
2072 var rQ = this._sock.rQwhole();
2073 var cmode, data;
2074 var cl_header, cl_data;
2075
2076 var handlePalette = function () {
2077 var numColors = rQ[rQi + 2] + 1;
2078 var paletteSize = numColors * 3;
2079 this._FBU.bytes += paletteSize;
2080 if (this._sock.rQwait("TIGHT palette " + cmode, this._FBU.bytes)) { return false; }
2081
2082 var bpp = (numColors <= 2) ? 1 : 8;
2083 var rowSize = Math.floor((this._FBU.width * bpp + 7) / 8);
2084 var raw = false;
2085 if (rowSize * this._FBU.height < 12) {
2086 raw = true;
2087 cl_header = 0;
2088 cl_data = rowSize * this._FBU.height;
2089 //clength = [0, rowSize * this._FBU.height];
2090 } else {
2091 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2092 var cl_offset = rQi + 3 + paletteSize;
2093 cl_header = 1;
2094 cl_data = 0;
2095 cl_data += rQ[cl_offset] & 0x7f;
2096 if (rQ[cl_offset] & 0x80) {
2097 cl_header++;
2098 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2099 if (rQ[cl_offset + 1] & 0x80) {
2100 cl_header++;
2101 cl_data += rQ[cl_offset + 2] << 14;
2102 }
2103 }
2104 // end inline getTightCLength
2105 }
2106
2107 this._FBU.bytes += cl_header + cl_data;
2108 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2109
2110 // Shift ctl, filter id, num colors, palette entries, and clength off
2111 this._sock.rQskipBytes(3);
2112 //var palette = this._sock.rQshiftBytes(paletteSize);
2113 this._sock.rQshiftTo(this._paletteBuff, paletteSize);
2114 this._sock.rQskipBytes(cl_header);
2115
2116 if (raw) {
2117 data = this._sock.rQshiftBytes(cl_data);
2118 } else {
2119 data = decompress(this._sock.rQshiftBytes(cl_data), rowSize * this._FBU.height);
2120 }
2121
2122 // Convert indexed (palette based) image data to RGB
2123 var rgbx;
2124 if (numColors == 2) {
2125 rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2126 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2127 } else {
2128 rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2129 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2130 }
2131
2132
2133 return true;
2134 }.bind(this);
2135
2136 var handleCopy = function () {
2137 var raw = false;
2138 var uncompressedSize = this._FBU.width * this._FBU.height * 3;
2139 if (uncompressedSize < 12) {
2140 raw = true;
2141 cl_header = 0;
2142 cl_data = uncompressedSize;
2143 } else {
2144 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2145 var cl_offset = rQi + 1;
2146 cl_header = 1;
2147 cl_data = 0;
2148 cl_data += rQ[cl_offset] & 0x7f;
2149 if (rQ[cl_offset] & 0x80) {
2150 cl_header++;
2151 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2152 if (rQ[cl_offset + 1] & 0x80) {
2153 cl_header++;
2154 cl_data += rQ[cl_offset + 2] << 14;
2155 }
2156 }
2157 // end inline getTightCLength
2158 }
2159 this._FBU.bytes = 1 + cl_header + cl_data;
2160 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2161
2162 // Shift ctl, clength off
2163 this._sock.rQshiftBytes(1 + cl_header);
2164
2165 if (raw) {
2166 data = this._sock.rQshiftBytes(cl_data);
2167 } else {
2168 data = decompress(this._sock.rQshiftBytes(cl_data), uncompressedSize);
2169 }
2170
2171 this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
2172
2173 return true;
2174 }.bind(this);
2175
2176 var ctl = this._sock.rQpeek8();
2177
2178 // Keep tight reset bits
2179 resetStreams = ctl & 0xF;
2180
2181 // Figure out filter
2182 ctl = ctl >> 4;
2183 streamId = ctl & 0x3;
2184
2185 if (ctl === 0x08) cmode = "fill";
2186 else if (ctl === 0x09) cmode = "jpeg";
2187 else if (ctl === 0x0A) cmode = "png";
2188 else if (ctl & 0x04) cmode = "filter";
2189 else if (ctl < 0x04) cmode = "copy";
2190 else return this._fail("Unexpected server message",
2191 "Illegal tight compression received, " +
2192 "ctl: " + ctl);
2193
2194 switch (cmode) {
2195 // fill use depth because TPIXELs drop the padding byte
2196 case "fill": // TPIXEL
2197 this._FBU.bytes += 3;
2198 break;
2199 case "jpeg": // max clength
2200 this._FBU.bytes += 3;
2201 break;
2202 case "png": // max clength
2203 this._FBU.bytes += 3;
2204 break;
2205 case "filter": // filter id + num colors if palette
2206 this._FBU.bytes += 2;
2207 break;
2208 case "copy":
2209 break;
2210 }
2211
2212 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2213
2214 // Determine FBU.bytes
2215 switch (cmode) {
2216 case "fill":
2217 // skip ctl byte
2218 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);
2219 this._sock.rQskipBytes(4);
2220 break;
2221 case "png":
2222 case "jpeg":
2223 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2224 var cl_offset = rQi + 1;
2225 cl_header = 1;
2226 cl_data = 0;
2227 cl_data += rQ[cl_offset] & 0x7f;
2228 if (rQ[cl_offset] & 0x80) {
2229 cl_header++;
2230 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2231 if (rQ[cl_offset + 1] & 0x80) {
2232 cl_header++;
2233 cl_data += rQ[cl_offset + 2] << 14;
2234 }
2235 }
2236 // end inline getTightCLength
2237 this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
2238 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2239
2240 // We have everything, render it
2241 this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
2242 data = this._sock.rQshiftBytes(cl_data);
2243 this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data);
2244 break;
2245 case "filter":
2246 var filterId = rQ[rQi + 1];
2247 if (filterId === 1) {
2248 if (!handlePalette()) { return false; }
2249 } else {
2250 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2251 // Filter 2, Gradient is valid but not use if jpeg is enabled
2252 this._fail("Unexpected server message",
2253 "Unsupported tight subencoding received, " +
2254 "filter: " + filterId);
2255 }
2256 break;
2257 case "copy":
2258 if (!handleCopy()) { return false; }
2259 break;
2260 }
2261
2262
2263 this._FBU.bytes = 0;
2264 this._FBU.rects--;
2265
2266 return true;
2267 },
2268
2269 last_rect: function () {
2270 this._FBU.rects = 0;
2271 return true;
2272 },
2273
2274 ExtendedDesktopSize: function () {
2275 this._FBU.bytes = 1;
2276 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2277
2278 this._supportsSetDesktopSize = true;
2279 this._setCapability("resize", true);
2280
2281 var number_of_screens = this._sock.rQpeek8();
2282
2283 this._FBU.bytes = 4 + (number_of_screens * 16);
2284 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2285
2286 this._sock.rQskipBytes(1); // number-of-screens
2287 this._sock.rQskipBytes(3); // padding
2288
2289 for (var i = 0; i < number_of_screens; i += 1) {
2290 // Save the id and flags of the first screen
2291 if (i === 0) {
2292 this._screen_id = this._sock.rQshiftBytes(4); // id
2293 this._sock.rQskipBytes(2); // x-position
2294 this._sock.rQskipBytes(2); // y-position
2295 this._sock.rQskipBytes(2); // width
2296 this._sock.rQskipBytes(2); // height
2297 this._screen_flags = this._sock.rQshiftBytes(4); // flags
2298 } else {
2299 this._sock.rQskipBytes(16);
2300 }
2301 }
2302
2303 /*
2304 * The x-position indicates the reason for the change:
2305 *
2306 * 0 - server resized on its own
2307 * 1 - this client requested the resize
2308 * 2 - another client requested the resize
2309 */
2310
2311 // We need to handle errors when we requested the resize.
2312 if (this._FBU.x === 1 && this._FBU.y !== 0) {
2313 var msg = "";
2314 // The y-position indicates the status code from the server
2315 switch (this._FBU.y) {
2316 case 1:
2317 msg = "Resize is administratively prohibited";
2318 break;
2319 case 2:
2320 msg = "Out of resources";
2321 break;
2322 case 3:
2323 msg = "Invalid screen layout";
2324 break;
2325 default:
2326 msg = "Unknown reason";
2327 break;
2328 }
2329 Log.Warn("Server did not accept the resize request: "
2330 + msg);
2331 } else {
2332 this._resize(this._FBU.width, this._FBU.height);
2333 }
2334
2335 this._FBU.bytes = 0;
2336 this._FBU.rects -= 1;
2337 return true;
2338 },
2339
2340 DesktopSize: function () {
2341 this._resize(this._FBU.width, this._FBU.height);
2342 this._FBU.bytes = 0;
2343 this._FBU.rects -= 1;
2344 return true;
2345 },
2346
2347 Cursor: function () {
2348 Log.Debug(">> set_cursor");
2349 var x = this._FBU.x; // hotspot-x
2350 var y = this._FBU.y; // hotspot-y
2351 var w = this._FBU.width;
2352 var h = this._FBU.height;
2353
2354 var pixelslength = w * h * 4;
2355 var masklength = Math.floor((w + 7) / 8) * h;
2356
2357 this._FBU.bytes = pixelslength + masklength;
2358 if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
2359
2360 this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
2361 this._sock.rQshiftBytes(masklength),
2362 x, y, w, h);
2363
2364 this._FBU.bytes = 0;
2365 this._FBU.rects--;
2366
2367 Log.Debug("<< set_cursor");
2368 return true;
2369 },
2370
2371 QEMUExtendedKeyEvent: function () {
2372 this._FBU.rects--;
2373
2374 // Old Safari doesn't support creating keyboard events
2375 try {
2376 var keyboardEvent = document.createEvent("keyboardEvent");
2377 if (keyboardEvent.code !== undefined) {
2378 this._qemuExtKeyEventSupported = true;
2379 }
2380 } catch (err) {
2381 }
2382 },
2383 };