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