rfb.js 86 KB

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