rfb.js 79 KB

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