rfb.js 84 KB

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