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