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