rfb.js 85 KB

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