rfb.js 85 KB

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