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