rfb.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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, 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. if ((Util.get_logging() !== 'debug') ||
  294. (state === 'loaded')) {
  295. // Show noVNC logo on load and when disconnected if
  296. // debug is off
  297. if (noVNC_logo) {
  298. canvas.resize(noVNC_logo.width, noVNC_logo.height);
  299. canvas.blitStringImage(noVNC_logo.data, 0, 0);
  300. }
  301. }
  302. }
  303. ws.close();
  304. }
  305. if (oldstate === 'fatal') {
  306. Util.Error("Fatal error, cannot continue");
  307. }
  308. if ((state === 'failed') || (state === 'fatal')) {
  309. func = Util.Error;
  310. } else {
  311. func = Util.Warn;
  312. }
  313. if ((oldstate === 'failed') && (state === 'disconnected')) {
  314. // Do disconnect action, but stay in failed state.
  315. rfb_state = 'failed';
  316. } else {
  317. rfb_state = state;
  318. }
  319. cmsg = typeof(statusMsg) !== 'undefined' ? (" Msg: " + statusMsg) : "";
  320. func("New state '" + rfb_state + "', was '" + oldstate + "'." + cmsg);
  321. if (connTimer && (rfb_state !== 'connect')) {
  322. Util.Debug("Clearing connect timer");
  323. clearInterval(connTimer);
  324. connTimer = null;
  325. }
  326. if (disconnTimer && (rfb_state !== 'disconnect')) {
  327. Util.Debug("Clearing disconnect timer");
  328. clearInterval(disconnTimer);
  329. disconnTimer = null;
  330. }
  331. switch (state) {
  332. case 'normal':
  333. if ((oldstate === 'disconnected') || (oldstate === 'failed')) {
  334. Util.Error("Invalid transition from 'disconnected' or 'failed' to 'normal'");
  335. }
  336. break;
  337. case 'connect':
  338. connTimer = setTimeout(function () {
  339. fail("Connect timeout");
  340. }, conf.connectTimeout * 1000);
  341. init_vars();
  342. connect();
  343. // WebSocket.onopen transitions to 'ProtocolVersion'
  344. break;
  345. case 'disconnect':
  346. if (! test_mode) {
  347. disconnTimer = setTimeout(function () {
  348. fail("Disconnect timeout");
  349. }, conf.disconnectTimeout * 1000);
  350. }
  351. print_stats();
  352. // WebSocket.onclose transitions to 'disconnected'
  353. break;
  354. case 'failed':
  355. if (oldstate === 'disconnected') {
  356. Util.Error("Invalid transition from 'disconnected' to 'failed'");
  357. }
  358. if (oldstate === 'normal') {
  359. Util.Error("Error while connected.");
  360. }
  361. if (oldstate === 'init') {
  362. Util.Error("Error while initializing.");
  363. }
  364. // Make sure we transition to disconnected
  365. setTimeout(function() { updateState('disconnected'); }, 50);
  366. break;
  367. default:
  368. // No state change action to take
  369. }
  370. if ((oldstate === 'failed') && (state === 'disconnected')) {
  371. // Leave the failed message
  372. conf.updateState(that, state, oldstate);
  373. } else {
  374. conf.updateState(that, state, oldstate, statusMsg);
  375. }
  376. };
  377. function fail(msg) {
  378. updateState('failed', msg);
  379. return false;
  380. }
  381. function handle_message() {
  382. //Util.Debug(">> handle_message ws.rQlen(): " + ws.rQlen());
  383. //Util.Debug("ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  384. if (ws.rQlen() === 0) {
  385. Util.Warn("handle_message called on empty receive queue");
  386. return;
  387. }
  388. switch (rfb_state) {
  389. case 'disconnected':
  390. case 'failed':
  391. Util.Error("Got data while disconnected");
  392. break;
  393. case 'normal':
  394. if (normal_msg() && ws.rQlen() > 0) {
  395. // true means we can continue processing
  396. // Give other events a chance to run
  397. if (msgTimer === null) {
  398. Util.Debug("More data to process, creating timer");
  399. msgTimer = setTimeout(function () {
  400. msgTimer = null;
  401. handle_message();
  402. }, 10);
  403. } else {
  404. Util.Debug("More data to process, existing timer");
  405. }
  406. }
  407. break;
  408. default:
  409. init_msg();
  410. break;
  411. }
  412. }
  413. function genDES(password, challenge) {
  414. var i, passwd = [], des;
  415. for (i=0; i < password.length; i += 1) {
  416. passwd.push(password.charCodeAt(i));
  417. }
  418. return (new DES(passwd)).encrypt(challenge);
  419. }
  420. function flushClient() {
  421. if (mouse_arr.length > 0) {
  422. //send(mouse_arr.concat(fbUpdateRequest(1)));
  423. ws.send(mouse_arr);
  424. setTimeout(function() {
  425. ws.send(fbUpdateRequest(1));
  426. }, 50);
  427. mouse_arr = [];
  428. return true;
  429. } else {
  430. return false;
  431. }
  432. }
  433. // overridable for testing
  434. checkEvents = function() {
  435. var now;
  436. if (rfb_state === 'normal') {
  437. if (! flushClient()) {
  438. now = new Date().getTime();
  439. if (now > last_req_time + conf.fbu_req_rate) {
  440. last_req_time = now;
  441. ws.send(fbUpdateRequest(1));
  442. }
  443. }
  444. }
  445. setTimeout(checkEvents, conf.check_rate);
  446. };
  447. function keyPress(keysym, down) {
  448. var arr;
  449. arr = keyEvent(keysym, down);
  450. arr = arr.concat(fbUpdateRequest(1));
  451. ws.send(arr);
  452. }
  453. function mouseButton(x, y, down, bmask) {
  454. if (down) {
  455. mouse_buttonMask |= bmask;
  456. } else {
  457. mouse_buttonMask ^= bmask;
  458. }
  459. mouse_arr = mouse_arr.concat( pointerEvent(x, y) );
  460. flushClient();
  461. }
  462. function mouseMove(x, y) {
  463. //Util.Debug('>> mouseMove ' + x + "," + y);
  464. mouse_arr = mouse_arr.concat( pointerEvent(x, y) );
  465. }
  466. //
  467. // Server message handlers
  468. //
  469. // RFB/VNC initialisation message handler
  470. init_msg = function() {
  471. //Util.Debug(">> init_msg [rfb_state '" + rfb_state + "']");
  472. var strlen, reason, length, sversion, cversion,
  473. i, types, num_types, challenge, response, bpp, depth,
  474. big_endian, true_color, name_length;
  475. //Util.Debug("ws.rQ (" + ws.rQlen() + ") " + ws.rQslice(0));
  476. switch (rfb_state) {
  477. case 'ProtocolVersion' :
  478. if (ws.rQlen() < 12) {
  479. return fail("Incomplete protocol version");
  480. }
  481. sversion = ws.rQshiftStr(12).substr(4,7);
  482. Util.Info("Server ProtocolVersion: " + sversion);
  483. switch (sversion) {
  484. case "003.003": rfb_version = 3.3; break;
  485. case "003.006": rfb_version = 3.3; break; // UltraVNC
  486. case "003.007": rfb_version = 3.7; break;
  487. case "003.008": rfb_version = 3.8; break;
  488. default:
  489. return fail("Invalid server version " + sversion);
  490. }
  491. if (rfb_version > rfb_max_version) {
  492. rfb_version = rfb_max_version;
  493. }
  494. if (! test_mode) {
  495. sendTimer = setInterval(function() {
  496. // Send updates either at a rate of one update
  497. // every 50ms, or whatever slower rate the network
  498. // can handle.
  499. ws.flush();
  500. }, 50);
  501. }
  502. cversion = "00" + parseInt(rfb_version,10) +
  503. ".00" + ((rfb_version * 10) % 10);
  504. ws.send_string("RFB " + cversion + "\n");
  505. updateState('Security', "Sent ProtocolVersion: " + cversion);
  506. break;
  507. case 'Security' :
  508. if (rfb_version >= 3.7) {
  509. // Server sends supported list, client decides
  510. num_types = ws.rQshift8();
  511. if (ws.rQwait("security type", num_types, 1)) { return false; }
  512. if (num_types === 0) {
  513. strlen = ws.rQshift32();
  514. reason = ws.rQshiftStr(strlen);
  515. return fail("Security failure: " + reason);
  516. }
  517. rfb_auth_scheme = 0;
  518. types = ws.rQshiftBytes(num_types);
  519. Util.Debug("Server security types: " + types);
  520. for (i=0; i < types.length; i+=1) {
  521. if ((types[i] > rfb_auth_scheme) && (types[i] < 3)) {
  522. rfb_auth_scheme = types[i];
  523. }
  524. }
  525. if (rfb_auth_scheme === 0) {
  526. return fail("Unsupported security types: " + types);
  527. }
  528. ws.send([rfb_auth_scheme]);
  529. } else {
  530. // Server decides
  531. if (ws.rQwait("security scheme", 4)) { return false; }
  532. rfb_auth_scheme = ws.rQshift32();
  533. }
  534. updateState('Authentication',
  535. "Authenticating using scheme: " + rfb_auth_scheme);
  536. init_msg(); // Recursive fallthrough (workaround JSLint complaint)
  537. break;
  538. // Triggered by fallthough, not by server message
  539. case 'Authentication' :
  540. //Util.Debug("Security auth scheme: " + rfb_auth_scheme);
  541. switch (rfb_auth_scheme) {
  542. case 0: // connection failed
  543. if (ws.rQwait("auth reason", 4)) { return false; }
  544. strlen = ws.rQshift32();
  545. reason = ws.rQshiftStr(strlen);
  546. return fail("Auth failure: " + reason);
  547. case 1: // no authentication
  548. if (rfb_version >= 3.8) {
  549. updateState('SecurityResult');
  550. return;
  551. } else {
  552. // Fall through to ClientInitialisation
  553. }
  554. break;
  555. case 2: // VNC authentication
  556. if (rfb_password.length === 0) {
  557. updateState('password', "Password Required");
  558. return;
  559. }
  560. if (ws.rQwait("auth challenge", 16)) { return false; }
  561. challenge = ws.rQshiftBytes(16);
  562. //Util.Debug("Password: " + rfb_password);
  563. //Util.Debug("Challenge: " + challenge +
  564. // " (" + challenge.length + ")");
  565. response = genDES(rfb_password, challenge);
  566. //Util.Debug("Response: " + response +
  567. // " (" + response.length + ")");
  568. //Util.Debug("Sending DES encrypted auth response");
  569. ws.send(response);
  570. updateState('SecurityResult');
  571. return;
  572. default:
  573. fail("Unsupported auth scheme: " + rfb_auth_scheme);
  574. return;
  575. }
  576. updateState('ClientInitialisation', "No auth required");
  577. init_msg(); // Recursive fallthrough (workaround JSLint complaint)
  578. break;
  579. case 'SecurityResult' :
  580. if (ws.rQwait("VNC auth response ", 4)) { return false; }
  581. switch (ws.rQshift32()) {
  582. case 0: // OK
  583. // Fall through to ClientInitialisation
  584. break;
  585. case 1: // failed
  586. if (rfb_version >= 3.8) {
  587. length = ws.rQshift32();
  588. if (ws.rQwait("SecurityResult reason", length, 8)) {
  589. return false;
  590. }
  591. reason = ws.rQshiftStr(length);
  592. fail(reason);
  593. } else {
  594. fail("Authentication failed");
  595. }
  596. return;
  597. case 2: // too-many
  598. return fail("Too many auth attempts");
  599. }
  600. updateState('ClientInitialisation', "Authentication OK");
  601. init_msg(); // Recursive fallthrough (workaround JSLint complaint)
  602. break;
  603. // Triggered by fallthough, not by server message
  604. case 'ClientInitialisation' :
  605. ws.send([conf.shared ? 1 : 0]); // ClientInitialisation
  606. updateState('ServerInitialisation', "Authentication OK");
  607. break;
  608. case 'ServerInitialisation' :
  609. if (ws.rQwait("server initialization", 24)) { return false; }
  610. /* Screen size */
  611. fb_width = ws.rQshift16();
  612. fb_height = ws.rQshift16();
  613. /* PIXEL_FORMAT */
  614. bpp = ws.rQshift8();
  615. depth = ws.rQshift8();
  616. big_endian = ws.rQshift8();
  617. true_color = ws.rQshift8();
  618. Util.Info("Screen: " + fb_width + "x" + fb_height +
  619. ", bpp: " + bpp + ", depth: " + depth +
  620. ", big_endian: " + big_endian +
  621. ", true_color: " + true_color);
  622. /* Connection name/title */
  623. ws.rQshiftStr(12);
  624. name_length = ws.rQshift32();
  625. fb_name = ws.rQshiftStr(name_length);
  626. canvas.resize(fb_width, fb_height, conf.true_color);
  627. canvas.start(keyPress, mouseButton, mouseMove);
  628. if (conf.true_color) {
  629. fb_Bpp = 4;
  630. fb_depth = 3;
  631. } else {
  632. fb_Bpp = 1;
  633. fb_depth = 1;
  634. }
  635. response = pixelFormat();
  636. response = response.concat(clientEncodings());
  637. response = response.concat(fbUpdateRequest(0));
  638. timing.fbu_rt_start = (new Date()).getTime();
  639. ws.send(response);
  640. /* Start pushing/polling */
  641. setTimeout(checkEvents, conf.check_rate);
  642. setTimeout(scan_tight_imgQ, scan_imgQ_rate);
  643. if (conf.encrypt) {
  644. updateState('normal', "Connected (encrypted) to: " + fb_name);
  645. } else {
  646. updateState('normal', "Connected (unencrypted) to: " + fb_name);
  647. }
  648. break;
  649. }
  650. //Util.Debug("<< init_msg");
  651. };
  652. /* Normal RFB/VNC server message handler */
  653. normal_msg = function() {
  654. //Util.Debug(">> normal_msg");
  655. var ret = true, msg_type, length,
  656. c, first_colour, num_colours, red, green, blue;
  657. if (FBU.rects > 0) {
  658. msg_type = 0;
  659. } else {
  660. msg_type = ws.rQshift8();
  661. }
  662. switch (msg_type) {
  663. case 0: // FramebufferUpdate
  664. ret = framebufferUpdate(); // false means need more data
  665. break;
  666. case 1: // SetColourMapEntries
  667. Util.Debug("SetColourMapEntries");
  668. ws.rQshift8(); // Padding
  669. first_colour = ws.rQshift16(); // First colour
  670. num_colours = ws.rQshift16();
  671. for (c=0; c < num_colours; c+=1) {
  672. red = ws.rQshift16();
  673. //Util.Debug("red before: " + red);
  674. red = parseInt(red / 256, 10);
  675. //Util.Debug("red after: " + red);
  676. green = parseInt(ws.rQshift16() / 256, 10);
  677. blue = parseInt(ws.rQshift16() / 256, 10);
  678. canvas.set_colourMap([red, green, blue], first_colour + c);
  679. }
  680. Util.Info("Registered " + num_colours + " colourMap entries");
  681. //Util.Debug("colourMap: " + canvas.get_colourMap());
  682. break;
  683. case 2: // Bell
  684. Util.Warn("Bell (unsupported)");
  685. break;
  686. case 3: // ServerCutText
  687. Util.Debug("ServerCutText");
  688. if (ws.rQwait("ServerCutText header", 7, 1)) { return false; }
  689. ws.rQshiftBytes(3); // Padding
  690. length = ws.rQshift32();
  691. if (ws.rQwait("ServerCutText", length, 8)) { return false; }
  692. conf.clipboardReceive(that, ws.rQshiftStr(length));
  693. break;
  694. default:
  695. fail("Disconnected: illegal server message type " + msg_type);
  696. Util.Debug("ws.rQslice(0,30):" + ws.rQslice(0,30));
  697. break;
  698. }
  699. //Util.Debug("<< normal_msg");
  700. return ret;
  701. };
  702. framebufferUpdate = function() {
  703. var now, hdr, fbu_rt_diff, ret = true;
  704. if (FBU.rects === 0) {
  705. //Util.Debug("New FBU: ws.rQslice(0,20): " + ws.rQslice(0,20));
  706. if (ws.rQwait("FBU header", 3)) {
  707. ws.rQunshift8(0); // FBU msg_type
  708. return false;
  709. }
  710. ws.rQshift8(); // padding
  711. FBU.rects = ws.rQshift16();
  712. //Util.Debug("FramebufferUpdate, rects:" + FBU.rects);
  713. FBU.bytes = 0;
  714. timing.cur_fbu = 0;
  715. if (timing.fbu_rt_start > 0) {
  716. now = (new Date()).getTime();
  717. Util.Info("First FBU latency: " + (now - timing.fbu_rt_start));
  718. }
  719. }
  720. while (FBU.rects > 0) {
  721. if (rfb_state !== "normal") {
  722. return false;
  723. }
  724. if (ws.rQwait("FBU", FBU.bytes)) { return false; }
  725. if (FBU.bytes === 0) {
  726. if (ws.rQwait("rect header", 12)) { return false; }
  727. /* New FramebufferUpdate */
  728. hdr = ws.rQshiftBytes(12);
  729. FBU.x = (hdr[0] << 8) + hdr[1];
  730. FBU.y = (hdr[2] << 8) + hdr[3];
  731. FBU.width = (hdr[4] << 8) + hdr[5];
  732. FBU.height = (hdr[6] << 8) + hdr[7];
  733. FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
  734. (hdr[10] << 8) + hdr[11], 10);
  735. if (encNames[FBU.encoding]) {
  736. // Debug:
  737. /*
  738. var msg = "FramebufferUpdate rects:" + FBU.rects;
  739. msg += " x: " + FBU.x + " y: " + FBU.y;
  740. msg += " width: " + FBU.width + " height: " + FBU.height;
  741. msg += " encoding:" + FBU.encoding;
  742. msg += "(" + encNames[FBU.encoding] + ")";
  743. msg += ", ws.rQlen(): " + ws.rQlen();
  744. Util.Debug(msg);
  745. */
  746. } else {
  747. fail("Disconnected: unsupported encoding " +
  748. FBU.encoding);
  749. return false;
  750. }
  751. }
  752. timing.last_fbu = (new Date()).getTime();
  753. ret = encHandlers[FBU.encoding]();
  754. now = (new Date()).getTime();
  755. timing.cur_fbu += (now - timing.last_fbu);
  756. if (ret) {
  757. encStats[FBU.encoding][0] += 1;
  758. encStats[FBU.encoding][1] += 1;
  759. }
  760. if (FBU.rects === 0) {
  761. if (((FBU.width === fb_width) &&
  762. (FBU.height === fb_height)) ||
  763. (timing.fbu_rt_start > 0)) {
  764. timing.full_fbu_total += timing.cur_fbu;
  765. timing.full_fbu_cnt += 1;
  766. Util.Info("Timing of full FBU, cur: " +
  767. timing.cur_fbu + ", total: " +
  768. timing.full_fbu_total + ", cnt: " +
  769. timing.full_fbu_cnt + ", avg: " +
  770. (timing.full_fbu_total /
  771. timing.full_fbu_cnt));
  772. }
  773. if (timing.fbu_rt_start > 0) {
  774. fbu_rt_diff = now - timing.fbu_rt_start;
  775. timing.fbu_rt_total += fbu_rt_diff;
  776. timing.fbu_rt_cnt += 1;
  777. Util.Info("full FBU round-trip, cur: " +
  778. fbu_rt_diff + ", total: " +
  779. timing.fbu_rt_total + ", cnt: " +
  780. timing.fbu_rt_cnt + ", avg: " +
  781. (timing.fbu_rt_total /
  782. timing.fbu_rt_cnt));
  783. timing.fbu_rt_start = 0;
  784. }
  785. }
  786. if (! ret) {
  787. return ret; // false ret means need more data
  788. }
  789. }
  790. return true; // We finished this FBU
  791. };
  792. //
  793. // FramebufferUpdate encodings
  794. //
  795. encHandlers.RAW = function display_raw() {
  796. //Util.Debug(">> display_raw (" + ws.rQlen() + " bytes)");
  797. var cur_y, cur_height;
  798. if (FBU.lines === 0) {
  799. FBU.lines = FBU.height;
  800. }
  801. FBU.bytes = FBU.width * fb_Bpp; // At least a line
  802. if (ws.rQwait("RAW", FBU.bytes)) { return false; }
  803. cur_y = FBU.y + (FBU.height - FBU.lines);
  804. cur_height = Math.min(FBU.lines,
  805. Math.floor(ws.rQlen()/(FBU.width * fb_Bpp)));
  806. canvas.blitImage(FBU.x, cur_y, FBU.width, cur_height,
  807. ws.get_rQ(), ws.get_rQi());
  808. ws.rQshiftBytes(FBU.width * cur_height * fb_Bpp);
  809. FBU.lines -= cur_height;
  810. if (FBU.lines > 0) {
  811. FBU.bytes = FBU.width * fb_Bpp; // At least another line
  812. } else {
  813. FBU.rects -= 1;
  814. FBU.bytes = 0;
  815. }
  816. //Util.Debug("<< display_raw (" + ws.rQlen() + " bytes)");
  817. return true;
  818. };
  819. encHandlers.COPYRECT = function display_copy_rect() {
  820. //Util.Debug(">> display_copy_rect");
  821. var old_x, old_y;
  822. if (ws.rQwait("COPYRECT", 4)) { return false; }
  823. old_x = ws.rQshift16();
  824. old_y = ws.rQshift16();
  825. canvas.copyImage(old_x, old_y, FBU.x, FBU.y, FBU.width, FBU.height);
  826. FBU.rects -= 1;
  827. FBU.bytes = 0;
  828. return true;
  829. };
  830. encHandlers.RRE = function display_rre() {
  831. //Util.Debug(">> display_rre (" + ws.rQlen() + " bytes)");
  832. var color, x, y, width, height, chunk;
  833. if (FBU.subrects === 0) {
  834. if (ws.rQwait("RRE", 4+fb_Bpp)) { return false; }
  835. FBU.subrects = ws.rQshift32();
  836. color = ws.rQshiftBytes(fb_Bpp); // Background
  837. canvas.fillRect(FBU.x, FBU.y, FBU.width, FBU.height, color);
  838. }
  839. while ((FBU.subrects > 0) && (ws.rQlen() >= (fb_Bpp + 8))) {
  840. color = ws.rQshiftBytes(fb_Bpp);
  841. x = ws.rQshift16();
  842. y = ws.rQshift16();
  843. width = ws.rQshift16();
  844. height = ws.rQshift16();
  845. canvas.fillRect(FBU.x + x, FBU.y + y, width, height, color);
  846. FBU.subrects -= 1;
  847. }
  848. //Util.Debug(" display_rre: rects: " + FBU.rects +
  849. // ", FBU.subrects: " + FBU.subrects);
  850. if (FBU.subrects > 0) {
  851. chunk = Math.min(rre_chunk_sz, FBU.subrects);
  852. FBU.bytes = (fb_Bpp + 8) * chunk;
  853. } else {
  854. FBU.rects -= 1;
  855. FBU.bytes = 0;
  856. }
  857. //Util.Debug("<< display_rre, FBU.bytes: " + FBU.bytes);
  858. return true;
  859. };
  860. encHandlers.HEXTILE = function display_hextile() {
  861. //Util.Debug(">> display_hextile");
  862. var subencoding, subrects, tile, color, cur_tile,
  863. tile_x, x, w, tile_y, y, h, xy, s, sx, sy, wh, sw, sh,
  864. rQ = ws.get_rQ(), rQi = ws.get_rQi();
  865. if (FBU.tiles === 0) {
  866. FBU.tiles_x = Math.ceil(FBU.width/16);
  867. FBU.tiles_y = Math.ceil(FBU.height/16);
  868. FBU.total_tiles = FBU.tiles_x * FBU.tiles_y;
  869. FBU.tiles = FBU.total_tiles;
  870. }
  871. /* FBU.bytes comes in as 1, ws.rQlen() at least 1 */
  872. while (FBU.tiles > 0) {
  873. FBU.bytes = 1;
  874. if (ws.rQwait("HEXTILE subencoding", FBU.bytes)) { return false; }
  875. subencoding = rQ[rQi]; // Peek
  876. if (subencoding > 30) { // Raw
  877. fail("Disconnected: illegal hextile subencoding " + subencoding);
  878. //Util.Debug("ws.rQslice(0,30):" + ws.rQslice(0,30));
  879. return false;
  880. }
  881. subrects = 0;
  882. cur_tile = FBU.total_tiles - FBU.tiles;
  883. tile_x = cur_tile % FBU.tiles_x;
  884. tile_y = Math.floor(cur_tile / FBU.tiles_x);
  885. x = FBU.x + tile_x * 16;
  886. y = FBU.y + tile_y * 16;
  887. w = Math.min(16, (FBU.x + FBU.width) - x);
  888. h = Math.min(16, (FBU.y + FBU.height) - y);
  889. /* Figure out how much we are expecting */
  890. if (subencoding & 0x01) { // Raw
  891. //Util.Debug(" Raw subencoding");
  892. FBU.bytes += w * h * fb_Bpp;
  893. } else {
  894. if (subencoding & 0x02) { // Background
  895. FBU.bytes += fb_Bpp;
  896. }
  897. if (subencoding & 0x04) { // Foreground
  898. FBU.bytes += fb_Bpp;
  899. }
  900. if (subencoding & 0x08) { // AnySubrects
  901. FBU.bytes += 1; // Since we aren't shifting it off
  902. if (ws.rQwait("hextile subrects header", FBU.bytes)) { return false; }
  903. subrects = rQ[rQi + FBU.bytes-1]; // Peek
  904. if (subencoding & 0x10) { // SubrectsColoured
  905. FBU.bytes += subrects * (fb_Bpp + 2);
  906. } else {
  907. FBU.bytes += subrects * 2;
  908. }
  909. }
  910. }
  911. /*
  912. Util.Debug(" tile:" + cur_tile + "/" + (FBU.total_tiles - 1) +
  913. " (" + tile_x + "," + tile_y + ")" +
  914. " [" + x + "," + y + "]@" + w + "x" + h +
  915. ", subenc:" + subencoding +
  916. "(last: " + FBU.lastsubencoding + "), subrects:" +
  917. subrects +
  918. ", ws.rQlen():" + ws.rQlen() + ", FBU.bytes:" + FBU.bytes +
  919. " last:" + ws.rQslice(FBU.bytes-10, FBU.bytes) +
  920. " next:" + ws.rQslice(FBU.bytes-1, FBU.bytes+10));
  921. */
  922. if (ws.rQwait("hextile", FBU.bytes)) { return false; }
  923. /* We know the encoding and have a whole tile */
  924. FBU.subencoding = rQ[rQi];
  925. rQi += 1;
  926. if (FBU.subencoding === 0) {
  927. if (FBU.lastsubencoding & 0x01) {
  928. /* Weird: ignore blanks after RAW */
  929. Util.Debug(" Ignoring blank after RAW");
  930. } else {
  931. canvas.fillRect(x, y, w, h, FBU.background);
  932. }
  933. } else if (FBU.subencoding & 0x01) { // Raw
  934. canvas.blitImage(x, y, w, h, rQ, rQi);
  935. rQi += FBU.bytes - 1;
  936. } else {
  937. if (FBU.subencoding & 0x02) { // Background
  938. FBU.background = rQ.slice(rQi, rQi + fb_Bpp);
  939. rQi += fb_Bpp;
  940. }
  941. if (FBU.subencoding & 0x04) { // Foreground
  942. FBU.foreground = rQ.slice(rQi, rQi + fb_Bpp);
  943. rQi += fb_Bpp;
  944. }
  945. tile = canvas.getTile(x, y, w, h, FBU.background);
  946. if (FBU.subencoding & 0x08) { // AnySubrects
  947. subrects = rQ[rQi];
  948. rQi += 1;
  949. for (s = 0; s < subrects; s += 1) {
  950. if (FBU.subencoding & 0x10) { // SubrectsColoured
  951. color = rQ.slice(rQi, rQi + fb_Bpp);
  952. rQi += fb_Bpp;
  953. } else {
  954. color = FBU.foreground;
  955. }
  956. xy = rQ[rQi];
  957. rQi += 1;
  958. sx = (xy >> 4);
  959. sy = (xy & 0x0f);
  960. wh = rQ[rQi];
  961. rQi += 1;
  962. sw = (wh >> 4) + 1;
  963. sh = (wh & 0x0f) + 1;
  964. canvas.setSubTile(tile, sx, sy, sw, sh, color);
  965. }
  966. }
  967. canvas.putTile(tile);
  968. }
  969. ws.set_rQi(rQi);
  970. FBU.lastsubencoding = FBU.subencoding;
  971. FBU.bytes = 0;
  972. FBU.tiles -= 1;
  973. }
  974. if (FBU.tiles === 0) {
  975. FBU.rects -= 1;
  976. }
  977. //Util.Debug("<< display_hextile");
  978. return true;
  979. };
  980. encHandlers.TIGHT_PNG = function display_tight_png() {
  981. //Util.Debug(">> display_tight_png");
  982. var ctl, cmode, clength, getCLength, color, img;
  983. //Util.Debug(" FBU.rects: " + FBU.rects);
  984. //Util.Debug(" starting ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  985. FBU.bytes = 1; // compression-control byte
  986. if (ws.rQwait("TIGHT compression-control", FBU.bytes)) { return false; }
  987. // Get 'compact length' header and data size
  988. getCLength = function (arr) {
  989. var header = 1, data = 0;
  990. data += arr[0] & 0x7f;
  991. if (arr[0] & 0x80) {
  992. header += 1;
  993. data += (arr[1] & 0x7f) << 7;
  994. if (arr[1] & 0x80) {
  995. header += 1;
  996. data += arr[2] << 14;
  997. }
  998. }
  999. return [header, data];
  1000. };
  1001. ctl = ws.rQpeek8();
  1002. switch (ctl >> 4) {
  1003. case 0x08: cmode = "fill"; break;
  1004. case 0x09: cmode = "jpeg"; break;
  1005. case 0x0A: cmode = "png"; break;
  1006. default: throw("Illegal basic compression received, ctl: " + ctl);
  1007. }
  1008. switch (cmode) {
  1009. // fill uses fb_depth because TPIXELs drop the padding byte
  1010. case "fill": FBU.bytes += fb_depth; break; // TPIXEL
  1011. case "jpeg": FBU.bytes += 3; break; // max clength
  1012. case "png": FBU.bytes += 3; break; // max clength
  1013. }
  1014. if (ws.rQwait("TIGHT " + cmode, FBU.bytes)) { return false; }
  1015. //Util.Debug(" ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  1016. //Util.Debug(" cmode: " + cmode);
  1017. // Determine FBU.bytes
  1018. switch (cmode) {
  1019. case "fill":
  1020. ws.rQshift8(); // shift off ctl
  1021. color = ws.rQshiftBytes(fb_depth);
  1022. canvas.fillRect(FBU.x, FBU.y, FBU.width, FBU.height, color);
  1023. break;
  1024. case "jpeg":
  1025. case "png":
  1026. clength = getCLength(ws.rQslice(1, 4));
  1027. FBU.bytes = 1 + clength[0] + clength[1]; // ctl + clength size + jpeg-data
  1028. if (ws.rQwait("TIGHT " + cmode, FBU.bytes)) { return false; }
  1029. // We have everything, render it
  1030. //Util.Debug(" png, ws.rQlen(): " + ws.rQlen() + ", clength[0]: " + clength[0] + ", clength[1]: " + clength[1]);
  1031. ws.rQshiftBytes(1 + clength[0]); // shift off ctl + compact length
  1032. img = new Image();
  1033. img.onload = scan_tight_imgQ;
  1034. FBU.imgQ.push([img, FBU.x, FBU.y]);
  1035. img.src = "data:image/" + cmode +
  1036. extract_data_uri(ws.rQshiftBytes(clength[1]));
  1037. img = null;
  1038. break;
  1039. }
  1040. FBU.bytes = 0;
  1041. FBU.rects -= 1;
  1042. //Util.Debug(" ending ws.rQslice(0,20): " + ws.rQslice(0,20) + " (" + ws.rQlen() + ")");
  1043. //Util.Debug("<< display_tight_png");
  1044. return true;
  1045. };
  1046. extract_data_uri = function(arr) {
  1047. //var i, stra = [];
  1048. //for (i=0; i< arr.length; i += 1) {
  1049. // stra.push(String.fromCharCode(arr[i]));
  1050. //}
  1051. //return "," + escape(stra.join(''));
  1052. return ";base64," + Base64.encode(arr);
  1053. };
  1054. scan_tight_imgQ = function() {
  1055. var img, imgQ, ctx;
  1056. ctx = canvas.getContext();
  1057. if (rfb_state === 'normal') {
  1058. imgQ = FBU.imgQ;
  1059. while ((imgQ.length > 0) && (imgQ[0][0].complete)) {
  1060. img = imgQ.shift();
  1061. ctx.drawImage(img[0], img[1], img[2]);
  1062. }
  1063. setTimeout(scan_tight_imgQ, scan_imgQ_rate);
  1064. }
  1065. };
  1066. encHandlers.DesktopSize = function set_desktopsize() {
  1067. Util.Debug(">> set_desktopsize");
  1068. fb_width = FBU.width;
  1069. fb_height = FBU.height;
  1070. canvas.clear();
  1071. canvas.resize(fb_width, fb_height);
  1072. timing.fbu_rt_start = (new Date()).getTime();
  1073. // Send a new non-incremental request
  1074. ws.send(fbUpdateRequest(0));
  1075. FBU.bytes = 0;
  1076. FBU.rects -= 1;
  1077. Util.Debug("<< set_desktopsize");
  1078. return true;
  1079. };
  1080. encHandlers.Cursor = function set_cursor() {
  1081. var x, y, w, h, pixelslength, masklength;
  1082. //Util.Debug(">> set_cursor");
  1083. x = FBU.x; // hotspot-x
  1084. y = FBU.y; // hotspot-y
  1085. w = FBU.width;
  1086. h = FBU.height;
  1087. pixelslength = w * h * fb_Bpp;
  1088. masklength = Math.floor((w + 7) / 8) * h;
  1089. FBU.bytes = pixelslength + masklength;
  1090. if (ws.rQwait("cursor encoding", FBU.bytes)) { return false; }
  1091. //Util.Debug(" set_cursor, x: " + x + ", y: " + y + ", w: " + w + ", h: " + h);
  1092. canvas.changeCursor(ws.rQshiftBytes(pixelslength),
  1093. ws.rQshiftBytes(masklength),
  1094. x, y, w, h);
  1095. FBU.bytes = 0;
  1096. FBU.rects -= 1;
  1097. //Util.Debug("<< set_cursor");
  1098. return true;
  1099. };
  1100. encHandlers.JPEG_quality_lo = function set_jpeg_quality() {
  1101. Util.Error("Server sent jpeg_quality pseudo-encoding");
  1102. };
  1103. encHandlers.compress_lo = function set_compress_level() {
  1104. Util.Error("Server sent compress level pseudo-encoding");
  1105. };
  1106. /*
  1107. * Client message routines
  1108. */
  1109. pixelFormat = function() {
  1110. //Util.Debug(">> pixelFormat");
  1111. var arr;
  1112. arr = [0]; // msg-type
  1113. arr.push8(0); // padding
  1114. arr.push8(0); // padding
  1115. arr.push8(0); // padding
  1116. arr.push8(fb_Bpp * 8); // bits-per-pixel
  1117. arr.push8(fb_depth * 8); // depth
  1118. arr.push8(0); // little-endian
  1119. arr.push8(conf.true_color ? 1 : 0); // true-color
  1120. arr.push16(255); // red-max
  1121. arr.push16(255); // green-max
  1122. arr.push16(255); // blue-max
  1123. arr.push8(0); // red-shift
  1124. arr.push8(8); // green-shift
  1125. arr.push8(16); // blue-shift
  1126. arr.push8(0); // padding
  1127. arr.push8(0); // padding
  1128. arr.push8(0); // padding
  1129. //Util.Debug("<< pixelFormat");
  1130. return arr;
  1131. };
  1132. clientEncodings = function() {
  1133. //Util.Debug(">> clientEncodings");
  1134. var arr, i, encList = [];
  1135. for (i=0; i<encodings.length; i += 1) {
  1136. if ((encodings[i][0] === "Cursor") &&
  1137. (! conf.local_cursor)) {
  1138. Util.Debug("Skipping Cursor pseudo-encoding");
  1139. } else {
  1140. //Util.Debug("Adding encoding: " + encodings[i][0]);
  1141. encList.push(encodings[i][1]);
  1142. }
  1143. }
  1144. arr = [2]; // msg-type
  1145. arr.push8(0); // padding
  1146. arr.push16(encList.length); // encoding count
  1147. for (i=0; i < encList.length; i += 1) {
  1148. arr.push32(encList[i]);
  1149. }
  1150. //Util.Debug("<< clientEncodings: " + arr);
  1151. return arr;
  1152. };
  1153. fbUpdateRequest = function(incremental, x, y, xw, yw) {
  1154. //Util.Debug(">> fbUpdateRequest");
  1155. if (!x) { x = 0; }
  1156. if (!y) { y = 0; }
  1157. if (!xw) { xw = fb_width; }
  1158. if (!yw) { yw = fb_height; }
  1159. var arr;
  1160. arr = [3]; // msg-type
  1161. arr.push8(incremental);
  1162. arr.push16(x);
  1163. arr.push16(y);
  1164. arr.push16(xw);
  1165. arr.push16(yw);
  1166. //Util.Debug("<< fbUpdateRequest");
  1167. return arr;
  1168. };
  1169. keyEvent = function(keysym, down) {
  1170. //Util.Debug(">> keyEvent, keysym: " + keysym + ", down: " + down);
  1171. var arr;
  1172. arr = [4]; // msg-type
  1173. arr.push8(down);
  1174. arr.push16(0);
  1175. arr.push32(keysym);
  1176. //Util.Debug("<< keyEvent");
  1177. return arr;
  1178. };
  1179. pointerEvent = function(x, y) {
  1180. //Util.Debug(">> pointerEvent, x,y: " + x + "," + y +
  1181. // " , mask: " + mouse_buttonMask);
  1182. var arr;
  1183. arr = [5]; // msg-type
  1184. arr.push8(mouse_buttonMask);
  1185. arr.push16(x);
  1186. arr.push16(y);
  1187. //Util.Debug("<< pointerEvent");
  1188. return arr;
  1189. };
  1190. clientCutText = function(text) {
  1191. //Util.Debug(">> clientCutText");
  1192. var arr, i, n;
  1193. arr = [6]; // msg-type
  1194. arr.push8(0); // padding
  1195. arr.push8(0); // padding
  1196. arr.push8(0); // padding
  1197. arr.push32(text.length);
  1198. n = text.length;
  1199. for (i=0; i < n; i+=1) {
  1200. arr.push(text.charCodeAt(i));
  1201. }
  1202. //Util.Debug("<< clientCutText:" + arr);
  1203. return arr;
  1204. };
  1205. //
  1206. // Public API interface functions
  1207. //
  1208. that.connect = function(host, port, password) {
  1209. //Util.Debug(">> connect");
  1210. rfb_host = host;
  1211. rfb_port = port;
  1212. rfb_password = (password !== undefined) ? password : "";
  1213. if ((!rfb_host) || (!rfb_port)) {
  1214. return fail("Must set host and port");
  1215. }
  1216. updateState('connect');
  1217. //Util.Debug("<< connect");
  1218. };
  1219. that.disconnect = function() {
  1220. //Util.Debug(">> disconnect");
  1221. updateState('disconnect', 'Disconnecting');
  1222. //Util.Debug("<< disconnect");
  1223. };
  1224. that.sendPassword = function(passwd) {
  1225. rfb_password = passwd;
  1226. rfb_state = "Authentication";
  1227. setTimeout(init_msg, 1);
  1228. };
  1229. that.sendCtrlAltDel = function() {
  1230. if (rfb_state !== "normal") { return false; }
  1231. Util.Info("Sending Ctrl-Alt-Del");
  1232. var arr = [];
  1233. arr = arr.concat(keyEvent(0xFFE3, 1)); // Control
  1234. arr = arr.concat(keyEvent(0xFFE9, 1)); // Alt
  1235. arr = arr.concat(keyEvent(0xFFFF, 1)); // Delete
  1236. arr = arr.concat(keyEvent(0xFFFF, 0)); // Delete
  1237. arr = arr.concat(keyEvent(0xFFE9, 0)); // Alt
  1238. arr = arr.concat(keyEvent(0xFFE3, 0)); // Control
  1239. arr = arr.concat(fbUpdateRequest(1));
  1240. ws.send(arr);
  1241. };
  1242. // Send a key press. If 'down' is not specified then send a down key
  1243. // followed by an up key.
  1244. that.sendKey = function(code, down) {
  1245. if (rfb_state !== "normal") { return false; }
  1246. var arr = [];
  1247. if (typeof down !== 'undefined') {
  1248. Util.Info("Sending key code (" + (down ? "down" : "up") + "): " + code);
  1249. arr = arr.concat(keyEvent(code, down ? 1 : 0));
  1250. } else {
  1251. Util.Info("Sending key code (down + up): " + code);
  1252. arr = arr.concat(keyEvent(code, 1));
  1253. arr = arr.concat(keyEvent(code, 0));
  1254. }
  1255. arr = arr.concat(fbUpdateRequest(1));
  1256. ws.send(arr);
  1257. };
  1258. that.clipboardPasteFrom = function(text) {
  1259. if (rfb_state !== "normal") { return; }
  1260. //Util.Debug(">> clipboardPasteFrom: " + text.substr(0,40) + "...");
  1261. ws.send(clientCutText(text));
  1262. //Util.Debug("<< clipboardPasteFrom");
  1263. };
  1264. that.testMode = function(override_send) {
  1265. // Overridable internal functions for testing
  1266. test_mode = true;
  1267. // TODO figure out what to do here
  1268. ws.send = override_send;
  1269. that.recv_message = ws.recv_message; // Expose it
  1270. checkEvents = function () { /* Stub Out */ };
  1271. that.connect = function(host, port, password) {
  1272. rfb_host = host;
  1273. rfb_port = port;
  1274. rfb_password = password;
  1275. updateState('ProtocolVersion', "Starting VNC handshake");
  1276. };
  1277. };
  1278. return constructor(); // Return the public API interface
  1279. } // End of RFB()