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