rfb.js 83 KB

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