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