rfb.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. /*
  2. * noVNC: HTML5 VNC client
  3. * Copyright (C) 2010 Joel Martin
  4. * Licensed under LGPL-3 (see LICENSE.txt)
  5. *
  6. * See README.md for usage and integration instructions.
  7. */
  8. "use strict";
  9. /*jslint white: false, browser: true, bitwise: false, plusplus: false */
  10. /*global window, WebSocket, Util, Canvas, VNC_native_ws, Base64, DES */
  11. function RFB(conf) {
  12. conf = conf || {}; // Configuration
  13. var that = {}, // Public API interface
  14. // Pre-declare private functions used before definitions (jslint)
  15. init_vars, updateState, init_msg, normal_msg,
  16. framebufferUpdate, print_stats,
  17. pixelFormat, clientEncodings, fbUpdateRequest,
  18. keyEvent, pointerEvent, clientCutText,
  19. extract_data_uri, scan_tight_imgQ,
  20. checkEvents, // Overridable for testing
  21. //
  22. // Private RFB namespace variables
  23. //
  24. rfb_host = '',
  25. rfb_port = 5900,
  26. rfb_password = '',
  27. rfb_state = 'disconnected',
  28. rfb_version = 0,
  29. rfb_max_version= 3.8,
  30. rfb_auth_scheme= '',
  31. // In preference order
  32. encodings = [
  33. ['COPYRECT', 0x01 ],
  34. ['TIGHT_PNG', -260 ],
  35. ['HEXTILE', 0x05 ],
  36. ['RRE', 0x02 ],
  37. ['RAW', 0x00 ],
  38. ['DesktopSize', -223 ],
  39. ['Cursor', -239 ],
  40. // Psuedo-encoding settings
  41. ['JPEG_quality_lo', -32 ],
  42. //['JPEG_quality_hi', -23 ],
  43. ['compress_lo', -255 ]
  44. //['compress_hi', -247 ]
  45. ],
  46. encHandlers = {},
  47. encNames = {},
  48. encStats = {}, // [rectCnt, rectCntTot]
  49. ws = null, // Websock object
  50. canvas = null, // Canvas object
  51. sendTimer = null, // Send Queue check timer
  52. connTimer = null, // connection timer
  53. disconnTimer = null, // disconnection timer
  54. msgTimer = null, // queued handle_message timer
  55. // Frame buffer update state
  56. FBU = {
  57. rects : 0,
  58. subrects : 0, // RRE
  59. lines : 0, // RAW
  60. tiles : 0, // HEXTILE
  61. bytes : 0,
  62. x : 0,
  63. y : 0,
  64. width : 0,
  65. height : 0,
  66. encoding : 0,
  67. subencoding : -1,
  68. background : null,
  69. imgQ : [] // TIGHT_PNG image queue
  70. },
  71. fb_Bpp = 4,
  72. fb_depth = 3,
  73. fb_width = 0,
  74. fb_height = 0,
  75. fb_name = "",
  76. scan_imgQ_rate = 100,
  77. last_req_time = 0,
  78. rre_chunk_sz = 100,
  79. timing = {
  80. last_fbu : 0,
  81. fbu_total : 0,
  82. fbu_total_cnt : 0,
  83. full_fbu_total : 0,
  84. full_fbu_cnt : 0,
  85. fbu_rt_start : 0,
  86. fbu_rt_total : 0,
  87. fbu_rt_cnt : 0
  88. },
  89. test_mode = false,
  90. /* Mouse state */
  91. mouse_buttonMask = 0,
  92. mouse_arr = [];
  93. //
  94. // Configuration settings
  95. //
  96. function cdef(v, type, defval, desc) {
  97. Util.conf_default(conf, that, v, type, defval, desc); }
  98. cdef('target', 'str', null, 'VNC viewport rendering Canvas');
  99. cdef('focusContainer', 'dom', document, 'Area that traps keyboard input');
  100. cdef('encrypt', 'bool', false, 'Use TLS/SSL/wss encryption');
  101. cdef('true_color', 'bool', true, 'Request true color pixel data');
  102. cdef('local_cursor', 'bool', false, 'Request locally rendered cursor');
  103. cdef('shared', 'bool', true, 'Request shared mode');
  104. cdef('connectTimeout', 'int', 2, 'Time (s) to wait for connection');
  105. cdef('disconnectTimeout', 'int', 3, 'Time (s) to wait for disconnection');
  106. cdef('check_rate', 'int', 217, 'Timing (ms) of send/receive check');
  107. cdef('fbu_req_rate', 'int', 1413, 'Timing (ms) of frameBufferUpdate requests');
  108. cdef('updateState',
  109. 'func', function() { Util.Debug("updateState stub"); },
  110. 'callback: state update');
  111. cdef('clipboardReceive',
  112. 'func', function() { Util.Debug("clipboardReceive stub"); },
  113. 'callback: clipboard contents received');
  114. // Override/add some specific getters/setters
  115. that.set_local_cursor = function(cursor) {
  116. if ((!cursor) || (cursor in {'0':1, 'no':1, 'false':1})) {
  117. conf.local_cursor = false;
  118. } else {
  119. if (canvas.get_cursor_uri()) {
  120. conf.local_cursor = true;
  121. } else {
  122. Util.Warn("Browser does not support local cursor");
  123. }
  124. }
  125. };
  126. that.get_canvas = function() {
  127. return canvas;
  128. };
  129. //
  130. // Setup routines
  131. //
  132. // Create the public API interface and initialize
  133. function constructor() {
  134. var i, rmode;
  135. Util.Debug(">> RFB.constructor");
  136. // Create lookup tables based encoding number
  137. for (i=0; i < encodings.length; i+=1) {
  138. encHandlers[encodings[i][1]] = encHandlers[encodings[i][0]];
  139. encNames[encodings[i][1]] = encodings[i][0];
  140. encStats[encodings[i][1]] = [0, 0];
  141. }
  142. // Initialize canvas
  143. try {
  144. canvas = new Canvas({'target': conf.target,
  145. 'focusContainer': conf.focusContainer});
  146. } catch (exc) {
  147. Util.Error("Canvas exception: " + exc);
  148. updateState('fatal', "No working Canvas");
  149. }
  150. rmode = canvas.get_render_mode();
  151. init_vars();
  152. /* Check web-socket-js if no builtin WebSocket support */
  153. if (Websock_native) {
  154. Util.Info("Using native WebSockets");
  155. updateState('loaded', 'noVNC ready: native WebSockets, ' + rmode);
  156. } else {
  157. Util.Warn("Using web-socket-js bridge. Flash version: " +
  158. Util.Flash.version);
  159. if ((! Util.Flash) ||
  160. (Util.Flash.version < 9)) {
  161. updateState('fatal', "WebSockets or Adobe Flash is required");
  162. } else if (document.location.href.substr(0, 7) === "file://") {
  163. updateState('fatal',
  164. "'file://' URL is incompatible with Adobe Flash");
  165. } else {
  166. updateState('loaded', 'noVNC ready: WebSockets emulation, ' + rmode);
  167. }
  168. }
  169. Util.Debug("<< RFB.constructor");
  170. return that; // Return the public API interface
  171. }
  172. function connect() {
  173. Util.Debug(">> RFB.connect");
  174. var uri = "";
  175. if (conf.encrypt) {
  176. uri = "wss://";
  177. } else {
  178. uri = "ws://";
  179. }
  180. uri += rfb_host + ":" + rfb_port + "/";
  181. Util.Info("connecting to " + uri);
  182. ws.open(uri);
  183. Util.Debug("<< RFB.connect");
  184. }
  185. init_vars = function() {
  186. /* Reset state */
  187. ws = new Websock();
  188. ws.init();
  189. ws.on('message', handle_message);
  190. ws.on('open', function() {
  191. if (rfb_state === "connect") {
  192. updateState('ProtocolVersion', "Starting VNC handshake");
  193. } else {
  194. fail("Got unexpected WebSockets connection");
  195. }
  196. });
  197. ws.on('close', function() {
  198. if (rfb_state === 'disconnect') {
  199. updateState('disconnected', 'VNC disconnected');
  200. } else if (rfb_state === 'ProtocolVersion') {
  201. fail('Failed to connect to server');
  202. } else if (rfb_state in {'failed':1, 'disconnected':1}) {
  203. Util.Error("Received onclose while disconnected");
  204. } else {
  205. fail('Server disconnected');
  206. }
  207. });
  208. ws.on('error', function(e) {
  209. fail("WebSock error: " + e);
  210. });
  211. FBU.rects = 0;
  212. FBU.subrects = 0; // RRE and HEXTILE
  213. FBU.lines = 0; // RAW
  214. FBU.tiles = 0; // HEXTILE
  215. FBU.imgQ = []; // TIGHT_PNG image queue
  216. mouse_buttonMask = 0;
  217. mouse_arr = [];
  218. // Clear the per connection encoding stats
  219. for (var i=0; i < encodings.length; i+=1) {
  220. encStats[encodings[i][1]][0] = 0;
  221. }
  222. };
  223. // Print statistics
  224. print_stats = function() {
  225. var i, encName, s;
  226. Util.Info("Encoding stats for this connection:");
  227. for (i=0; i < encodings.length; i+=1) {
  228. s = encStats[encodings[i][1]];
  229. if ((s[0] + s[1]) > 0) {
  230. Util.Info(" " + encodings[i][0] + ": " +
  231. s[0] + " rects");
  232. }
  233. }
  234. Util.Info("Encoding stats since page load:");
  235. for (i=0; i < encodings.length; i+=1) {
  236. s = encStats[encodings[i][1]];
  237. if ((s[0] + s[1]) > 0) {
  238. Util.Info(" " + encodings[i][0] + ": "
  239. + s[1] + " rects");
  240. }
  241. }
  242. };
  243. //
  244. // Utility routines
  245. //
  246. /*
  247. * Running states:
  248. * disconnected - idle state
  249. * normal - connected
  250. *
  251. * Page states:
  252. * loaded - page load, equivalent to disconnected
  253. * connect - starting initialization
  254. * disconnect - starting disconnect
  255. * failed - abnormal transition to disconnected
  256. * fatal - failed to load page, or fatal error
  257. *
  258. * VNC initialization states:
  259. * ProtocolVersion
  260. * Security
  261. * Authentication
  262. * password - waiting for password, not part of RFB
  263. * SecurityResult
  264. * ClientInitialization - not triggered by server message
  265. * ServerInitialization
  266. */
  267. updateState = function(state, statusMsg) {
  268. var func, cmsg, oldstate = rfb_state;
  269. if (state === oldstate) {
  270. /* Already here, ignore */
  271. Util.Debug("Already in state '" + state + "', ignoring.");
  272. return;
  273. }
  274. /*
  275. * These are disconnected states. A previous connect may
  276. * asynchronously cause a connection so make sure we are closed.
  277. */
  278. if (state in {'disconnected':1, 'loaded':1, 'connect':1,
  279. 'disconnect':1, 'failed':1, 'fatal':1}) {
  280. if (sendTimer) {
  281. clearInterval(sendTimer);
  282. sendTimer = null;
  283. }
  284. if (msgTimer) {
  285. clearInterval(msgTimer);
  286. msgTimer = null;
  287. }
  288. if (canvas && canvas.getContext()) {
  289. canvas.stop();
  290. if (Util.get_logging() !== 'debug') {
  291. canvas.clear();
  292. }
  293. }
  294. ws.close();
  295. }
  296. if (oldstate === 'fatal') {
  297. Util.Error("Fatal error, cannot continue");
  298. }
  299. if ((state === 'failed') || (state === 'fatal')) {
  300. func = Util.Error;
  301. } else {
  302. func = Util.Warn;
  303. }
  304. if ((oldstate === 'failed') && (state === 'disconnected')) {
  305. // Do disconnect action, but stay in failed state.
  306. rfb_state = 'failed';
  307. } else {
  308. rfb_state = state;
  309. }
  310. cmsg = typeof(statusMsg) !== 'undefined' ? (" Msg: " + statusMsg) : "";
  311. func("New state '" + rfb_state + "', was '" + oldstate + "'." + cmsg);
  312. if (connTimer && (rfb_state !== 'connect')) {
  313. Util.Debug("Clearing connect timer");
  314. clearInterval(connTimer);
  315. connTimer = null;
  316. }
  317. if (disconnTimer && (rfb_state !== 'disconnect')) {
  318. Util.Debug("Clearing disconnect timer");
  319. clearInterval(disconnTimer);
  320. disconnTimer = null;
  321. }
  322. switch (state) {
  323. case 'normal':
  324. if ((oldstate === 'disconnected') || (oldstate === 'failed')) {
  325. Util.Error("Invalid transition from 'disconnected' or 'failed' to 'normal'");
  326. }
  327. break;
  328. case 'connect':
  329. connTimer = setTimeout(function () {
  330. fail("Connect timeout");
  331. }, conf.connectTimeout * 1000);
  332. init_vars();
  333. connect();
  334. // WebSocket.onopen transitions to 'ProtocolVersion'
  335. break;
  336. case 'disconnect':
  337. if (! test_mode) {
  338. disconnTimer = setTimeout(function () {
  339. fail("Disconnect timeout");
  340. }, conf.disconnectTimeout * 1000);
  341. }
  342. print_stats();
  343. // WebSocket.onclose transitions to 'disconnected'
  344. break;
  345. case 'failed':
  346. if (oldstate === 'disconnected') {
  347. Util.Error("Invalid transition from 'disconnected' to 'failed'");
  348. }
  349. if (oldstate === 'normal') {
  350. Util.Error("Error while connected.");
  351. }
  352. if (oldstate === 'init') {
  353. Util.Error("Error while initializing.");
  354. }
  355. // Make sure we transition to disconnected
  356. setTimeout(function() { updateState('disconnected'); }, 50);
  357. break;
  358. default:
  359. // No state change action to take
  360. }
  361. if ((oldstate === 'failed') && (state === 'disconnected')) {
  362. // Leave the failed message
  363. conf.updateState(that, state, oldstate);
  364. } else {
  365. conf.updateState(that, state, oldstate, statusMsg);
  366. }
  367. };
  368. function fail(msg) {
  369. updateState('failed', msg);
  370. return false;
  371. }
  372. function handle_message() {
  373. //Util.Debug(">> handle_message ws.rQlen(): " + ws.rQlen());
  374. //Util.Debug("ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  375. if (ws.rQlen() === 0) {
  376. Util.Warn("handle_message called on empty receive queue");
  377. return;
  378. }
  379. switch (rfb_state) {
  380. case 'disconnected':
  381. case 'failed':
  382. Util.Error("Got data while disconnected");
  383. break;
  384. case 'normal':
  385. if (normal_msg() && ws.rQlen() > 0) {
  386. // true means we can continue processing
  387. // Give other events a chance to run
  388. if (msgTimer === null) {
  389. Util.Debug("More data to process, creating timer");
  390. msgTimer = setTimeout(function () {
  391. msgTimer = null;
  392. handle_message();
  393. }, 10);
  394. } else {
  395. Util.Debug("More data to process, existing timer");
  396. }
  397. }
  398. break;
  399. default:
  400. init_msg();
  401. break;
  402. }
  403. }
  404. function genDES(password, challenge) {
  405. var i, passwd = [], des;
  406. for (i=0; i < password.length; i += 1) {
  407. passwd.push(password.charCodeAt(i));
  408. }
  409. return (new DES(passwd)).encrypt(challenge);
  410. }
  411. function flushClient() {
  412. if (mouse_arr.length > 0) {
  413. //send(mouse_arr.concat(fbUpdateRequest(1)));
  414. ws.send(mouse_arr);
  415. setTimeout(function() {
  416. ws.send(fbUpdateRequest(1));
  417. }, 50);
  418. mouse_arr = [];
  419. return true;
  420. } else {
  421. return false;
  422. }
  423. }
  424. // overridable for testing
  425. checkEvents = function() {
  426. var now;
  427. if (rfb_state === 'normal') {
  428. if (! flushClient()) {
  429. now = new Date().getTime();
  430. if (now > last_req_time + conf.fbu_req_rate) {
  431. last_req_time = now;
  432. ws.send(fbUpdateRequest(1));
  433. }
  434. }
  435. }
  436. setTimeout(checkEvents, conf.check_rate);
  437. };
  438. function keyPress(keysym, down) {
  439. var arr;
  440. arr = keyEvent(keysym, down);
  441. arr = arr.concat(fbUpdateRequest(1));
  442. ws.send(arr);
  443. }
  444. function mouseButton(x, y, down, bmask) {
  445. if (down) {
  446. mouse_buttonMask |= bmask;
  447. } else {
  448. mouse_buttonMask ^= bmask;
  449. }
  450. mouse_arr = mouse_arr.concat( pointerEvent(x, y) );
  451. flushClient();
  452. }
  453. function mouseMove(x, y) {
  454. //Util.Debug('>> mouseMove ' + x + "," + y);
  455. mouse_arr = mouse_arr.concat( pointerEvent(x, y) );
  456. }
  457. //
  458. // Server message handlers
  459. //
  460. // RFB/VNC initialisation message handler
  461. init_msg = function() {
  462. //Util.Debug(">> init_msg [rfb_state '" + rfb_state + "']");
  463. var strlen, reason, length, sversion, cversion,
  464. i, types, num_types, challenge, response, bpp, depth,
  465. big_endian, true_color, name_length;
  466. //Util.Debug("ws.rQ (" + ws.rQlen() + ") " + ws.rQslice(0));
  467. switch (rfb_state) {
  468. case 'ProtocolVersion' :
  469. if (ws.rQlen() < 12) {
  470. return fail("Incomplete protocol version");
  471. }
  472. sversion = ws.rQshiftStr(12).substr(4,7);
  473. Util.Info("Server ProtocolVersion: " + sversion);
  474. switch (sversion) {
  475. case "003.003": rfb_version = 3.3; break;
  476. case "003.006": rfb_version = 3.3; break; // UltraVNC
  477. case "003.007": rfb_version = 3.7; break;
  478. case "003.008": rfb_version = 3.8; break;
  479. default:
  480. return fail("Invalid server version " + sversion);
  481. }
  482. if (rfb_version > rfb_max_version) {
  483. rfb_version = rfb_max_version;
  484. }
  485. if (! test_mode) {
  486. sendTimer = setInterval(function() {
  487. // Send updates either at a rate of one update
  488. // every 50ms, or whatever slower rate the network
  489. // can handle.
  490. ws.flush();
  491. }, 50);
  492. }
  493. cversion = "00" + parseInt(rfb_version,10) +
  494. ".00" + ((rfb_version * 10) % 10);
  495. ws.send_string("RFB " + cversion + "\n");
  496. updateState('Security', "Sent ProtocolVersion: " + cversion);
  497. break;
  498. case 'Security' :
  499. if (rfb_version >= 3.7) {
  500. // Server sends supported list, client decides
  501. num_types = ws.rQshift8();
  502. if (ws.rQwait("security type", num_types, 1)) { return false; }
  503. if (num_types === 0) {
  504. strlen = ws.rQshift32();
  505. reason = ws.rQshiftStr(strlen);
  506. return fail("Security failure: " + reason);
  507. }
  508. rfb_auth_scheme = 0;
  509. types = ws.rQshiftBytes(num_types);
  510. Util.Debug("Server security types: " + types);
  511. for (i=0; i < types.length; i+=1) {
  512. if ((types[i] > rfb_auth_scheme) && (types[i] < 3)) {
  513. rfb_auth_scheme = types[i];
  514. }
  515. }
  516. if (rfb_auth_scheme === 0) {
  517. return fail("Unsupported security types: " + types);
  518. }
  519. ws.send([rfb_auth_scheme]);
  520. } else {
  521. // Server decides
  522. if (ws.rQwait("security scheme", 4)) { return false; }
  523. rfb_auth_scheme = ws.rQshift32();
  524. }
  525. updateState('Authentication',
  526. "Authenticating using scheme: " + rfb_auth_scheme);
  527. init_msg(); // Recursive fallthrough (workaround JSLint complaint)
  528. break;
  529. // Triggered by fallthough, not by server message
  530. case 'Authentication' :
  531. //Util.Debug("Security auth scheme: " + rfb_auth_scheme);
  532. switch (rfb_auth_scheme) {
  533. case 0: // connection failed
  534. if (ws.rQwait("auth reason", 4)) { return false; }
  535. strlen = ws.rQshift32();
  536. reason = ws.rQshiftStr(strlen);
  537. return fail("Auth failure: " + reason);
  538. case 1: // no authentication
  539. if (rfb_version >= 3.8) {
  540. updateState('SecurityResult');
  541. return;
  542. } else {
  543. // Fall through to ClientInitialisation
  544. }
  545. break;
  546. case 2: // VNC authentication
  547. if (rfb_password.length === 0) {
  548. updateState('password', "Password Required");
  549. return;
  550. }
  551. if (ws.rQwait("auth challenge", 16)) { return false; }
  552. challenge = ws.rQshiftBytes(16);
  553. //Util.Debug("Password: " + rfb_password);
  554. //Util.Debug("Challenge: " + challenge +
  555. // " (" + challenge.length + ")");
  556. response = genDES(rfb_password, challenge);
  557. //Util.Debug("Response: " + response +
  558. // " (" + response.length + ")");
  559. //Util.Debug("Sending DES encrypted auth response");
  560. ws.send(response);
  561. updateState('SecurityResult');
  562. return;
  563. default:
  564. fail("Unsupported auth scheme: " + rfb_auth_scheme);
  565. return;
  566. }
  567. updateState('ClientInitialisation', "No auth required");
  568. init_msg(); // Recursive fallthrough (workaround JSLint complaint)
  569. break;
  570. case 'SecurityResult' :
  571. if (ws.rQwait("VNC auth response ", 4)) { return false; }
  572. switch (ws.rQshift32()) {
  573. case 0: // OK
  574. // Fall through to ClientInitialisation
  575. break;
  576. case 1: // failed
  577. if (rfb_version >= 3.8) {
  578. length = ws.rQshift32();
  579. if (ws.rQwait("SecurityResult reason", length, 8)) {
  580. return false;
  581. }
  582. reason = ws.rQshiftStr(length);
  583. fail(reason);
  584. } else {
  585. fail("Authentication failed");
  586. }
  587. return;
  588. case 2: // too-many
  589. return fail("Too many auth attempts");
  590. }
  591. updateState('ClientInitialisation', "Authentication OK");
  592. init_msg(); // Recursive fallthrough (workaround JSLint complaint)
  593. break;
  594. // Triggered by fallthough, not by server message
  595. case 'ClientInitialisation' :
  596. ws.send([conf.shared ? 1 : 0]); // ClientInitialisation
  597. updateState('ServerInitialisation', "Authentication OK");
  598. break;
  599. case 'ServerInitialisation' :
  600. if (ws.rQwait("server initialization", 24)) { return false; }
  601. /* Screen size */
  602. fb_width = ws.rQshift16();
  603. fb_height = ws.rQshift16();
  604. /* PIXEL_FORMAT */
  605. bpp = ws.rQshift8();
  606. depth = ws.rQshift8();
  607. big_endian = ws.rQshift8();
  608. true_color = ws.rQshift8();
  609. Util.Info("Screen: " + fb_width + "x" + fb_height +
  610. ", bpp: " + bpp + ", depth: " + depth +
  611. ", big_endian: " + big_endian +
  612. ", true_color: " + true_color);
  613. /* Connection name/title */
  614. ws.rQshiftStr(12);
  615. name_length = ws.rQshift32();
  616. fb_name = ws.rQshiftStr(name_length);
  617. canvas.resize(fb_width, fb_height, conf.true_color);
  618. canvas.start(keyPress, mouseButton, mouseMove);
  619. if (conf.true_color) {
  620. fb_Bpp = 4;
  621. fb_depth = 3;
  622. } else {
  623. fb_Bpp = 1;
  624. fb_depth = 1;
  625. }
  626. response = pixelFormat();
  627. response = response.concat(clientEncodings());
  628. response = response.concat(fbUpdateRequest(0));
  629. timing.fbu_rt_start = (new Date()).getTime();
  630. ws.send(response);
  631. /* Start pushing/polling */
  632. setTimeout(checkEvents, conf.check_rate);
  633. setTimeout(scan_tight_imgQ, scan_imgQ_rate);
  634. if (conf.encrypt) {
  635. updateState('normal', "Connected (encrypted) to: " + fb_name);
  636. } else {
  637. updateState('normal', "Connected (unencrypted) to: " + fb_name);
  638. }
  639. break;
  640. }
  641. //Util.Debug("<< init_msg");
  642. };
  643. /* Normal RFB/VNC server message handler */
  644. normal_msg = function() {
  645. //Util.Debug(">> normal_msg");
  646. var ret = true, msg_type, length,
  647. c, first_colour, num_colours, red, green, blue;
  648. if (FBU.rects > 0) {
  649. msg_type = 0;
  650. } else {
  651. msg_type = ws.rQshift8();
  652. }
  653. switch (msg_type) {
  654. case 0: // FramebufferUpdate
  655. ret = framebufferUpdate(); // false means need more data
  656. break;
  657. case 1: // SetColourMapEntries
  658. Util.Debug("SetColourMapEntries");
  659. ws.rQshift8(); // Padding
  660. first_colour = ws.rQshift16(); // First colour
  661. num_colours = ws.rQshift16();
  662. for (c=0; c < num_colours; c+=1) {
  663. red = ws.rQshift16();
  664. //Util.Debug("red before: " + red);
  665. red = parseInt(red / 256, 10);
  666. //Util.Debug("red after: " + red);
  667. green = parseInt(ws.rQshift16() / 256, 10);
  668. blue = parseInt(ws.rQshift16() / 256, 10);
  669. canvas.set_colourMap([red, green, blue], first_colour + c);
  670. }
  671. Util.Info("Registered " + num_colours + " colourMap entries");
  672. //Util.Debug("colourMap: " + canvas.get_colourMap());
  673. break;
  674. case 2: // Bell
  675. Util.Warn("Bell (unsupported)");
  676. break;
  677. case 3: // ServerCutText
  678. Util.Debug("ServerCutText");
  679. if (ws.rQwait("ServerCutText header", 7, 1)) { return false; }
  680. ws.rQshiftBytes(3); // Padding
  681. length = ws.rQshift32();
  682. if (ws.rQwait("ServerCutText", length, 8)) { return false; }
  683. conf.clipboardReceive(that, ws.rQshiftStr(length));
  684. break;
  685. default:
  686. fail("Disconnected: illegal server message type " + msg_type);
  687. Util.Debug("ws.rQslice(0,30):" + ws.rQslice(0,30));
  688. break;
  689. }
  690. //Util.Debug("<< normal_msg");
  691. return ret;
  692. };
  693. framebufferUpdate = function() {
  694. var now, hdr, fbu_rt_diff, ret = true;
  695. if (FBU.rects === 0) {
  696. //Util.Debug("New FBU: ws.rQslice(0,20): " + ws.rQslice(0,20));
  697. if (ws.rQwait("FBU header", 3)) {
  698. ws.rQunshift8(0); // FBU msg_type
  699. return false;
  700. }
  701. ws.rQshift8(); // padding
  702. FBU.rects = ws.rQshift16();
  703. //Util.Debug("FramebufferUpdate, rects:" + FBU.rects);
  704. FBU.bytes = 0;
  705. timing.cur_fbu = 0;
  706. if (timing.fbu_rt_start > 0) {
  707. now = (new Date()).getTime();
  708. Util.Info("First FBU latency: " + (now - timing.fbu_rt_start));
  709. }
  710. }
  711. while (FBU.rects > 0) {
  712. if (rfb_state !== "normal") {
  713. return false;
  714. }
  715. if (ws.rQwait("FBU", FBU.bytes)) { return false; }
  716. if (FBU.bytes === 0) {
  717. if (ws.rQwait("rect header", 12)) { return false; }
  718. /* New FramebufferUpdate */
  719. hdr = ws.rQshiftBytes(12);
  720. FBU.x = (hdr[0] << 8) + hdr[1];
  721. FBU.y = (hdr[2] << 8) + hdr[3];
  722. FBU.width = (hdr[4] << 8) + hdr[5];
  723. FBU.height = (hdr[6] << 8) + hdr[7];
  724. FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
  725. (hdr[10] << 8) + hdr[11], 10);
  726. if (encNames[FBU.encoding]) {
  727. // Debug:
  728. /*
  729. var msg = "FramebufferUpdate rects:" + FBU.rects;
  730. msg += " x: " + FBU.x + " y: " + FBU.y;
  731. msg += " width: " + FBU.width + " height: " + FBU.height;
  732. msg += " encoding:" + FBU.encoding;
  733. msg += "(" + encNames[FBU.encoding] + ")";
  734. msg += ", ws.rQlen(): " + ws.rQlen();
  735. Util.Debug(msg);
  736. */
  737. } else {
  738. fail("Disconnected: unsupported encoding " +
  739. FBU.encoding);
  740. return false;
  741. }
  742. }
  743. timing.last_fbu = (new Date()).getTime();
  744. ret = encHandlers[FBU.encoding]();
  745. now = (new Date()).getTime();
  746. timing.cur_fbu += (now - timing.last_fbu);
  747. if (ret) {
  748. encStats[FBU.encoding][0] += 1;
  749. encStats[FBU.encoding][1] += 1;
  750. }
  751. if (FBU.rects === 0) {
  752. if (((FBU.width === fb_width) &&
  753. (FBU.height === fb_height)) ||
  754. (timing.fbu_rt_start > 0)) {
  755. timing.full_fbu_total += timing.cur_fbu;
  756. timing.full_fbu_cnt += 1;
  757. Util.Info("Timing of full FBU, cur: " +
  758. timing.cur_fbu + ", total: " +
  759. timing.full_fbu_total + ", cnt: " +
  760. timing.full_fbu_cnt + ", avg: " +
  761. (timing.full_fbu_total /
  762. timing.full_fbu_cnt));
  763. }
  764. if (timing.fbu_rt_start > 0) {
  765. fbu_rt_diff = now - timing.fbu_rt_start;
  766. timing.fbu_rt_total += fbu_rt_diff;
  767. timing.fbu_rt_cnt += 1;
  768. Util.Info("full FBU round-trip, cur: " +
  769. fbu_rt_diff + ", total: " +
  770. timing.fbu_rt_total + ", cnt: " +
  771. timing.fbu_rt_cnt + ", avg: " +
  772. (timing.fbu_rt_total /
  773. timing.fbu_rt_cnt));
  774. timing.fbu_rt_start = 0;
  775. }
  776. }
  777. if (! ret) {
  778. return ret; // false ret means need more data
  779. }
  780. }
  781. return true; // We finished this FBU
  782. };
  783. //
  784. // FramebufferUpdate encodings
  785. //
  786. encHandlers.RAW = function display_raw() {
  787. //Util.Debug(">> display_raw (" + ws.rQlen() + " bytes)");
  788. var cur_y, cur_height;
  789. if (FBU.lines === 0) {
  790. FBU.lines = FBU.height;
  791. }
  792. FBU.bytes = FBU.width * fb_Bpp; // At least a line
  793. if (ws.rQwait("RAW", FBU.bytes)) { return false; }
  794. cur_y = FBU.y + (FBU.height - FBU.lines);
  795. cur_height = Math.min(FBU.lines,
  796. Math.floor(ws.rQlen()/(FBU.width * fb_Bpp)));
  797. canvas.blitImage(FBU.x, cur_y, FBU.width, cur_height,
  798. ws.get_rQ(), ws.get_rQi());
  799. ws.rQshiftBytes(FBU.width * cur_height * fb_Bpp);
  800. FBU.lines -= cur_height;
  801. if (FBU.lines > 0) {
  802. FBU.bytes = FBU.width * fb_Bpp; // At least another line
  803. } else {
  804. FBU.rects -= 1;
  805. FBU.bytes = 0;
  806. }
  807. //Util.Debug("<< display_raw (" + ws.rQlen() + " bytes)");
  808. return true;
  809. };
  810. encHandlers.COPYRECT = function display_copy_rect() {
  811. //Util.Debug(">> display_copy_rect");
  812. var old_x, old_y;
  813. if (ws.rQwait("COPYRECT", 4)) { return false; }
  814. old_x = ws.rQshift16();
  815. old_y = ws.rQshift16();
  816. canvas.copyImage(old_x, old_y, FBU.x, FBU.y, FBU.width, FBU.height);
  817. FBU.rects -= 1;
  818. FBU.bytes = 0;
  819. return true;
  820. };
  821. encHandlers.RRE = function display_rre() {
  822. //Util.Debug(">> display_rre (" + ws.rQlen() + " bytes)");
  823. var color, x, y, width, height, chunk;
  824. if (FBU.subrects === 0) {
  825. if (ws.rQwait("RRE", 4+fb_Bpp)) { return false; }
  826. FBU.subrects = ws.rQshift32();
  827. color = ws.rQshiftBytes(fb_Bpp); // Background
  828. canvas.fillRect(FBU.x, FBU.y, FBU.width, FBU.height, color);
  829. }
  830. while ((FBU.subrects > 0) && (ws.rQlen() >= (fb_Bpp + 8))) {
  831. color = ws.rQshiftBytes(fb_Bpp);
  832. x = ws.rQshift16();
  833. y = ws.rQshift16();
  834. width = ws.rQshift16();
  835. height = ws.rQshift16();
  836. canvas.fillRect(FBU.x + x, FBU.y + y, width, height, color);
  837. FBU.subrects -= 1;
  838. }
  839. //Util.Debug(" display_rre: rects: " + FBU.rects +
  840. // ", FBU.subrects: " + FBU.subrects);
  841. if (FBU.subrects > 0) {
  842. chunk = Math.min(rre_chunk_sz, FBU.subrects);
  843. FBU.bytes = (fb_Bpp + 8) * chunk;
  844. } else {
  845. FBU.rects -= 1;
  846. FBU.bytes = 0;
  847. }
  848. //Util.Debug("<< display_rre, FBU.bytes: " + FBU.bytes);
  849. return true;
  850. };
  851. encHandlers.HEXTILE = function display_hextile() {
  852. //Util.Debug(">> display_hextile");
  853. var subencoding, subrects, tile, color, cur_tile,
  854. tile_x, x, w, tile_y, y, h, xy, s, sx, sy, wh, sw, sh,
  855. rQ = ws.get_rQ(), rQi = ws.get_rQi();
  856. if (FBU.tiles === 0) {
  857. FBU.tiles_x = Math.ceil(FBU.width/16);
  858. FBU.tiles_y = Math.ceil(FBU.height/16);
  859. FBU.total_tiles = FBU.tiles_x * FBU.tiles_y;
  860. FBU.tiles = FBU.total_tiles;
  861. }
  862. /* FBU.bytes comes in as 1, ws.rQlen() at least 1 */
  863. while (FBU.tiles > 0) {
  864. FBU.bytes = 1;
  865. if (ws.rQwait("HEXTILE subencoding", FBU.bytes)) { return false; }
  866. subencoding = rQ[rQi]; // Peek
  867. if (subencoding > 30) { // Raw
  868. fail("Disconnected: illegal hextile subencoding " + subencoding);
  869. //Util.Debug("ws.rQslice(0,30):" + ws.rQslice(0,30));
  870. return false;
  871. }
  872. subrects = 0;
  873. cur_tile = FBU.total_tiles - FBU.tiles;
  874. tile_x = cur_tile % FBU.tiles_x;
  875. tile_y = Math.floor(cur_tile / FBU.tiles_x);
  876. x = FBU.x + tile_x * 16;
  877. y = FBU.y + tile_y * 16;
  878. w = Math.min(16, (FBU.x + FBU.width) - x);
  879. h = Math.min(16, (FBU.y + FBU.height) - y);
  880. /* Figure out how much we are expecting */
  881. if (subencoding & 0x01) { // Raw
  882. //Util.Debug(" Raw subencoding");
  883. FBU.bytes += w * h * fb_Bpp;
  884. } else {
  885. if (subencoding & 0x02) { // Background
  886. FBU.bytes += fb_Bpp;
  887. }
  888. if (subencoding & 0x04) { // Foreground
  889. FBU.bytes += fb_Bpp;
  890. }
  891. if (subencoding & 0x08) { // AnySubrects
  892. FBU.bytes += 1; // Since we aren't shifting it off
  893. if (ws.rQwait("hextile subrects header", FBU.bytes)) { return false; }
  894. subrects = rQ[rQi + FBU.bytes-1]; // Peek
  895. if (subencoding & 0x10) { // SubrectsColoured
  896. FBU.bytes += subrects * (fb_Bpp + 2);
  897. } else {
  898. FBU.bytes += subrects * 2;
  899. }
  900. }
  901. }
  902. /*
  903. Util.Debug(" tile:" + cur_tile + "/" + (FBU.total_tiles - 1) +
  904. " (" + tile_x + "," + tile_y + ")" +
  905. " [" + x + "," + y + "]@" + w + "x" + h +
  906. ", subenc:" + subencoding +
  907. "(last: " + FBU.lastsubencoding + "), subrects:" +
  908. subrects +
  909. ", ws.rQlen():" + ws.rQlen() + ", FBU.bytes:" + FBU.bytes +
  910. " last:" + ws.rQslice(FBU.bytes-10, FBU.bytes) +
  911. " next:" + ws.rQslice(FBU.bytes-1, FBU.bytes+10));
  912. */
  913. if (ws.rQwait("hextile", FBU.bytes)) { return false; }
  914. /* We know the encoding and have a whole tile */
  915. FBU.subencoding = rQ[rQi];
  916. rQi += 1;
  917. if (FBU.subencoding === 0) {
  918. if (FBU.lastsubencoding & 0x01) {
  919. /* Weird: ignore blanks after RAW */
  920. Util.Debug(" Ignoring blank after RAW");
  921. } else {
  922. canvas.fillRect(x, y, w, h, FBU.background);
  923. }
  924. } else if (FBU.subencoding & 0x01) { // Raw
  925. canvas.blitImage(x, y, w, h, rQ, rQi);
  926. rQi += FBU.bytes - 1;
  927. } else {
  928. if (FBU.subencoding & 0x02) { // Background
  929. FBU.background = rQ.slice(rQi, rQi + fb_Bpp);
  930. rQi += fb_Bpp;
  931. }
  932. if (FBU.subencoding & 0x04) { // Foreground
  933. FBU.foreground = rQ.slice(rQi, rQi + fb_Bpp);
  934. rQi += fb_Bpp;
  935. }
  936. tile = canvas.getTile(x, y, w, h, FBU.background);
  937. if (FBU.subencoding & 0x08) { // AnySubrects
  938. subrects = rQ[rQi];
  939. rQi += 1;
  940. for (s = 0; s < subrects; s += 1) {
  941. if (FBU.subencoding & 0x10) { // SubrectsColoured
  942. color = rQ.slice(rQi, rQi + fb_Bpp);
  943. rQi += fb_Bpp;
  944. } else {
  945. color = FBU.foreground;
  946. }
  947. xy = rQ[rQi];
  948. rQi += 1;
  949. sx = (xy >> 4);
  950. sy = (xy & 0x0f);
  951. wh = rQ[rQi];
  952. rQi += 1;
  953. sw = (wh >> 4) + 1;
  954. sh = (wh & 0x0f) + 1;
  955. canvas.setSubTile(tile, sx, sy, sw, sh, color);
  956. }
  957. }
  958. canvas.putTile(tile);
  959. }
  960. ws.set_rQi(rQi);
  961. FBU.lastsubencoding = FBU.subencoding;
  962. FBU.bytes = 0;
  963. FBU.tiles -= 1;
  964. }
  965. if (FBU.tiles === 0) {
  966. FBU.rects -= 1;
  967. }
  968. //Util.Debug("<< display_hextile");
  969. return true;
  970. };
  971. encHandlers.TIGHT_PNG = function display_tight_png() {
  972. //Util.Debug(">> display_tight_png");
  973. var ctl, cmode, clength, getCLength, color, img;
  974. //Util.Debug(" FBU.rects: " + FBU.rects);
  975. //Util.Debug(" starting ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  976. FBU.bytes = 1; // compression-control byte
  977. if (ws.rQwait("TIGHT compression-control", FBU.bytes)) { return false; }
  978. // Get 'compact length' header and data size
  979. getCLength = function (arr) {
  980. var header = 1, data = 0;
  981. data += arr[0] & 0x7f;
  982. if (arr[0] & 0x80) {
  983. header += 1;
  984. data += (arr[1] & 0x7f) << 7;
  985. if (arr[1] & 0x80) {
  986. header += 1;
  987. data += arr[2] << 14;
  988. }
  989. }
  990. return [header, data];
  991. };
  992. ctl = ws.rQpeek8();
  993. switch (ctl >> 4) {
  994. case 0x08: cmode = "fill"; break;
  995. case 0x09: cmode = "jpeg"; break;
  996. case 0x0A: cmode = "png"; break;
  997. default: throw("Illegal basic compression received, ctl: " + ctl);
  998. }
  999. switch (cmode) {
  1000. // fill uses fb_depth because TPIXELs drop the padding byte
  1001. case "fill": FBU.bytes += fb_depth; break; // TPIXEL
  1002. case "jpeg": FBU.bytes += 3; break; // max clength
  1003. case "png": FBU.bytes += 3; break; // max clength
  1004. }
  1005. if (ws.rQwait("TIGHT " + cmode, FBU.bytes)) { return false; }
  1006. //Util.Debug(" ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  1007. //Util.Debug(" cmode: " + cmode);
  1008. // Determine FBU.bytes
  1009. switch (cmode) {
  1010. case "fill":
  1011. ws.rQshift8(); // shift off ctl
  1012. color = ws.rQshiftBytes(fb_depth);
  1013. canvas.fillRect(FBU.x, FBU.y, FBU.width, FBU.height, color);
  1014. break;
  1015. case "jpeg":
  1016. case "png":
  1017. clength = getCLength(ws.rQslice(1, 4));
  1018. FBU.bytes = 1 + clength[0] + clength[1]; // ctl + clength size + jpeg-data
  1019. if (ws.rQwait("TIGHT " + cmode, FBU.bytes)) { return false; }
  1020. // We have everything, render it
  1021. //Util.Debug(" png, ws.rQlen(): " + ws.rQlen() + ", clength[0]: " + clength[0] + ", clength[1]: " + clength[1]);
  1022. ws.rQshiftBytes(1 + clength[0]); // shift off ctl + compact length
  1023. img = new Image();
  1024. img.onload = scan_tight_imgQ;
  1025. FBU.imgQ.push([img, FBU.x, FBU.y]);
  1026. img.src = "data:image/" + cmode +
  1027. extract_data_uri(ws.rQshiftBytes(clength[1]));
  1028. img = null;
  1029. break;
  1030. }
  1031. FBU.bytes = 0;
  1032. FBU.rects -= 1;
  1033. //Util.Debug(" ending ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  1034. //Util.Debug("<< display_tight_png");
  1035. return true;
  1036. };
  1037. extract_data_uri = function(arr) {
  1038. //var i, stra = [];
  1039. //for (i=0; i< arr.length; i += 1) {
  1040. // stra.push(String.fromCharCode(arr[i]));
  1041. //}
  1042. //return "," + escape(stra.join(''));
  1043. return ";base64," + Base64.encode(arr);
  1044. };
  1045. scan_tight_imgQ = function() {
  1046. var img, imgQ, ctx;
  1047. ctx = canvas.getContext();
  1048. if (rfb_state === 'normal') {
  1049. imgQ = FBU.imgQ;
  1050. while ((imgQ.length > 0) && (imgQ[0][0].complete)) {
  1051. img = imgQ.shift();
  1052. ctx.drawImage(img[0], img[1], img[2]);
  1053. }
  1054. setTimeout(scan_tight_imgQ, scan_imgQ_rate);
  1055. }
  1056. };
  1057. encHandlers.DesktopSize = function set_desktopsize() {
  1058. Util.Debug(">> set_desktopsize");
  1059. fb_width = FBU.width;
  1060. fb_height = FBU.height;
  1061. canvas.clear();
  1062. canvas.resize(fb_width, fb_height);
  1063. timing.fbu_rt_start = (new Date()).getTime();
  1064. // Send a new non-incremental request
  1065. ws.send(fbUpdateRequest(0));
  1066. FBU.bytes = 0;
  1067. FBU.rects -= 1;
  1068. Util.Debug("<< set_desktopsize");
  1069. return true;
  1070. };
  1071. encHandlers.Cursor = function set_cursor() {
  1072. var x, y, w, h, pixelslength, masklength;
  1073. //Util.Debug(">> set_cursor");
  1074. x = FBU.x; // hotspot-x
  1075. y = FBU.y; // hotspot-y
  1076. w = FBU.width;
  1077. h = FBU.height;
  1078. pixelslength = w * h * fb_Bpp;
  1079. masklength = Math.floor((w + 7) / 8) * h;
  1080. FBU.bytes = pixelslength + masklength;
  1081. if (ws.rQwait("cursor encoding", FBU.bytes)) { return false; }
  1082. //Util.Debug(" set_cursor, x: " + x + ", y: " + y + ", w: " + w + ", h: " + h);
  1083. canvas.changeCursor(ws.rQshiftBytes(pixelslength),
  1084. ws.rQshiftBytes(masklength),
  1085. x, y, w, h);
  1086. FBU.bytes = 0;
  1087. FBU.rects -= 1;
  1088. //Util.Debug("<< set_cursor");
  1089. return true;
  1090. };
  1091. encHandlers.JPEG_quality_lo = function set_jpeg_quality() {
  1092. Util.Error("Server sent jpeg_quality pseudo-encoding");
  1093. };
  1094. encHandlers.compress_lo = function set_compress_level() {
  1095. Util.Error("Server sent compress level pseudo-encoding");
  1096. };
  1097. /*
  1098. * Client message routines
  1099. */
  1100. pixelFormat = function() {
  1101. //Util.Debug(">> pixelFormat");
  1102. var arr;
  1103. arr = [0]; // msg-type
  1104. arr.push8(0); // padding
  1105. arr.push8(0); // padding
  1106. arr.push8(0); // padding
  1107. arr.push8(fb_Bpp * 8); // bits-per-pixel
  1108. arr.push8(fb_depth * 8); // depth
  1109. arr.push8(0); // little-endian
  1110. arr.push8(conf.true_color ? 1 : 0); // true-color
  1111. arr.push16(255); // red-max
  1112. arr.push16(255); // green-max
  1113. arr.push16(255); // blue-max
  1114. arr.push8(0); // red-shift
  1115. arr.push8(8); // green-shift
  1116. arr.push8(16); // blue-shift
  1117. arr.push8(0); // padding
  1118. arr.push8(0); // padding
  1119. arr.push8(0); // padding
  1120. //Util.Debug("<< pixelFormat");
  1121. return arr;
  1122. };
  1123. clientEncodings = function() {
  1124. //Util.Debug(">> clientEncodings");
  1125. var arr, i, encList = [];
  1126. for (i=0; i<encodings.length; i += 1) {
  1127. if ((encodings[i][0] === "Cursor") &&
  1128. (! conf.local_cursor)) {
  1129. Util.Debug("Skipping Cursor pseudo-encoding");
  1130. } else {
  1131. //Util.Debug("Adding encoding: " + encodings[i][0]);
  1132. encList.push(encodings[i][1]);
  1133. }
  1134. }
  1135. arr = [2]; // msg-type
  1136. arr.push8(0); // padding
  1137. arr.push16(encList.length); // encoding count
  1138. for (i=0; i < encList.length; i += 1) {
  1139. arr.push32(encList[i]);
  1140. }
  1141. //Util.Debug("<< clientEncodings: " + arr);
  1142. return arr;
  1143. };
  1144. fbUpdateRequest = function(incremental, x, y, xw, yw) {
  1145. //Util.Debug(">> fbUpdateRequest");
  1146. if (!x) { x = 0; }
  1147. if (!y) { y = 0; }
  1148. if (!xw) { xw = fb_width; }
  1149. if (!yw) { yw = fb_height; }
  1150. var arr;
  1151. arr = [3]; // msg-type
  1152. arr.push8(incremental);
  1153. arr.push16(x);
  1154. arr.push16(y);
  1155. arr.push16(xw);
  1156. arr.push16(yw);
  1157. //Util.Debug("<< fbUpdateRequest");
  1158. return arr;
  1159. };
  1160. keyEvent = function(keysym, down) {
  1161. //Util.Debug(">> keyEvent, keysym: " + keysym + ", down: " + down);
  1162. var arr;
  1163. arr = [4]; // msg-type
  1164. arr.push8(down);
  1165. arr.push16(0);
  1166. arr.push32(keysym);
  1167. //Util.Debug("<< keyEvent");
  1168. return arr;
  1169. };
  1170. pointerEvent = function(x, y) {
  1171. //Util.Debug(">> pointerEvent, x,y: " + x + "," + y +
  1172. // " , mask: " + mouse_buttonMask);
  1173. var arr;
  1174. arr = [5]; // msg-type
  1175. arr.push8(mouse_buttonMask);
  1176. arr.push16(x);
  1177. arr.push16(y);
  1178. //Util.Debug("<< pointerEvent");
  1179. return arr;
  1180. };
  1181. clientCutText = function(text) {
  1182. //Util.Debug(">> clientCutText");
  1183. var arr, i, n;
  1184. arr = [6]; // msg-type
  1185. arr.push8(0); // padding
  1186. arr.push8(0); // padding
  1187. arr.push8(0); // padding
  1188. arr.push32(text.length);
  1189. n = text.length;
  1190. for (i=0; i < n; i+=1) {
  1191. arr.push(text.charCodeAt(i));
  1192. }
  1193. //Util.Debug("<< clientCutText:" + arr);
  1194. return arr;
  1195. };
  1196. //
  1197. // Public API interface functions
  1198. //
  1199. that.connect = function(host, port, password) {
  1200. //Util.Debug(">> connect");
  1201. rfb_host = host;
  1202. rfb_port = port;
  1203. rfb_password = (password !== undefined) ? password : "";
  1204. if ((!rfb_host) || (!rfb_port)) {
  1205. return fail("Must set host and port");
  1206. }
  1207. updateState('connect');
  1208. //Util.Debug("<< connect");
  1209. };
  1210. that.disconnect = function() {
  1211. //Util.Debug(">> disconnect");
  1212. updateState('disconnect', 'Disconnecting');
  1213. //Util.Debug("<< disconnect");
  1214. };
  1215. that.sendPassword = function(passwd) {
  1216. rfb_password = passwd;
  1217. rfb_state = "Authentication";
  1218. setTimeout(init_msg, 1);
  1219. };
  1220. that.sendCtrlAltDel = function() {
  1221. if (rfb_state !== "normal") { return false; }
  1222. Util.Info("Sending Ctrl-Alt-Del");
  1223. var arr = [];
  1224. arr = arr.concat(keyEvent(0xFFE3, 1)); // Control
  1225. arr = arr.concat(keyEvent(0xFFE9, 1)); // Alt
  1226. arr = arr.concat(keyEvent(0xFFFF, 1)); // Delete
  1227. arr = arr.concat(keyEvent(0xFFFF, 0)); // Delete
  1228. arr = arr.concat(keyEvent(0xFFE9, 0)); // Alt
  1229. arr = arr.concat(keyEvent(0xFFE3, 0)); // Control
  1230. arr = arr.concat(fbUpdateRequest(1));
  1231. ws.send(arr);
  1232. };
  1233. // Send a key press. If 'down' is not specified then send a down key
  1234. // followed by an up key.
  1235. that.sendKey = function(code, down) {
  1236. if (rfb_state !== "normal") { return false; }
  1237. var arr = [];
  1238. if (typeof down !== 'undefined') {
  1239. Util.Info("Sending key code (" + (down ? "down" : "up") + "): " + code);
  1240. arr = arr.concat(keyEvent(code, down ? 1 : 0));
  1241. } else {
  1242. Util.Info("Sending key code (down + up): " + code);
  1243. arr = arr.concat(keyEvent(code, 1));
  1244. arr = arr.concat(keyEvent(code, 0));
  1245. }
  1246. arr = arr.concat(fbUpdateRequest(1));
  1247. ws.send(arr);
  1248. };
  1249. that.clipboardPasteFrom = function(text) {
  1250. if (rfb_state !== "normal") { return; }
  1251. //Util.Debug(">> clipboardPasteFrom: " + text.substr(0,40) + "...");
  1252. ws.send(clientCutText(text));
  1253. //Util.Debug("<< clipboardPasteFrom");
  1254. };
  1255. that.testMode = function(override_send) {
  1256. // Overridable internal functions for testing
  1257. test_mode = true;
  1258. // TODO figure out what to do here
  1259. ws.send = override_send;
  1260. that.recv_message = ws.recv_message; // Expose it
  1261. checkEvents = function () { /* Stub Out */ };
  1262. that.connect = function(host, port, password) {
  1263. rfb_host = host;
  1264. rfb_port = port;
  1265. rfb_password = password;
  1266. updateState('ProtocolVersion', "Starting VNC handshake");
  1267. };
  1268. };
  1269. return constructor(); // Return the public API interface
  1270. } // End of RFB()