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