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