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