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