rfb.js 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149
  1. /*
  2. * noVNC: HTML5 VNC client
  3. * Copyright (C) 2012 Joel Martin
  4. * Copyright (C) 2013 Samuel Mannehed for Cendio AB
  5. * Licensed under MPL 2.0 (see LICENSE.txt)
  6. *
  7. * See README.md for usage and integration instructions.
  8. *
  9. * TIGHT decoder portion:
  10. * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
  11. */
  12. /*jslint white: false, browser: true */
  13. /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES */
  14. var RFB;
  15. (function () {
  16. "use strict";
  17. RFB = function (defaults) {
  18. if (!defaults) {
  19. defaults = {};
  20. }
  21. this._rfb_host = '';
  22. this._rfb_port = 5900;
  23. this._rfb_password = '';
  24. this._rfb_path = '';
  25. this._rfb_state = 'disconnected';
  26. this._rfb_version = 0;
  27. this._rfb_max_version = 3.8;
  28. this._rfb_auth_scheme = '';
  29. this._rfb_tightvnc = false;
  30. this._rfb_xvp_ver = 0;
  31. // In preference order
  32. this._encodings = [
  33. ['COPYRECT', 0x01 ],
  34. ['TIGHT', 0x07 ],
  35. ['TIGHT_PNG', -260 ],
  36. ['HEXTILE', 0x05 ],
  37. ['RRE', 0x02 ],
  38. ['RAW', 0x00 ],
  39. ['DesktopSize', -223 ],
  40. ['Cursor', -239 ],
  41. // Psuedo-encoding settings
  42. //['JPEG_quality_lo', -32 ],
  43. ['JPEG_quality_med', -26 ],
  44. //['JPEG_quality_hi', -23 ],
  45. //['compress_lo', -255 ],
  46. ['compress_hi', -247 ],
  47. ['last_rect', -224 ],
  48. ['xvp', -309 ],
  49. ['ExtendedDesktopSize', -308 ]
  50. ];
  51. this._encHandlers = {};
  52. this._encNames = {};
  53. this._encStats = {};
  54. this._sock = null; // Websock object
  55. this._display = null; // Display object
  56. this._keyboard = null; // Keyboard input handler object
  57. this._mouse = null; // Mouse input handler object
  58. this._sendTimer = null; // Send Queue check timer
  59. this._disconnTimer = null; // disconnection timer
  60. this._msgTimer = null; // queued handle_msg timer
  61. // Frame buffer update state
  62. this._FBU = {
  63. rects: 0,
  64. subrects: 0, // RRE
  65. lines: 0, // RAW
  66. tiles: 0, // HEXTILE
  67. bytes: 0,
  68. x: 0,
  69. y: 0,
  70. width: 0,
  71. height: 0,
  72. encoding: 0,
  73. subencoding: -1,
  74. background: null,
  75. zlib: [] // TIGHT zlib streams
  76. };
  77. this._fb_Bpp = 4;
  78. this._fb_depth = 3;
  79. this._fb_width = 0;
  80. this._fb_height = 0;
  81. this._fb_name = "";
  82. this._destBuff = null;
  83. this._paletteBuff = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
  84. this._rre_chunk_sz = 100;
  85. this._timing = {
  86. last_fbu: 0,
  87. fbu_total: 0,
  88. fbu_total_cnt: 0,
  89. full_fbu_total: 0,
  90. full_fbu_cnt: 0,
  91. fbu_rt_start: 0,
  92. fbu_rt_total: 0,
  93. fbu_rt_cnt: 0,
  94. pixels: 0
  95. };
  96. this._supportsSetDesktopSize = false;
  97. this._screen_id = 0;
  98. this._screen_flags = 0;
  99. // Mouse state
  100. this._mouse_buttonMask = 0;
  101. this._mouse_arr = [];
  102. this._viewportDragging = false;
  103. this._viewportDragPos = {};
  104. this._viewportHasMoved = false;
  105. // set the default value on user-facing properties
  106. Util.set_defaults(this, defaults, {
  107. 'target': 'null', // VNC display rendering Canvas object
  108. 'focusContainer': document, // DOM element that captures keyboard input
  109. 'encrypt': false, // Use TLS/SSL/wss encryption
  110. 'true_color': true, // Request true color pixel data
  111. 'local_cursor': false, // Request locally rendered cursor
  112. 'shared': true, // Request shared mode
  113. 'view_only': false, // Disable client mouse/keyboard
  114. 'xvp_password_sep': '@', // Separator for XVP password fields
  115. 'disconnectTimeout': 3, // Time (s) to wait for disconnection
  116. 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
  117. 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
  118. 'viewportDrag': false, // Move the viewport on mouse drags
  119. // Callback functions
  120. 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate, statusMsg): state update/change
  121. 'onPasswordRequired': function () { }, // onPasswordRequired(rfb): VNC password is required
  122. 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
  123. 'onBell': function () { }, // onBell(rfb): RFB Bell message received
  124. 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
  125. 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
  126. 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
  127. 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
  128. 'onXvpInit': function () { }, // onXvpInit(version): XVP extensions active for this connection
  129. });
  130. // main setup
  131. Util.Debug(">> RFB.constructor");
  132. // populate encHandlers with bound versions
  133. Object.keys(RFB.encodingHandlers).forEach(function (encName) {
  134. this._encHandlers[encName] = RFB.encodingHandlers[encName].bind(this);
  135. }.bind(this));
  136. // Create lookup tables based on encoding number
  137. for (var i = 0; i < this._encodings.length; i++) {
  138. this._encHandlers[this._encodings[i][1]] = this._encHandlers[this._encodings[i][0]];
  139. this._encNames[this._encodings[i][1]] = this._encodings[i][0];
  140. this._encStats[this._encodings[i][1]] = [0, 0];
  141. }
  142. // NB: nothing that needs explicit teardown should be done
  143. // before this point, since this can throw an exception
  144. try {
  145. this._display = new Display({target: this._target});
  146. } catch (exc) {
  147. Util.Error("Display exception: " + exc);
  148. throw exc;
  149. }
  150. this._keyboard = new Keyboard({target: this._focusContainer,
  151. onKeyPress: this._handleKeyPress.bind(this)});
  152. this._mouse = new Mouse({target: this._target,
  153. onMouseButton: this._handleMouseButton.bind(this),
  154. onMouseMove: this._handleMouseMove.bind(this),
  155. notify: this._keyboard.sync.bind(this._keyboard)});
  156. this._sock = new Websock();
  157. this._sock.on('message', this._handle_message.bind(this));
  158. this._sock.on('open', function () {
  159. if (this._rfb_state === 'connect') {
  160. this._updateState('ProtocolVersion', "Starting VNC handshake");
  161. } else {
  162. this._fail("Got unexpected WebSocket connection");
  163. }
  164. }.bind(this));
  165. this._sock.on('close', function (e) {
  166. Util.Warn("WebSocket on-close event");
  167. var msg = "";
  168. if (e.code) {
  169. msg = " (code: " + e.code;
  170. if (e.reason) {
  171. msg += ", reason: " + e.reason;
  172. }
  173. msg += ")";
  174. }
  175. if (this._rfb_state === 'disconnect') {
  176. this._updateState('disconnected', 'VNC disconnected' + msg);
  177. } else if (this._rfb_state === 'ProtocolVersion') {
  178. this._fail('Failed to connect to server' + msg);
  179. } else if (this._rfb_state in {'failed': 1, 'disconnected': 1}) {
  180. Util.Error("Received onclose while disconnected" + msg);
  181. } else {
  182. this._fail("Server disconnected" + msg);
  183. }
  184. this._sock.off('close');
  185. }.bind(this));
  186. this._sock.on('error', function (e) {
  187. Util.Warn("WebSocket on-error event");
  188. });
  189. this._init_vars();
  190. var rmode = this._display.get_render_mode();
  191. if (Websock_native) {
  192. Util.Info("Using native WebSockets");
  193. this._updateState('loaded', 'noVNC ready: native WebSockets, ' + rmode);
  194. } else {
  195. this._cleanupSocket('fatal');
  196. throw new Error("WebSocket support is required to use noVNC");
  197. }
  198. Util.Debug("<< RFB.constructor");
  199. };
  200. RFB.prototype = {
  201. // Public methods
  202. connect: function (host, port, password, path) {
  203. this._rfb_host = host;
  204. this._rfb_port = port;
  205. this._rfb_password = (password !== undefined) ? password : "";
  206. this._rfb_path = (path !== undefined) ? path : "";
  207. if (!this._rfb_host || !this._rfb_port) {
  208. return this._fail("Must set host and port");
  209. }
  210. this._updateState('connect');
  211. },
  212. disconnect: function () {
  213. this._updateState('disconnect', 'Disconnecting');
  214. this._sock.off('error');
  215. this._sock.off('message');
  216. this._sock.off('open');
  217. },
  218. sendPassword: function (passwd) {
  219. this._rfb_password = passwd;
  220. this._rfb_state = 'Authentication';
  221. setTimeout(this._init_msg.bind(this), 1);
  222. },
  223. sendCtrlAltDel: function () {
  224. if (this._rfb_state !== 'normal' || this._view_only) { return false; }
  225. Util.Info("Sending Ctrl-Alt-Del");
  226. RFB.messages.keyEvent(this._sock, XK_Control_L, 1);
  227. RFB.messages.keyEvent(this._sock, XK_Alt_L, 1);
  228. RFB.messages.keyEvent(this._sock, XK_Delete, 1);
  229. RFB.messages.keyEvent(this._sock, XK_Delete, 0);
  230. RFB.messages.keyEvent(this._sock, XK_Alt_L, 0);
  231. RFB.messages.keyEvent(this._sock, XK_Control_L, 0);
  232. this._sock.flush();
  233. },
  234. xvpOp: function (ver, op) {
  235. if (this._rfb_xvp_ver < ver) { return false; }
  236. Util.Info("Sending XVP operation " + op + " (version " + ver + ")");
  237. this._sock.send_string("\xFA\x00" + String.fromCharCode(ver) + String.fromCharCode(op));
  238. return true;
  239. },
  240. xvpShutdown: function () {
  241. return this.xvpOp(1, 2);
  242. },
  243. xvpReboot: function () {
  244. return this.xvpOp(1, 3);
  245. },
  246. xvpReset: function () {
  247. return this.xvpOp(1, 4);
  248. },
  249. // Send a key press. If 'down' is not specified then send a down key
  250. // followed by an up key.
  251. sendKey: function (code, down) {
  252. if (this._rfb_state !== "normal" || this._view_only) { return false; }
  253. if (typeof down !== 'undefined') {
  254. Util.Info("Sending key code (" + (down ? "down" : "up") + "): " + code);
  255. RFB.messages.keyEvent(this._sock, code, down ? 1 : 0);
  256. } else {
  257. Util.Info("Sending key code (down + up): " + code);
  258. RFB.messages.keyEvent(this._sock, code, 1);
  259. RFB.messages.keyEvent(this._sock, code, 0);
  260. }
  261. this._sock.flush();
  262. },
  263. clipboardPasteFrom: function (text) {
  264. if (this._rfb_state !== 'normal') { return; }
  265. RFB.messages.clientCutText(this._sock, text);
  266. this._sock.flush();
  267. },
  268. // 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. // TODO(directxman12): why aren't we just calling '_fail' here
  1700. throw new Error("Unsupported tight subencoding received, filter: " + filterId);
  1701. }
  1702. break;
  1703. case "copy":
  1704. if (!handleCopy()) { return false; }
  1705. break;
  1706. }
  1707. this._FBU.bytes = 0;
  1708. this._FBU.rects--;
  1709. return true;
  1710. },
  1711. TIGHT: function () { return this._encHandlers.display_tight(false); },
  1712. TIGHT_PNG: function () { return this._encHandlers.display_tight(true); },
  1713. last_rect: function () {
  1714. this._FBU.rects = 0;
  1715. return true;
  1716. },
  1717. handle_FB_resize: function () {
  1718. this._fb_width = this._FBU.width;
  1719. this._fb_height = this._FBU.height;
  1720. this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
  1721. this._display.resize(this._fb_width, this._fb_height);
  1722. this._onFBResize(this, this._fb_width, this._fb_height);
  1723. this._timing.fbu_rt_start = (new Date()).getTime();
  1724. this._FBU.bytes = 0;
  1725. this._FBU.rects -= 1;
  1726. return true;
  1727. },
  1728. ExtendedDesktopSize: function () {
  1729. this._FBU.bytes = 1;
  1730. if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
  1731. this._supportsSetDesktopSize = true;
  1732. var number_of_screens = this._sock.rQpeek8();
  1733. this._FBU.bytes = 4 + (number_of_screens * 16);
  1734. if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
  1735. this._sock.rQskipBytes(1); // number-of-screens
  1736. this._sock.rQskipBytes(3); // padding
  1737. for (var i = 0; i < number_of_screens; i += 1) {
  1738. // Save the id and flags of the first screen
  1739. if (i === 0) {
  1740. this._screen_id = this._sock.rQshiftBytes(4); // id
  1741. this._sock.rQskipBytes(2); // x-position
  1742. this._sock.rQskipBytes(2); // y-position
  1743. this._sock.rQskipBytes(2); // width
  1744. this._sock.rQskipBytes(2); // height
  1745. this._screen_flags = this._sock.rQshiftBytes(4); // flags
  1746. } else {
  1747. this._sock.rQskipBytes(16);
  1748. }
  1749. }
  1750. /*
  1751. * The x-position indicates the reason for the change:
  1752. *
  1753. * 0 - server resized on its own
  1754. * 1 - this client requested the resize
  1755. * 2 - another client requested the resize
  1756. */
  1757. // We need to handle errors when we requested the resize.
  1758. if (this._FBU.x === 1 && this._FBU.y !== 0) {
  1759. var msg = "";
  1760. // The y-position indicates the status code from the server
  1761. switch (this._FBU.y) {
  1762. case 1:
  1763. msg = "Resize is administratively prohibited";
  1764. break;
  1765. case 2:
  1766. msg = "Out of resources";
  1767. break;
  1768. case 3:
  1769. msg = "Invalid screen layout";
  1770. break;
  1771. default:
  1772. msg = "Unknown reason";
  1773. break;
  1774. }
  1775. Util.Info("Server did not accept the resize request: " + msg);
  1776. return true;
  1777. }
  1778. this._encHandlers.handle_FB_resize();
  1779. return true;
  1780. },
  1781. DesktopSize: function () {
  1782. this._encHandlers.handle_FB_resize();
  1783. return true;
  1784. },
  1785. Cursor: function () {
  1786. Util.Debug(">> set_cursor");
  1787. var x = this._FBU.x; // hotspot-x
  1788. var y = this._FBU.y; // hotspot-y
  1789. var w = this._FBU.width;
  1790. var h = this._FBU.height;
  1791. var pixelslength = w * h * this._fb_Bpp;
  1792. var masklength = Math.floor((w + 7) / 8) * h;
  1793. this._FBU.bytes = pixelslength + masklength;
  1794. if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
  1795. this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
  1796. this._sock.rQshiftBytes(masklength),
  1797. x, y, w, h);
  1798. this._FBU.bytes = 0;
  1799. this._FBU.rects--;
  1800. Util.Debug("<< set_cursor");
  1801. return true;
  1802. },
  1803. JPEG_quality_lo: function () {
  1804. Util.Error("Server sent jpeg_quality pseudo-encoding");
  1805. },
  1806. compress_lo: function () {
  1807. Util.Error("Server sent compress level pseudo-encoding");
  1808. }
  1809. };
  1810. })();