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