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