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