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