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