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