]> git.proxmox.com Git - mirror_novnc.git/blob - core/rfb.js
b8ff782031375f2f4b935dbff44187a6df1f11db
[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 var _ = Util.Localisation.get;
267
268 RFB.prototype = {
269 // Public methods
270 connect: function (host, port, password, path) {
271 this._rfb_host = host;
272 this._rfb_port = port;
273 this._rfb_password = (password !== undefined) ? password : "";
274 this._rfb_path = (path !== undefined) ? path : "";
275
276 if (!this._rfb_host || !this._rfb_port) {
277 return this._fail(
278 _("Must set host and port"));
279 }
280
281 this._rfb_init_state = '';
282 this._updateConnectionState('connecting');
283 return true;
284 },
285
286 disconnect: function () {
287 this._updateConnectionState('disconnecting');
288 this._sock.off('error');
289 this._sock.off('message');
290 this._sock.off('open');
291 },
292
293 sendPassword: function (passwd) {
294 this._rfb_password = passwd;
295 setTimeout(this._init_msg.bind(this), 0);
296 },
297
298 sendCtrlAltDel: function () {
299 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
300 Util.Info("Sending Ctrl-Alt-Del");
301
302 RFB.messages.keyEvent(this._sock, KeyTable.XK_Control_L, 1);
303 RFB.messages.keyEvent(this._sock, KeyTable.XK_Alt_L, 1);
304 RFB.messages.keyEvent(this._sock, KeyTable.XK_Delete, 1);
305 RFB.messages.keyEvent(this._sock, KeyTable.XK_Delete, 0);
306 RFB.messages.keyEvent(this._sock, KeyTable.XK_Alt_L, 0);
307 RFB.messages.keyEvent(this._sock, KeyTable.XK_Control_L, 0);
308 return true;
309 },
310
311 xvpOp: function (ver, op) {
312 if (this._rfb_xvp_ver < ver) { return false; }
313 Util.Info("Sending XVP operation " + op + " (version " + ver + ")");
314 this._sock.send_string("\xFA\x00" + String.fromCharCode(ver) + String.fromCharCode(op));
315 return true;
316 },
317
318 xvpShutdown: function () {
319 return this.xvpOp(1, 2);
320 },
321
322 xvpReboot: function () {
323 return this.xvpOp(1, 3);
324 },
325
326 xvpReset: function () {
327 return this.xvpOp(1, 4);
328 },
329
330 // Send a key press. If 'down' is not specified then send a down key
331 // followed by an up key.
332 sendKey: function (keysym, down) {
333 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
334 if (typeof down !== 'undefined') {
335 Util.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym);
336 RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0);
337 } else {
338 Util.Info("Sending keysym (down + up): " + keysym);
339 RFB.messages.keyEvent(this._sock, keysym, 1);
340 RFB.messages.keyEvent(this._sock, keysym, 0);
341 }
342 return true;
343 },
344
345 clipboardPasteFrom: function (text) {
346 if (this._rfb_connection_state !== 'connected') { return; }
347 RFB.messages.clientCutText(this._sock, text);
348 },
349
350 // Requests a change of remote desktop size. This message is an extension
351 // and may only be sent if we have received an ExtendedDesktopSize message
352 requestDesktopSize: function (width, height) {
353 if (this._rfb_connection_state !== 'connected' ||
354 this._view_only) {
355 return false;
356 }
357
358 if (this._supportsSetDesktopSize) {
359 RFB.messages.setDesktopSize(this._sock, width, height,
360 this._screen_id, this._screen_flags);
361 this._sock.flush();
362 return true;
363 } else {
364 return false;
365 }
366 },
367
368
369 // Private methods
370
371 _connect: function () {
372 Util.Debug(">> RFB.connect");
373 this._init_vars();
374
375 var uri;
376 if (typeof UsingSocketIO !== 'undefined') {
377 uri = 'http';
378 } else {
379 uri = this._encrypt ? 'wss' : 'ws';
380 }
381
382 uri += '://' + this._rfb_host + ':' + this._rfb_port + '/' + this._rfb_path;
383 Util.Info("connecting to " + uri);
384
385 try {
386 // WebSocket.onopen transitions to the RFB init states
387 this._sock.open(uri, this._wsProtocols);
388 } catch (e) {
389 if (e.name === 'SyntaxError') {
390 this._fail("Invalid host or port value given", e);
391 } else {
392 this._fail("Error while connecting", e);
393 }
394 }
395
396 Util.Debug("<< RFB.connect");
397 },
398
399 _disconnect: function () {
400 Util.Debug(">> RFB.disconnect");
401 this._cleanup();
402 this._sock.close();
403 this._print_stats();
404 Util.Debug("<< RFB.disconnect");
405 },
406
407 _init_vars: function () {
408 // reset state
409 this._FBU.rects = 0;
410 this._FBU.subrects = 0; // RRE and HEXTILE
411 this._FBU.lines = 0; // RAW
412 this._FBU.tiles = 0; // HEXTILE
413 this._FBU.zlibs = []; // TIGHT zlib encoders
414 this._mouse_buttonMask = 0;
415 this._mouse_arr = [];
416 this._rfb_tightvnc = false;
417
418 // Clear the per connection encoding stats
419 var i;
420 for (i = 0; i < this._encodings.length; i++) {
421 this._encStats[this._encodings[i][1]][0] = 0;
422 }
423
424 for (i = 0; i < 4; i++) {
425 this._FBU.zlibs[i] = new Inflator.Inflate();
426 }
427 },
428
429 _print_stats: function () {
430 Util.Info("Encoding stats for this connection:");
431 var i, s;
432 for (i = 0; i < this._encodings.length; i++) {
433 s = this._encStats[this._encodings[i][1]];
434 if (s[0] + s[1] > 0) {
435 Util.Info(" " + this._encodings[i][0] + ": " + s[0] + " rects");
436 }
437 }
438
439 Util.Info("Encoding stats since page load:");
440 for (i = 0; i < this._encodings.length; i++) {
441 s = this._encStats[this._encodings[i][1]];
442 Util.Info(" " + this._encodings[i][0] + ": " + s[1] + " rects");
443 }
444 },
445
446 _cleanup: function () {
447 if (!this._view_only) { this._keyboard.ungrab(); }
448 if (!this._view_only) { this._mouse.ungrab(); }
449 this._display.defaultCursor();
450 if (Util.get_logging() !== 'debug') {
451 // Show noVNC logo on load and when disconnected, unless in
452 // debug mode
453 this._display.clear();
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 var types = this._sock.rQshiftBytes(num_types);
796 Util.Debug("Server security types: " + types);
797
798 // Look for each auth in preferred order
799 this._rfb_auth_scheme = 0;
800 if (types.indexOf(1) !== -1) {
801 this._rfb_auth_scheme = 1; // None
802 } else if (types.indexOf(22) !== -1) {
803 this._rfb_auth_scheme = 22; // XVP
804 } else if (types.indexOf(16) !== -1) {
805 this._rfb_auth_scheme = 16; // Tight
806 } else if (types.indexOf(2) !== -1) {
807 this._rfb_auth_scheme = 2; // VNC Auth
808 } else {
809 return this._fail("Unsupported server",
810 "Unsupported security types: " + types);
811 }
812
813 this._sock.send([this._rfb_auth_scheme]);
814 } else {
815 // Server decides
816 if (this._sock.rQwait("security scheme", 4)) { return false; }
817 this._rfb_auth_scheme = this._sock.rQshift32();
818 }
819
820 this._rfb_init_state = 'Authentication';
821 Util.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme);
822
823 return this._init_msg(); // jump to authentication
824 },
825
826 // authentication
827 _negotiate_xvp_auth: function () {
828 var xvp_sep = this._xvp_password_sep;
829 var xvp_auth = this._rfb_password.split(xvp_sep);
830 if (xvp_auth.length < 3) {
831 var msg = 'XVP credentials required (user' + xvp_sep +
832 'target' + xvp_sep + 'password) -- got only ' + this._rfb_password;
833 this._onPasswordRequired(this, msg);
834 return false;
835 }
836
837 var xvp_auth_str = String.fromCharCode(xvp_auth[0].length) +
838 String.fromCharCode(xvp_auth[1].length) +
839 xvp_auth[0] +
840 xvp_auth[1];
841 this._sock.send_string(xvp_auth_str);
842 this._rfb_password = xvp_auth.slice(2).join(xvp_sep);
843 this._rfb_auth_scheme = 2;
844 return this._negotiate_authentication();
845 },
846
847 _negotiate_std_vnc_auth: function () {
848 if (this._rfb_password.length === 0) {
849 this._onPasswordRequired(this);
850 return false;
851 }
852
853 if (this._sock.rQwait("auth challenge", 16)) { return false; }
854
855 // TODO(directxman12): make genDES not require an Array
856 var challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
857 var response = RFB.genDES(this._rfb_password, challenge);
858 this._sock.send(response);
859 this._rfb_init_state = "SecurityResult";
860 return true;
861 },
862
863 _negotiate_tight_tunnels: function (numTunnels) {
864 var clientSupportedTunnelTypes = {
865 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
866 };
867 var serverSupportedTunnelTypes = {};
868 // receive tunnel capabilities
869 for (var i = 0; i < numTunnels; i++) {
870 var cap_code = this._sock.rQshift32();
871 var cap_vendor = this._sock.rQshiftStr(4);
872 var cap_signature = this._sock.rQshiftStr(8);
873 serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature };
874 }
875
876 // choose the notunnel type
877 if (serverSupportedTunnelTypes[0]) {
878 if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
879 serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
880 return this._fail("Unsupported server",
881 "Client's tunnel type had the incorrect " +
882 "vendor or signature");
883 }
884 this._sock.send([0, 0, 0, 0]); // use NOTUNNEL
885 return false; // wait until we receive the sub auth count to continue
886 } else {
887 return this._fail("Unsupported server",
888 "Server wanted tunnels, but doesn't support " +
889 "the notunnel type");
890 }
891 },
892
893 _negotiate_tight_auth: function () {
894 if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation
895 if (this._sock.rQwait("num tunnels", 4)) { return false; }
896 var numTunnels = this._sock.rQshift32();
897 if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
898
899 this._rfb_tightvnc = true;
900
901 if (numTunnels > 0) {
902 this._negotiate_tight_tunnels(numTunnels);
903 return false; // wait until we receive the sub auth to continue
904 }
905 }
906
907 // second pass, do the sub-auth negotiation
908 if (this._sock.rQwait("sub auth count", 4)) { return false; }
909 var subAuthCount = this._sock.rQshift32();
910 if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
911 this._rfb_init_state = 'SecurityResult';
912 return true;
913 }
914
915 if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
916
917 var clientSupportedTypes = {
918 'STDVNOAUTH__': 1,
919 'STDVVNCAUTH_': 2
920 };
921
922 var serverSupportedTypes = [];
923
924 for (var i = 0; i < subAuthCount; i++) {
925 var capNum = this._sock.rQshift32();
926 var capabilities = this._sock.rQshiftStr(12);
927 serverSupportedTypes.push(capabilities);
928 }
929
930 for (var authType in clientSupportedTypes) {
931 if (serverSupportedTypes.indexOf(authType) != -1) {
932 this._sock.send([0, 0, 0, clientSupportedTypes[authType]]);
933
934 switch (authType) {
935 case 'STDVNOAUTH__': // no auth
936 this._rfb_init_state = 'SecurityResult';
937 return true;
938 case 'STDVVNCAUTH_': // VNC auth
939 this._rfb_auth_scheme = 2;
940 return this._init_msg();
941 default:
942 return this._fail("Unsupported server",
943 "Unsupported tiny auth scheme: " +
944 authType);
945 }
946 }
947 }
948
949 return this._fail("Unsupported server",
950 "No supported sub-auth types!");
951 },
952
953 _negotiate_authentication: function () {
954 switch (this._rfb_auth_scheme) {
955 case 0: // connection failed
956 if (this._sock.rQwait("auth reason", 4)) { return false; }
957 var strlen = this._sock.rQshift32();
958 var reason = this._sock.rQshiftStr(strlen);
959 return this._fail("Authentication failure", reason);
960
961 case 1: // no auth
962 if (this._rfb_version >= 3.8) {
963 this._rfb_init_state = 'SecurityResult';
964 return true;
965 }
966 this._rfb_init_state = 'ClientInitialisation';
967 return this._init_msg();
968
969 case 22: // XVP auth
970 return this._negotiate_xvp_auth();
971
972 case 2: // VNC authentication
973 return this._negotiate_std_vnc_auth();
974
975 case 16: // TightVNC Security Type
976 return this._negotiate_tight_auth();
977
978 default:
979 return this._fail("Unsupported server",
980 "Unsupported auth scheme: " +
981 this._rfb_auth_scheme);
982 }
983 },
984
985 _handle_security_result: function () {
986 if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
987 switch (this._sock.rQshift32()) {
988 case 0: // OK
989 this._rfb_init_state = 'ClientInitialisation';
990 Util.Debug('Authentication OK');
991 return this._init_msg();
992 case 1: // failed
993 if (this._rfb_version >= 3.8) {
994 var length = this._sock.rQshift32();
995 if (this._sock.rQwait("SecurityResult reason", length, 8)) { return false; }
996 var reason = this._sock.rQshiftStr(length);
997 return this._fail("Authentication failure", reason);
998 } else {
999 return this._fail("Authentication failure");
1000 }
1001 return false;
1002 case 2:
1003 return this._fail("Too many authentication attempts");
1004 default:
1005 return this._fail("Unsupported server",
1006 "Unknown SecurityResult");
1007 }
1008 },
1009
1010 _negotiate_server_init: function () {
1011 if (this._sock.rQwait("server initialization", 24)) { return false; }
1012
1013 /* Screen size */
1014 this._fb_width = this._sock.rQshift16();
1015 this._fb_height = this._sock.rQshift16();
1016 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
1017
1018 /* PIXEL_FORMAT */
1019 var bpp = this._sock.rQshift8();
1020 var depth = this._sock.rQshift8();
1021 var big_endian = this._sock.rQshift8();
1022 var true_color = this._sock.rQshift8();
1023
1024 var red_max = this._sock.rQshift16();
1025 var green_max = this._sock.rQshift16();
1026 var blue_max = this._sock.rQshift16();
1027 var red_shift = this._sock.rQshift8();
1028 var green_shift = this._sock.rQshift8();
1029 var blue_shift = this._sock.rQshift8();
1030 this._sock.rQskipBytes(3); // padding
1031
1032 // NB(directxman12): we don't want to call any callbacks or print messages until
1033 // *after* we're past the point where we could backtrack
1034
1035 /* Connection name/title */
1036 var name_length = this._sock.rQshift32();
1037 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1038 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
1039
1040 if (this._rfb_tightvnc) {
1041 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1042 // In TightVNC mode, ServerInit message is extended
1043 var numServerMessages = this._sock.rQshift16();
1044 var numClientMessages = this._sock.rQshift16();
1045 var numEncodings = this._sock.rQshift16();
1046 this._sock.rQskipBytes(2); // padding
1047
1048 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1049 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1050
1051 // we don't actually do anything with the capability information that TIGHT sends,
1052 // so we just skip the all of this.
1053
1054 // TIGHT server message capabilities
1055 this._sock.rQskipBytes(16 * numServerMessages);
1056
1057 // TIGHT client message capabilities
1058 this._sock.rQskipBytes(16 * numClientMessages);
1059
1060 // TIGHT encoding capabilities
1061 this._sock.rQskipBytes(16 * numEncodings);
1062 }
1063
1064 // NB(directxman12): these are down here so that we don't run them multiple times
1065 // if we backtrack
1066 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1067 ", bpp: " + bpp + ", depth: " + depth +
1068 ", big_endian: " + big_endian +
1069 ", true_color: " + true_color +
1070 ", red_max: " + red_max +
1071 ", green_max: " + green_max +
1072 ", blue_max: " + blue_max +
1073 ", red_shift: " + red_shift +
1074 ", green_shift: " + green_shift +
1075 ", blue_shift: " + blue_shift);
1076
1077 if (big_endian !== 0) {
1078 Util.Warn("Server native endian is not little endian");
1079 }
1080
1081 if (red_shift !== 16) {
1082 Util.Warn("Server native red-shift is not 16");
1083 }
1084
1085 if (blue_shift !== 0) {
1086 Util.Warn("Server native blue-shift is not 0");
1087 }
1088
1089 // we're past the point where we could backtrack, so it's safe to call this
1090 this._onDesktopName(this, this._fb_name);
1091
1092 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1093 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1094 this._true_color = false;
1095 }
1096
1097 this._display.set_true_color(this._true_color);
1098 this._display.resize(this._fb_width, this._fb_height);
1099 this._onFBResize(this, this._fb_width, this._fb_height);
1100
1101 if (!this._view_only) { this._keyboard.grab(); }
1102 if (!this._view_only) { this._mouse.grab(); }
1103
1104 if (this._true_color) {
1105 this._fb_Bpp = 4;
1106 this._fb_depth = 3;
1107 } else {
1108 this._fb_Bpp = 1;
1109 this._fb_depth = 1;
1110 }
1111
1112 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1113 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1114 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1115
1116 this._timing.fbu_rt_start = (new Date()).getTime();
1117 this._timing.pixels = 0;
1118
1119 this._updateConnectionState('connected');
1120 return true;
1121 },
1122
1123 /* RFB protocol initialization states:
1124 * ProtocolVersion
1125 * Security
1126 * Authentication
1127 * SecurityResult
1128 * ClientInitialization - not triggered by server message
1129 * ServerInitialization
1130 */
1131 _init_msg: function () {
1132 switch (this._rfb_init_state) {
1133 case 'ProtocolVersion':
1134 return this._negotiate_protocol_version();
1135
1136 case 'Security':
1137 return this._negotiate_security();
1138
1139 case 'Authentication':
1140 return this._negotiate_authentication();
1141
1142 case 'SecurityResult':
1143 return this._handle_security_result();
1144
1145 case 'ClientInitialisation':
1146 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1147 this._rfb_init_state = 'ServerInitialisation';
1148 return true;
1149
1150 case 'ServerInitialisation':
1151 return this._negotiate_server_init();
1152
1153 default:
1154 return this._fail("Internal error", "Unknown init state: " +
1155 this._rfb_init_state);
1156 }
1157 },
1158
1159 _handle_set_colour_map_msg: function () {
1160 Util.Debug("SetColorMapEntries");
1161 this._sock.rQskip8(); // Padding
1162
1163 var first_colour = this._sock.rQshift16();
1164 var num_colours = this._sock.rQshift16();
1165 if (this._sock.rQwait('SetColorMapEntries', num_colours * 6, 6)) { return false; }
1166
1167 for (var c = 0; c < num_colours; c++) {
1168 var red = parseInt(this._sock.rQshift16() / 256, 10);
1169 var green = parseInt(this._sock.rQshift16() / 256, 10);
1170 var blue = parseInt(this._sock.rQshift16() / 256, 10);
1171 this._display.set_colourMap([blue, green, red], first_colour + c);
1172 }
1173 Util.Debug("colourMap: " + this._display.get_colourMap());
1174 Util.Info("Registered " + num_colours + " colourMap entries");
1175
1176 return true;
1177 },
1178
1179 _handle_server_cut_text: function () {
1180 Util.Debug("ServerCutText");
1181 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1182 this._sock.rQskipBytes(3); // Padding
1183 var length = this._sock.rQshift32();
1184 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
1185
1186 var text = this._sock.rQshiftStr(length);
1187 this._onClipboard(this, text);
1188
1189 return true;
1190 },
1191
1192 _handle_server_fence_msg: function() {
1193 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1194 this._sock.rQskipBytes(3); // Padding
1195 var flags = this._sock.rQshift32();
1196 var length = this._sock.rQshift8();
1197
1198 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
1199
1200 if (length > 64) {
1201 Util.Warn("Bad payload length (" + length + ") in fence response");
1202 length = 64;
1203 }
1204
1205 var payload = this._sock.rQshiftStr(length);
1206
1207 this._supportsFence = true;
1208
1209 /*
1210 * Fence flags
1211 *
1212 * (1<<0) - BlockBefore
1213 * (1<<1) - BlockAfter
1214 * (1<<2) - SyncNext
1215 * (1<<31) - Request
1216 */
1217
1218 if (!(flags & (1<<31))) {
1219 return this._fail("Internal error",
1220 "Unexpected fence response");
1221 }
1222
1223 // Filter out unsupported flags
1224 // FIXME: support syncNext
1225 flags &= (1<<0) | (1<<1);
1226
1227 // BlockBefore and BlockAfter are automatically handled by
1228 // the fact that we process each incoming message
1229 // synchronuosly.
1230 RFB.messages.clientFence(this._sock, flags, payload);
1231
1232 return true;
1233 },
1234
1235 _handle_xvp_msg: function () {
1236 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
1237 this._sock.rQskip8(); // Padding
1238 var xvp_ver = this._sock.rQshift8();
1239 var xvp_msg = this._sock.rQshift8();
1240
1241 switch (xvp_msg) {
1242 case 0: // XVP_FAIL
1243 Util.Error("Operation Failed");
1244 this._notification("XVP Operation Failed", 'error');
1245 break;
1246 case 1: // XVP_INIT
1247 this._rfb_xvp_ver = xvp_ver;
1248 Util.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
1249 this._onXvpInit(this._rfb_xvp_ver);
1250 break;
1251 default:
1252 this._fail("Unexpected server message",
1253 "Illegal server XVP message " + xvp_msg);
1254 break;
1255 }
1256
1257 return true;
1258 },
1259
1260 _normal_msg: function () {
1261 var msg_type;
1262
1263 if (this._FBU.rects > 0) {
1264 msg_type = 0;
1265 } else {
1266 msg_type = this._sock.rQshift8();
1267 }
1268
1269 switch (msg_type) {
1270 case 0: // FramebufferUpdate
1271 var ret = this._framebufferUpdate();
1272 if (ret && !this._enabledContinuousUpdates) {
1273 RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
1274 this._fb_width, this._fb_height);
1275 }
1276 return ret;
1277
1278 case 1: // SetColorMapEntries
1279 return this._handle_set_colour_map_msg();
1280
1281 case 2: // Bell
1282 Util.Debug("Bell");
1283 this._onBell(this);
1284 return true;
1285
1286 case 3: // ServerCutText
1287 return this._handle_server_cut_text();
1288
1289 case 150: // EndOfContinuousUpdates
1290 var first = !(this._supportsContinuousUpdates);
1291 this._supportsContinuousUpdates = true;
1292 this._enabledContinuousUpdates = false;
1293 if (first) {
1294 this._enabledContinuousUpdates = true;
1295 this._updateContinuousUpdates();
1296 Util.Info("Enabling continuous updates.");
1297 } else {
1298 // FIXME: We need to send a framebufferupdaterequest here
1299 // if we add support for turning off continuous updates
1300 }
1301 return true;
1302
1303 case 248: // ServerFence
1304 return this._handle_server_fence_msg();
1305
1306 case 250: // XVP
1307 return this._handle_xvp_msg();
1308
1309 default:
1310 this._fail("Unexpected server message", "Type:" + msg_type);
1311 Util.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1312 return true;
1313 }
1314 },
1315
1316 _onFlush: function() {
1317 this._flushing = false;
1318 // Resume processing
1319 if (this._sock.rQlen() > 0) {
1320 this._handle_message();
1321 }
1322 },
1323
1324 _framebufferUpdate: function () {
1325 var ret = true;
1326 var now;
1327
1328 if (this._FBU.rects === 0) {
1329 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
1330 this._sock.rQskip8(); // Padding
1331 this._FBU.rects = this._sock.rQshift16();
1332 this._FBU.bytes = 0;
1333 this._timing.cur_fbu = 0;
1334 if (this._timing.fbu_rt_start > 0) {
1335 now = (new Date()).getTime();
1336 Util.Info("First FBU latency: " + (now - this._timing.fbu_rt_start));
1337 }
1338
1339 // Make sure the previous frame is fully rendered first
1340 // to avoid building up an excessive queue
1341 if (this._display.pending()) {
1342 this._flushing = true;
1343 this._display.flush();
1344 return false;
1345 }
1346 }
1347
1348 while (this._FBU.rects > 0) {
1349 if (this._rfb_connection_state !== 'connected') { return false; }
1350
1351 if (this._sock.rQwait("FBU", this._FBU.bytes)) { return false; }
1352 if (this._FBU.bytes === 0) {
1353 if (this._sock.rQwait("rect header", 12)) { return false; }
1354 /* New FramebufferUpdate */
1355
1356 var hdr = this._sock.rQshiftBytes(12);
1357 this._FBU.x = (hdr[0] << 8) + hdr[1];
1358 this._FBU.y = (hdr[2] << 8) + hdr[3];
1359 this._FBU.width = (hdr[4] << 8) + hdr[5];
1360 this._FBU.height = (hdr[6] << 8) + hdr[7];
1361 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1362 (hdr[10] << 8) + hdr[11], 10);
1363
1364 this._onFBUReceive(this,
1365 {'x': this._FBU.x, 'y': this._FBU.y,
1366 'width': this._FBU.width, 'height': this._FBU.height,
1367 'encoding': this._FBU.encoding,
1368 'encodingName': this._encNames[this._FBU.encoding]});
1369
1370 if (!this._encNames[this._FBU.encoding]) {
1371 this._fail("Unexpected server message",
1372 "Unsupported encoding " +
1373 this._FBU.encoding);
1374 return false;
1375 }
1376 }
1377
1378 this._timing.last_fbu = (new Date()).getTime();
1379
1380 ret = this._encHandlers[this._FBU.encoding]();
1381
1382 now = (new Date()).getTime();
1383 this._timing.cur_fbu += (now - this._timing.last_fbu);
1384
1385 if (ret) {
1386 this._encStats[this._FBU.encoding][0]++;
1387 this._encStats[this._FBU.encoding][1]++;
1388 this._timing.pixels += this._FBU.width * this._FBU.height;
1389 }
1390
1391 if (this._timing.pixels >= (this._fb_width * this._fb_height)) {
1392 if ((this._FBU.width === this._fb_width && this._FBU.height === this._fb_height) ||
1393 this._timing.fbu_rt_start > 0) {
1394 this._timing.full_fbu_total += this._timing.cur_fbu;
1395 this._timing.full_fbu_cnt++;
1396 Util.Info("Timing of full FBU, curr: " +
1397 this._timing.cur_fbu + ", total: " +
1398 this._timing.full_fbu_total + ", cnt: " +
1399 this._timing.full_fbu_cnt + ", avg: " +
1400 (this._timing.full_fbu_total / this._timing.full_fbu_cnt));
1401 }
1402
1403 if (this._timing.fbu_rt_start > 0) {
1404 var fbu_rt_diff = now - this._timing.fbu_rt_start;
1405 this._timing.fbu_rt_total += fbu_rt_diff;
1406 this._timing.fbu_rt_cnt++;
1407 Util.Info("full FBU round-trip, cur: " +
1408 fbu_rt_diff + ", total: " +
1409 this._timing.fbu_rt_total + ", cnt: " +
1410 this._timing.fbu_rt_cnt + ", avg: " +
1411 (this._timing.fbu_rt_total / this._timing.fbu_rt_cnt));
1412 this._timing.fbu_rt_start = 0;
1413 }
1414 }
1415
1416 if (!ret) { return ret; } // need more data
1417 }
1418
1419 this._display.flip();
1420
1421 this._onFBUComplete(this,
1422 {'x': this._FBU.x, 'y': this._FBU.y,
1423 'width': this._FBU.width, 'height': this._FBU.height,
1424 'encoding': this._FBU.encoding,
1425 'encodingName': this._encNames[this._FBU.encoding]});
1426
1427 return true; // We finished this FBU
1428 },
1429
1430 _updateContinuousUpdates: function() {
1431 if (!this._enabledContinuousUpdates) { return; }
1432
1433 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1434 this._fb_width, this._fb_height);
1435 }
1436 };
1437
1438 Util.make_properties(RFB, [
1439 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1440 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1441 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1442 ['true_color', 'rw', 'bool'], // Request true color pixel data
1443 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1444 ['shared', 'rw', 'bool'], // Request shared mode
1445 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1446 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1447 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1448 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1449 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1450 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1451
1452 // Callback functions
1453 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1454 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1455 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1456 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1457 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1458 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1459 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1460 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1461 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1462 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1463 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1464 ]);
1465
1466 RFB.prototype.set_local_cursor = function (cursor) {
1467 if (!cursor || (cursor in {'0': 1, 'no': 1, 'false': 1})) {
1468 this._local_cursor = false;
1469 this._display.disableLocalCursor(); //Only show server-side cursor
1470 } else {
1471 if (this._display.get_cursor_uri()) {
1472 this._local_cursor = true;
1473 } else {
1474 Util.Warn("Browser does not support local cursor");
1475 this._display.disableLocalCursor();
1476 }
1477 }
1478 };
1479
1480 RFB.prototype.get_display = function () { return this._display; };
1481 RFB.prototype.get_keyboard = function () { return this._keyboard; };
1482 RFB.prototype.get_mouse = function () { return this._mouse; };
1483
1484 // Class Methods
1485 RFB.messages = {
1486 keyEvent: function (sock, keysym, down) {
1487 var buff = sock._sQ;
1488 var offset = sock._sQlen;
1489
1490 buff[offset] = 4; // msg-type
1491 buff[offset + 1] = down;
1492
1493 buff[offset + 2] = 0;
1494 buff[offset + 3] = 0;
1495
1496 buff[offset + 4] = (keysym >> 24);
1497 buff[offset + 5] = (keysym >> 16);
1498 buff[offset + 6] = (keysym >> 8);
1499 buff[offset + 7] = keysym;
1500
1501 sock._sQlen += 8;
1502 sock.flush();
1503 },
1504
1505 QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) {
1506 function getRFBkeycode(xt_scancode) {
1507 var upperByte = (keycode >> 8);
1508 var lowerByte = (keycode & 0x00ff);
1509 if (upperByte === 0xe0 && lowerByte < 0x7f) {
1510 lowerByte = lowerByte | 0x80;
1511 return lowerByte;
1512 }
1513 return xt_scancode;
1514 }
1515
1516 var buff = sock._sQ;
1517 var offset = sock._sQlen;
1518
1519 buff[offset] = 255; // msg-type
1520 buff[offset + 1] = 0; // sub msg-type
1521
1522 buff[offset + 2] = (down >> 8);
1523 buff[offset + 3] = down;
1524
1525 buff[offset + 4] = (keysym >> 24);
1526 buff[offset + 5] = (keysym >> 16);
1527 buff[offset + 6] = (keysym >> 8);
1528 buff[offset + 7] = keysym;
1529
1530 var RFBkeycode = getRFBkeycode(keycode);
1531
1532 buff[offset + 8] = (RFBkeycode >> 24);
1533 buff[offset + 9] = (RFBkeycode >> 16);
1534 buff[offset + 10] = (RFBkeycode >> 8);
1535 buff[offset + 11] = RFBkeycode;
1536
1537 sock._sQlen += 12;
1538 sock.flush();
1539 },
1540
1541 pointerEvent: function (sock, x, y, mask) {
1542 var buff = sock._sQ;
1543 var offset = sock._sQlen;
1544
1545 buff[offset] = 5; // msg-type
1546
1547 buff[offset + 1] = mask;
1548
1549 buff[offset + 2] = x >> 8;
1550 buff[offset + 3] = x;
1551
1552 buff[offset + 4] = y >> 8;
1553 buff[offset + 5] = y;
1554
1555 sock._sQlen += 6;
1556 sock.flush();
1557 },
1558
1559 // TODO(directxman12): make this unicode compatible?
1560 clientCutText: function (sock, text) {
1561 var buff = sock._sQ;
1562 var offset = sock._sQlen;
1563
1564 buff[offset] = 6; // msg-type
1565
1566 buff[offset + 1] = 0; // padding
1567 buff[offset + 2] = 0; // padding
1568 buff[offset + 3] = 0; // padding
1569
1570 var n = text.length;
1571
1572 buff[offset + 4] = n >> 24;
1573 buff[offset + 5] = n >> 16;
1574 buff[offset + 6] = n >> 8;
1575 buff[offset + 7] = n;
1576
1577 for (var i = 0; i < n; i++) {
1578 buff[offset + 8 + i] = text.charCodeAt(i);
1579 }
1580
1581 sock._sQlen += 8 + n;
1582 sock.flush();
1583 },
1584
1585 setDesktopSize: function (sock, width, height, id, flags) {
1586 var buff = sock._sQ;
1587 var offset = sock._sQlen;
1588
1589 buff[offset] = 251; // msg-type
1590 buff[offset + 1] = 0; // padding
1591 buff[offset + 2] = width >> 8; // width
1592 buff[offset + 3] = width;
1593 buff[offset + 4] = height >> 8; // height
1594 buff[offset + 5] = height;
1595
1596 buff[offset + 6] = 1; // number-of-screens
1597 buff[offset + 7] = 0; // padding
1598
1599 // screen array
1600 buff[offset + 8] = id >> 24; // id
1601 buff[offset + 9] = id >> 16;
1602 buff[offset + 10] = id >> 8;
1603 buff[offset + 11] = id;
1604 buff[offset + 12] = 0; // x-position
1605 buff[offset + 13] = 0;
1606 buff[offset + 14] = 0; // y-position
1607 buff[offset + 15] = 0;
1608 buff[offset + 16] = width >> 8; // width
1609 buff[offset + 17] = width;
1610 buff[offset + 18] = height >> 8; // height
1611 buff[offset + 19] = height;
1612 buff[offset + 20] = flags >> 24; // flags
1613 buff[offset + 21] = flags >> 16;
1614 buff[offset + 22] = flags >> 8;
1615 buff[offset + 23] = flags;
1616
1617 sock._sQlen += 24;
1618 sock.flush();
1619 },
1620
1621 clientFence: function (sock, flags, payload) {
1622 var buff = sock._sQ;
1623 var offset = sock._sQlen;
1624
1625 buff[offset] = 248; // msg-type
1626
1627 buff[offset + 1] = 0; // padding
1628 buff[offset + 2] = 0; // padding
1629 buff[offset + 3] = 0; // padding
1630
1631 buff[offset + 4] = flags >> 24; // flags
1632 buff[offset + 5] = flags >> 16;
1633 buff[offset + 6] = flags >> 8;
1634 buff[offset + 7] = flags;
1635
1636 var n = payload.length;
1637
1638 buff[offset + 8] = n; // length
1639
1640 for (var i = 0; i < n; i++) {
1641 buff[offset + 9 + i] = payload.charCodeAt(i);
1642 }
1643
1644 sock._sQlen += 9 + n;
1645 sock.flush();
1646 },
1647
1648 enableContinuousUpdates: function (sock, enable, x, y, width, height) {
1649 var buff = sock._sQ;
1650 var offset = sock._sQlen;
1651
1652 buff[offset] = 150; // msg-type
1653 buff[offset + 1] = enable; // enable-flag
1654
1655 buff[offset + 2] = x >> 8; // x
1656 buff[offset + 3] = x;
1657 buff[offset + 4] = y >> 8; // y
1658 buff[offset + 5] = y;
1659 buff[offset + 6] = width >> 8; // width
1660 buff[offset + 7] = width;
1661 buff[offset + 8] = height >> 8; // height
1662 buff[offset + 9] = height;
1663
1664 sock._sQlen += 10;
1665 sock.flush();
1666 },
1667
1668 pixelFormat: function (sock, bpp, depth, true_color) {
1669 var buff = sock._sQ;
1670 var offset = sock._sQlen;
1671
1672 buff[offset] = 0; // msg-type
1673
1674 buff[offset + 1] = 0; // padding
1675 buff[offset + 2] = 0; // padding
1676 buff[offset + 3] = 0; // padding
1677
1678 buff[offset + 4] = bpp * 8; // bits-per-pixel
1679 buff[offset + 5] = depth * 8; // depth
1680 buff[offset + 6] = 0; // little-endian
1681 buff[offset + 7] = true_color ? 1 : 0; // true-color
1682
1683 buff[offset + 8] = 0; // red-max
1684 buff[offset + 9] = 255; // red-max
1685
1686 buff[offset + 10] = 0; // green-max
1687 buff[offset + 11] = 255; // green-max
1688
1689 buff[offset + 12] = 0; // blue-max
1690 buff[offset + 13] = 255; // blue-max
1691
1692 buff[offset + 14] = 16; // red-shift
1693 buff[offset + 15] = 8; // green-shift
1694 buff[offset + 16] = 0; // blue-shift
1695
1696 buff[offset + 17] = 0; // padding
1697 buff[offset + 18] = 0; // padding
1698 buff[offset + 19] = 0; // padding
1699
1700 sock._sQlen += 20;
1701 sock.flush();
1702 },
1703
1704 clientEncodings: function (sock, encodings, local_cursor, true_color) {
1705 var buff = sock._sQ;
1706 var offset = sock._sQlen;
1707
1708 buff[offset] = 2; // msg-type
1709 buff[offset + 1] = 0; // padding
1710
1711 // offset + 2 and offset + 3 are encoding count
1712
1713 var i, j = offset + 4, cnt = 0;
1714 for (i = 0; i < encodings.length; i++) {
1715 if (encodings[i][0] === "Cursor" && !local_cursor) {
1716 Util.Debug("Skipping Cursor pseudo-encoding");
1717 } else if (encodings[i][0] === "TIGHT" && !true_color) {
1718 // TODO: remove this when we have tight+non-true-color
1719 Util.Warn("Skipping tight as it is only supported with true color");
1720 } else {
1721 var enc = encodings[i][1];
1722 buff[j] = enc >> 24;
1723 buff[j + 1] = enc >> 16;
1724 buff[j + 2] = enc >> 8;
1725 buff[j + 3] = enc;
1726
1727 j += 4;
1728 cnt++;
1729 }
1730 }
1731
1732 buff[offset + 2] = cnt >> 8;
1733 buff[offset + 3] = cnt;
1734
1735 sock._sQlen += j - offset;
1736 sock.flush();
1737 },
1738
1739 fbUpdateRequest: function (sock, incremental, x, y, w, h) {
1740 var buff = sock._sQ;
1741 var offset = sock._sQlen;
1742
1743 if (typeof(x) === "undefined") { x = 0; }
1744 if (typeof(y) === "undefined") { y = 0; }
1745
1746 buff[offset] = 3; // msg-type
1747 buff[offset + 1] = incremental ? 1 : 0;
1748
1749 buff[offset + 2] = (x >> 8) & 0xFF;
1750 buff[offset + 3] = x & 0xFF;
1751
1752 buff[offset + 4] = (y >> 8) & 0xFF;
1753 buff[offset + 5] = y & 0xFF;
1754
1755 buff[offset + 6] = (w >> 8) & 0xFF;
1756 buff[offset + 7] = w & 0xFF;
1757
1758 buff[offset + 8] = (h >> 8) & 0xFF;
1759 buff[offset + 9] = h & 0xFF;
1760
1761 sock._sQlen += 10;
1762 sock.flush();
1763 }
1764 };
1765
1766 RFB.genDES = function (password, challenge) {
1767 var passwd = [];
1768 for (var i = 0; i < password.length; i++) {
1769 passwd.push(password.charCodeAt(i));
1770 }
1771 return (new DES(passwd)).encrypt(challenge);
1772 };
1773
1774 RFB.encodingHandlers = {
1775 RAW: function () {
1776 if (this._FBU.lines === 0) {
1777 this._FBU.lines = this._FBU.height;
1778 }
1779
1780 this._FBU.bytes = this._FBU.width * this._fb_Bpp; // at least a line
1781 if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; }
1782 var cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines);
1783 var curr_height = Math.min(this._FBU.lines,
1784 Math.floor(this._sock.rQlen() / (this._FBU.width * this._fb_Bpp)));
1785 this._display.blitImage(this._FBU.x, cur_y, this._FBU.width,
1786 curr_height, this._sock.get_rQ(),
1787 this._sock.get_rQi());
1788 this._sock.rQskipBytes(this._FBU.width * curr_height * this._fb_Bpp);
1789 this._FBU.lines -= curr_height;
1790
1791 if (this._FBU.lines > 0) {
1792 this._FBU.bytes = this._FBU.width * this._fb_Bpp; // At least another line
1793 } else {
1794 this._FBU.rects--;
1795 this._FBU.bytes = 0;
1796 }
1797
1798 return true;
1799 },
1800
1801 COPYRECT: function () {
1802 this._FBU.bytes = 4;
1803 if (this._sock.rQwait("COPYRECT", 4)) { return false; }
1804 this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
1805 this._FBU.x, this._FBU.y, this._FBU.width,
1806 this._FBU.height);
1807
1808 this._FBU.rects--;
1809 this._FBU.bytes = 0;
1810 return true;
1811 },
1812
1813 RRE: function () {
1814 var color;
1815 if (this._FBU.subrects === 0) {
1816 this._FBU.bytes = 4 + this._fb_Bpp;
1817 if (this._sock.rQwait("RRE", 4 + this._fb_Bpp)) { return false; }
1818 this._FBU.subrects = this._sock.rQshift32();
1819 color = this._sock.rQshiftBytes(this._fb_Bpp); // Background
1820 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, color);
1821 }
1822
1823 while (this._FBU.subrects > 0 && this._sock.rQlen() >= (this._fb_Bpp + 8)) {
1824 color = this._sock.rQshiftBytes(this._fb_Bpp);
1825 var x = this._sock.rQshift16();
1826 var y = this._sock.rQshift16();
1827 var width = this._sock.rQshift16();
1828 var height = this._sock.rQshift16();
1829 this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color);
1830 this._FBU.subrects--;
1831 }
1832
1833 if (this._FBU.subrects > 0) {
1834 var chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects);
1835 this._FBU.bytes = (this._fb_Bpp + 8) * chunk;
1836 } else {
1837 this._FBU.rects--;
1838 this._FBU.bytes = 0;
1839 }
1840
1841 return true;
1842 },
1843
1844 HEXTILE: function () {
1845 var rQ = this._sock.get_rQ();
1846 var rQi = this._sock.get_rQi();
1847
1848 if (this._FBU.tiles === 0) {
1849 this._FBU.tiles_x = Math.ceil(this._FBU.width / 16);
1850 this._FBU.tiles_y = Math.ceil(this._FBU.height / 16);
1851 this._FBU.total_tiles = this._FBU.tiles_x * this._FBU.tiles_y;
1852 this._FBU.tiles = this._FBU.total_tiles;
1853 }
1854
1855 while (this._FBU.tiles > 0) {
1856 this._FBU.bytes = 1;
1857 if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; }
1858 var subencoding = rQ[rQi]; // Peek
1859 if (subencoding > 30) { // Raw
1860 this._fail("Unexpected server message",
1861 "Illegal hextile subencoding: " + subencoding);
1862 return false;
1863 }
1864
1865 var subrects = 0;
1866 var curr_tile = this._FBU.total_tiles - this._FBU.tiles;
1867 var tile_x = curr_tile % this._FBU.tiles_x;
1868 var tile_y = Math.floor(curr_tile / this._FBU.tiles_x);
1869 var x = this._FBU.x + tile_x * 16;
1870 var y = this._FBU.y + tile_y * 16;
1871 var w = Math.min(16, (this._FBU.x + this._FBU.width) - x);
1872 var h = Math.min(16, (this._FBU.y + this._FBU.height) - y);
1873
1874 // Figure out how much we are expecting
1875 if (subencoding & 0x01) { // Raw
1876 this._FBU.bytes += w * h * this._fb_Bpp;
1877 } else {
1878 if (subencoding & 0x02) { // Background
1879 this._FBU.bytes += this._fb_Bpp;
1880 }
1881 if (subencoding & 0x04) { // Foreground
1882 this._FBU.bytes += this._fb_Bpp;
1883 }
1884 if (subencoding & 0x08) { // AnySubrects
1885 this._FBU.bytes++; // Since we aren't shifting it off
1886 if (this._sock.rQwait("hextile subrects header", this._FBU.bytes)) { return false; }
1887 subrects = rQ[rQi + this._FBU.bytes - 1]; // Peek
1888 if (subencoding & 0x10) { // SubrectsColoured
1889 this._FBU.bytes += subrects * (this._fb_Bpp + 2);
1890 } else {
1891 this._FBU.bytes += subrects * 2;
1892 }
1893 }
1894 }
1895
1896 if (this._sock.rQwait("hextile", this._FBU.bytes)) { return false; }
1897
1898 // We know the encoding and have a whole tile
1899 this._FBU.subencoding = rQ[rQi];
1900 rQi++;
1901 if (this._FBU.subencoding === 0) {
1902 if (this._FBU.lastsubencoding & 0x01) {
1903 // Weird: ignore blanks are RAW
1904 Util.Debug(" Ignoring blank after RAW");
1905 } else {
1906 this._display.fillRect(x, y, w, h, this._FBU.background);
1907 }
1908 } else if (this._FBU.subencoding & 0x01) { // Raw
1909 this._display.blitImage(x, y, w, h, rQ, rQi);
1910 rQi += this._FBU.bytes - 1;
1911 } else {
1912 if (this._FBU.subencoding & 0x02) { // Background
1913 if (this._fb_Bpp == 1) {
1914 this._FBU.background = rQ[rQi];
1915 } else {
1916 // fb_Bpp is 4
1917 this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1918 }
1919 rQi += this._fb_Bpp;
1920 }
1921 if (this._FBU.subencoding & 0x04) { // Foreground
1922 if (this._fb_Bpp == 1) {
1923 this._FBU.foreground = rQ[rQi];
1924 } else {
1925 // this._fb_Bpp is 4
1926 this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1927 }
1928 rQi += this._fb_Bpp;
1929 }
1930
1931 this._display.startTile(x, y, w, h, this._FBU.background);
1932 if (this._FBU.subencoding & 0x08) { // AnySubrects
1933 subrects = rQ[rQi];
1934 rQi++;
1935
1936 for (var s = 0; s < subrects; s++) {
1937 var color;
1938 if (this._FBU.subencoding & 0x10) { // SubrectsColoured
1939 if (this._fb_Bpp === 1) {
1940 color = rQ[rQi];
1941 } else {
1942 // _fb_Bpp is 4
1943 color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1944 }
1945 rQi += this._fb_Bpp;
1946 } else {
1947 color = this._FBU.foreground;
1948 }
1949 var xy = rQ[rQi];
1950 rQi++;
1951 var sx = (xy >> 4);
1952 var sy = (xy & 0x0f);
1953
1954 var wh = rQ[rQi];
1955 rQi++;
1956 var sw = (wh >> 4) + 1;
1957 var sh = (wh & 0x0f) + 1;
1958
1959 this._display.subTile(sx, sy, sw, sh, color);
1960 }
1961 }
1962 this._display.finishTile();
1963 }
1964 this._sock.set_rQi(rQi);
1965 this._FBU.lastsubencoding = this._FBU.subencoding;
1966 this._FBU.bytes = 0;
1967 this._FBU.tiles--;
1968 }
1969
1970 if (this._FBU.tiles === 0) {
1971 this._FBU.rects--;
1972 }
1973
1974 return true;
1975 },
1976
1977 getTightCLength: function (arr) {
1978 var header = 1, data = 0;
1979 data += arr[0] & 0x7f;
1980 if (arr[0] & 0x80) {
1981 header++;
1982 data += (arr[1] & 0x7f) << 7;
1983 if (arr[1] & 0x80) {
1984 header++;
1985 data += arr[2] << 14;
1986 }
1987 }
1988 return [header, data];
1989 },
1990
1991 display_tight: function (isTightPNG) {
1992 if (this._fb_depth === 1) {
1993 this._fail("Internal error",
1994 "Tight protocol handler only implements " +
1995 "true color mode");
1996 }
1997
1998 this._FBU.bytes = 1; // compression-control byte
1999 if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; }
2000
2001 var checksum = function (data) {
2002 var sum = 0;
2003 for (var i = 0; i < data.length; i++) {
2004 sum += data[i];
2005 if (sum > 65536) sum -= 65536;
2006 }
2007 return sum;
2008 };
2009
2010 var resetStreams = 0;
2011 var streamId = -1;
2012 var decompress = function (data, expected) {
2013 for (var i = 0; i < 4; i++) {
2014 if ((resetStreams >> i) & 1) {
2015 this._FBU.zlibs[i].reset();
2016 Util.Info("Reset zlib stream " + i);
2017 }
2018 }
2019
2020 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2021 var uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected);
2022 /*if (uncompressed.status !== 0) {
2023 Util.Error("Invalid data in zlib stream");
2024 }*/
2025
2026 //return uncompressed.data;
2027 return uncompressed;
2028 }.bind(this);
2029
2030 var indexedToRGBX2Color = function (data, palette, width, height) {
2031 // Convert indexed (palette based) image data to RGB
2032 // TODO: reduce number of calculations inside loop
2033 var dest = this._destBuff;
2034 var w = Math.floor((width + 7) / 8);
2035 var w1 = Math.floor(width / 8);
2036
2037 /*for (var y = 0; y < height; y++) {
2038 var b, x, dp, sp;
2039 var yoffset = y * width;
2040 var ybitoffset = y * w;
2041 var xoffset, targetbyte;
2042 for (x = 0; x < w1; x++) {
2043 xoffset = yoffset + x * 8;
2044 targetbyte = data[ybitoffset + x];
2045 for (b = 7; b >= 0; b--) {
2046 dp = (xoffset + 7 - b) * 3;
2047 sp = (targetbyte >> b & 1) * 3;
2048 dest[dp] = palette[sp];
2049 dest[dp + 1] = palette[sp + 1];
2050 dest[dp + 2] = palette[sp + 2];
2051 }
2052 }
2053
2054 xoffset = yoffset + x * 8;
2055 targetbyte = data[ybitoffset + x];
2056 for (b = 7; b >= 8 - width % 8; b--) {
2057 dp = (xoffset + 7 - b) * 3;
2058 sp = (targetbyte >> b & 1) * 3;
2059 dest[dp] = palette[sp];
2060 dest[dp + 1] = palette[sp + 1];
2061 dest[dp + 2] = palette[sp + 2];
2062 }
2063 }*/
2064
2065 for (var y = 0; y < height; y++) {
2066 var b, x, dp, sp;
2067 for (x = 0; x < w1; x++) {
2068 for (b = 7; b >= 0; b--) {
2069 dp = (y * width + x * 8 + 7 - b) * 4;
2070 sp = (data[y * w + x] >> b & 1) * 3;
2071 dest[dp] = palette[sp];
2072 dest[dp + 1] = palette[sp + 1];
2073 dest[dp + 2] = palette[sp + 2];
2074 dest[dp + 3] = 255;
2075 }
2076 }
2077
2078 for (b = 7; b >= 8 - width % 8; b--) {
2079 dp = (y * width + x * 8 + 7 - b) * 4;
2080 sp = (data[y * w + x] >> b & 1) * 3;
2081 dest[dp] = palette[sp];
2082 dest[dp + 1] = palette[sp + 1];
2083 dest[dp + 2] = palette[sp + 2];
2084 dest[dp + 3] = 255;
2085 }
2086 }
2087
2088 return dest;
2089 }.bind(this);
2090
2091 var indexedToRGBX = function (data, palette, width, height) {
2092 // Convert indexed (palette based) image data to RGB
2093 var dest = this._destBuff;
2094 var total = width * height * 4;
2095 for (var i = 0, j = 0; i < total; i += 4, j++) {
2096 var sp = data[j] * 3;
2097 dest[i] = palette[sp];
2098 dest[i + 1] = palette[sp + 1];
2099 dest[i + 2] = palette[sp + 2];
2100 dest[i + 3] = 255;
2101 }
2102
2103 return dest;
2104 }.bind(this);
2105
2106 var rQi = this._sock.get_rQi();
2107 var rQ = this._sock.rQwhole();
2108 var cmode, data;
2109 var cl_header, cl_data;
2110
2111 var handlePalette = function () {
2112 var numColors = rQ[rQi + 2] + 1;
2113 var paletteSize = numColors * this._fb_depth;
2114 this._FBU.bytes += paletteSize;
2115 if (this._sock.rQwait("TIGHT palette " + cmode, this._FBU.bytes)) { return false; }
2116
2117 var bpp = (numColors <= 2) ? 1 : 8;
2118 var rowSize = Math.floor((this._FBU.width * bpp + 7) / 8);
2119 var raw = false;
2120 if (rowSize * this._FBU.height < 12) {
2121 raw = true;
2122 cl_header = 0;
2123 cl_data = rowSize * this._FBU.height;
2124 //clength = [0, rowSize * this._FBU.height];
2125 } else {
2126 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2127 var cl_offset = rQi + 3 + paletteSize;
2128 cl_header = 1;
2129 cl_data = 0;
2130 cl_data += rQ[cl_offset] & 0x7f;
2131 if (rQ[cl_offset] & 0x80) {
2132 cl_header++;
2133 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2134 if (rQ[cl_offset + 1] & 0x80) {
2135 cl_header++;
2136 cl_data += rQ[cl_offset + 2] << 14;
2137 }
2138 }
2139 // end inline getTightCLength
2140 }
2141
2142 this._FBU.bytes += cl_header + cl_data;
2143 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2144
2145 // Shift ctl, filter id, num colors, palette entries, and clength off
2146 this._sock.rQskipBytes(3);
2147 //var palette = this._sock.rQshiftBytes(paletteSize);
2148 this._sock.rQshiftTo(this._paletteBuff, paletteSize);
2149 this._sock.rQskipBytes(cl_header);
2150
2151 if (raw) {
2152 data = this._sock.rQshiftBytes(cl_data);
2153 } else {
2154 data = decompress(this._sock.rQshiftBytes(cl_data), rowSize * this._FBU.height);
2155 }
2156
2157 // Convert indexed (palette based) image data to RGB
2158 var rgbx;
2159 if (numColors == 2) {
2160 rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2161 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2162 } else {
2163 rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2164 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2165 }
2166
2167
2168 return true;
2169 }.bind(this);
2170
2171 var handleCopy = function () {
2172 var raw = false;
2173 var uncompressedSize = this._FBU.width * this._FBU.height * this._fb_depth;
2174 if (uncompressedSize < 12) {
2175 raw = true;
2176 cl_header = 0;
2177 cl_data = uncompressedSize;
2178 } else {
2179 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2180 var cl_offset = rQi + 1;
2181 cl_header = 1;
2182 cl_data = 0;
2183 cl_data += rQ[cl_offset] & 0x7f;
2184 if (rQ[cl_offset] & 0x80) {
2185 cl_header++;
2186 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2187 if (rQ[cl_offset + 1] & 0x80) {
2188 cl_header++;
2189 cl_data += rQ[cl_offset + 2] << 14;
2190 }
2191 }
2192 // end inline getTightCLength
2193 }
2194 this._FBU.bytes = 1 + cl_header + cl_data;
2195 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2196
2197 // Shift ctl, clength off
2198 this._sock.rQshiftBytes(1 + cl_header);
2199
2200 if (raw) {
2201 data = this._sock.rQshiftBytes(cl_data);
2202 } else {
2203 data = decompress(this._sock.rQshiftBytes(cl_data), uncompressedSize);
2204 }
2205
2206 this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
2207
2208 return true;
2209 }.bind(this);
2210
2211 var ctl = this._sock.rQpeek8();
2212
2213 // Keep tight reset bits
2214 resetStreams = ctl & 0xF;
2215
2216 // Figure out filter
2217 ctl = ctl >> 4;
2218 streamId = ctl & 0x3;
2219
2220 if (ctl === 0x08) cmode = "fill";
2221 else if (ctl === 0x09) cmode = "jpeg";
2222 else if (ctl === 0x0A) cmode = "png";
2223 else if (ctl & 0x04) cmode = "filter";
2224 else if (ctl < 0x04) cmode = "copy";
2225 else return this._fail("Unexpected server message",
2226 "Illegal tight compression received, " +
2227 "ctl: " + ctl);
2228
2229 if (isTightPNG && (cmode === "filter" || cmode === "copy")) {
2230 return this._fail("Unexpected server message",
2231 "filter/copy received in tightPNG mode");
2232 }
2233
2234 switch (cmode) {
2235 // fill use fb_depth because TPIXELs drop the padding byte
2236 case "fill": // TPIXEL
2237 this._FBU.bytes += this._fb_depth;
2238 break;
2239 case "jpeg": // max clength
2240 this._FBU.bytes += 3;
2241 break;
2242 case "png": // max clength
2243 this._FBU.bytes += 3;
2244 break;
2245 case "filter": // filter id + num colors if palette
2246 this._FBU.bytes += 2;
2247 break;
2248 case "copy":
2249 break;
2250 }
2251
2252 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2253
2254 // Determine FBU.bytes
2255 switch (cmode) {
2256 case "fill":
2257 // skip ctl byte
2258 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);
2259 this._sock.rQskipBytes(4);
2260 break;
2261 case "png":
2262 case "jpeg":
2263 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2264 var cl_offset = rQi + 1;
2265 cl_header = 1;
2266 cl_data = 0;
2267 cl_data += rQ[cl_offset] & 0x7f;
2268 if (rQ[cl_offset] & 0x80) {
2269 cl_header++;
2270 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2271 if (rQ[cl_offset + 1] & 0x80) {
2272 cl_header++;
2273 cl_data += rQ[cl_offset + 2] << 14;
2274 }
2275 }
2276 // end inline getTightCLength
2277 this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
2278 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
2279
2280 // We have everything, render it
2281 this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
2282 data = this._sock.rQshiftBytes(cl_data);
2283 this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data);
2284 break;
2285 case "filter":
2286 var filterId = rQ[rQi + 1];
2287 if (filterId === 1) {
2288 if (!handlePalette()) { return false; }
2289 } else {
2290 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2291 // Filter 2, Gradient is valid but not use if jpeg is enabled
2292 this._fail("Unexpected server message",
2293 "Unsupported tight subencoding received, " +
2294 "filter: " + filterId);
2295 }
2296 break;
2297 case "copy":
2298 if (!handleCopy()) { return false; }
2299 break;
2300 }
2301
2302
2303 this._FBU.bytes = 0;
2304 this._FBU.rects--;
2305
2306 return true;
2307 },
2308
2309 TIGHT: function () { return this._encHandlers.display_tight(false); },
2310 TIGHT_PNG: function () { return this._encHandlers.display_tight(true); },
2311
2312 last_rect: function () {
2313 this._FBU.rects = 0;
2314 return true;
2315 },
2316
2317 handle_FB_resize: function () {
2318 this._fb_width = this._FBU.width;
2319 this._fb_height = this._FBU.height;
2320 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
2321 this._display.resize(this._fb_width, this._fb_height);
2322 this._onFBResize(this, this._fb_width, this._fb_height);
2323 this._timing.fbu_rt_start = (new Date()).getTime();
2324 this._updateContinuousUpdates();
2325
2326 this._FBU.bytes = 0;
2327 this._FBU.rects -= 1;
2328 return true;
2329 },
2330
2331 ExtendedDesktopSize: function () {
2332 this._FBU.bytes = 1;
2333 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2334
2335 this._supportsSetDesktopSize = true;
2336 var number_of_screens = this._sock.rQpeek8();
2337
2338 this._FBU.bytes = 4 + (number_of_screens * 16);
2339 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2340
2341 this._sock.rQskipBytes(1); // number-of-screens
2342 this._sock.rQskipBytes(3); // padding
2343
2344 for (var i = 0; i < number_of_screens; i += 1) {
2345 // Save the id and flags of the first screen
2346 if (i === 0) {
2347 this._screen_id = this._sock.rQshiftBytes(4); // id
2348 this._sock.rQskipBytes(2); // x-position
2349 this._sock.rQskipBytes(2); // y-position
2350 this._sock.rQskipBytes(2); // width
2351 this._sock.rQskipBytes(2); // height
2352 this._screen_flags = this._sock.rQshiftBytes(4); // flags
2353 } else {
2354 this._sock.rQskipBytes(16);
2355 }
2356 }
2357
2358 /*
2359 * The x-position indicates the reason for the change:
2360 *
2361 * 0 - server resized on its own
2362 * 1 - this client requested the resize
2363 * 2 - another client requested the resize
2364 */
2365
2366 // We need to handle errors when we requested the resize.
2367 if (this._FBU.x === 1 && this._FBU.y !== 0) {
2368 var msg = "";
2369 // The y-position indicates the status code from the server
2370 switch (this._FBU.y) {
2371 case 1:
2372 msg = "Resize is administratively prohibited";
2373 break;
2374 case 2:
2375 msg = "Out of resources";
2376 break;
2377 case 3:
2378 msg = "Invalid screen layout";
2379 break;
2380 default:
2381 msg = "Unknown reason";
2382 break;
2383 }
2384 this._notification("Server did not accept the resize request: "
2385 + msg, 'normal');
2386 return true;
2387 }
2388
2389 this._encHandlers.handle_FB_resize();
2390 return true;
2391 },
2392
2393 DesktopSize: function () {
2394 this._encHandlers.handle_FB_resize();
2395 return true;
2396 },
2397
2398 Cursor: function () {
2399 Util.Debug(">> set_cursor");
2400 var x = this._FBU.x; // hotspot-x
2401 var y = this._FBU.y; // hotspot-y
2402 var w = this._FBU.width;
2403 var h = this._FBU.height;
2404
2405 var pixelslength = w * h * this._fb_Bpp;
2406 var masklength = Math.floor((w + 7) / 8) * h;
2407
2408 this._FBU.bytes = pixelslength + masklength;
2409 if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
2410
2411 this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
2412 this._sock.rQshiftBytes(masklength),
2413 x, y, w, h);
2414
2415 this._FBU.bytes = 0;
2416 this._FBU.rects--;
2417
2418 Util.Debug("<< set_cursor");
2419 return true;
2420 },
2421
2422 QEMUExtendedKeyEvent: function () {
2423 this._FBU.rects--;
2424
2425 var keyboardEvent = document.createEvent("keyboardEvent");
2426 if (keyboardEvent.code !== undefined) {
2427 this._qemuExtKeyEventSupported = true;
2428 this._keyboard.setQEMUVNCKeyboardHandler();
2429 }
2430 },
2431
2432 JPEG_quality_lo: function () {
2433 Util.Error("Server sent jpeg_quality pseudo-encoding");
2434 },
2435
2436 compress_lo: function () {
2437 Util.Error("Server sent compress level pseudo-encoding");
2438 }
2439 };
2440 })();