rfb.js 85 KB

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