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