rfb.js 78 KB

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