rfb.js 85 KB

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