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