vnc.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. /*
  2. * noVNC: HTML5 VNC client
  3. * Copyright (C) 2010 Joel Martin
  4. * Licensed under LGPL-3 (see LICENSE.LGPL-3)
  5. *
  6. * See README.md for usage and integration instructions.
  7. */
  8. "use strict";
  9. /*jslint white: false, nomen: false, browser: true, bitwise: false */
  10. /*global window, WebSocket, Util, Canvas, VNC_uri_prefix, Base64, DES */
  11. // Globals defined here
  12. var VNC_native_ws, RFB;
  13. /*
  14. * Load supporting scripts
  15. */
  16. function get_VNC_uri_prefix() {
  17. return (typeof VNC_uri_prefix !== "undefined") ? VNC_uri_prefix : "include/";
  18. }
  19. (function () {
  20. var extra = "", start, end;
  21. start = "<script src='" + get_VNC_uri_prefix();
  22. end = "'><\/script>";
  23. // Uncomment to activate firebug lite
  24. //extra += "<script src='http://getfirebug.com/releases/lite/1.2/" +
  25. // "firebug-lite-compressed.js'><\/script>";
  26. extra += start + "util.js" + end;
  27. extra += start + "base64.js" + end;
  28. extra += start + "des.js" + end;
  29. extra += start + "canvas.js" + end;
  30. /* If no builtin websockets then load web_socket.js */
  31. if (window.WebSocket) {
  32. VNC_native_ws = true;
  33. } else {
  34. VNC_native_ws = false;
  35. WebSocket__swfLocation = get_VNC_uri_prefix() +
  36. "web-socket-js/WebSocketMain.swf";
  37. extra += start + "web-socket-js/swfobject.js" + end;
  38. extra += start + "web-socket-js/FABridge.js" + end;
  39. extra += start + "web-socket-js/web_socket.js" + end;
  40. }
  41. document.write(extra);
  42. }());
  43. /*
  44. * RFB namespace
  45. */
  46. RFB = {
  47. /*
  48. * External interface variables and methods
  49. */
  50. host : '',
  51. port : 5900,
  52. password : '',
  53. encrypt : true,
  54. true_color : false,
  55. b64encode : true, // false means UTF-8 on the wire
  56. local_cursor : true,
  57. connectTimeout : 2000, // time to wait for connection
  58. // In preference order
  59. encodings : [
  60. ['COPYRECT', 0x01, 'display_copy_rect'],
  61. ['TIGHT_PNG', -260, 'display_tight_png'],
  62. ['HEXTILE', 0x05, 'display_hextile'],
  63. ['RRE', 0x02, 'display_rre'],
  64. ['RAW', 0x00, 'display_raw'],
  65. ['DesktopSize', -223, 'set_desktopsize'],
  66. ['Cursor', -239, 'set_cursor'],
  67. // Psuedo-encoding settings
  68. ['JPEG_quality_lo', -32, 'set_jpeg_quality'],
  69. // ['JPEG_quality_hi', -23, 'set_jpeg_quality'],
  70. ['compress_lo', -255, 'set_compress_level']
  71. // ['compress_hi', -247, 'set_compress_level']
  72. ],
  73. setUpdateState: function(externalUpdateState) {
  74. RFB.externalUpdateState = externalUpdateState;
  75. },
  76. setClipboardReceive: function(clipReceive) {
  77. RFB.clipboardCopyTo = clipReceive;
  78. },
  79. setCanvasID: function(canvasID) {
  80. RFB.canvasID = canvasID;
  81. },
  82. setEncrypt: function(encrypt) {
  83. if ((!encrypt) || (encrypt in {'0':1, 'no':1, 'false':1})) {
  84. RFB.encrypt = false;
  85. } else {
  86. RFB.encrypt = true;
  87. }
  88. },
  89. setBase64: function(b64) {
  90. if ((!b64) || (b64 in {'0':1, 'no':1, 'false':1})) {
  91. RFB.b64encode = false;
  92. } else {
  93. RFB.b64encode = true;
  94. }
  95. Util.Debug("Set b64encode to: " + RFB.b64encode);
  96. },
  97. setTrueColor: function(trueColor) {
  98. if ((!trueColor) || (trueColor in {'0':1, 'no':1, 'false':1})) {
  99. RFB.true_color = false;
  100. } else {
  101. RFB.true_color = true;
  102. }
  103. },
  104. setCursor: function(cursor) {
  105. if ((!cursor) || (cursor in {'0':1, 'no':1, 'false':1})) {
  106. RFB.local_cursor = false;
  107. } else {
  108. if (Canvas.isCursor()) {
  109. RFB.local_cursor = true;
  110. } else {
  111. Util.Warn("Browser does not support local cursor");
  112. }
  113. }
  114. },
  115. sendPassword: function(passwd) {
  116. RFB.password = passwd;
  117. RFB.state = "Authentication";
  118. setTimeout(RFB.init_msg, 1);
  119. },
  120. sendCtrlAltDel: function() {
  121. if (RFB.state !== "normal") { return false; }
  122. Util.Info("Sending Ctrl-Alt-Del");
  123. var arr = [];
  124. arr = arr.concat(RFB.keyEvent(0xFFE3, 1)); // Control
  125. arr = arr.concat(RFB.keyEvent(0xFFE9, 1)); // Alt
  126. arr = arr.concat(RFB.keyEvent(0xFFFF, 1)); // Delete
  127. arr = arr.concat(RFB.keyEvent(0xFFFF, 0)); // Delete
  128. arr = arr.concat(RFB.keyEvent(0xFFE9, 0)); // Alt
  129. arr = arr.concat(RFB.keyEvent(0xFFE3, 0)); // Control
  130. arr = arr.concat(RFB.fbUpdateRequest(1));
  131. RFB.send_array(arr);
  132. },
  133. load: function () {
  134. var i;
  135. //Util.Debug(">> load");
  136. /* Load web-socket-js if no builtin WebSocket support */
  137. if (VNC_native_ws) {
  138. Util.Info("Using native WebSockets");
  139. RFB.updateState('loaded', 'noVNC ready (using native WebSockets)');
  140. } else {
  141. Util.Warn("Using web-socket-js flash bridge");
  142. if ((! Util.Flash) ||
  143. (Util.Flash.version < 9)) {
  144. RFB.updateState('fatal', "WebSockets or Adobe Flash is required");
  145. } else if (document.location.href.substr(0, 7) === "file://") {
  146. RFB.updateState('fatal',
  147. "'file://' URL is incompatible with Adobe Flash");
  148. } else {
  149. RFB.updateState('loaded', 'noVNC ready (using Flash WebSockets emulation)');
  150. }
  151. }
  152. // Initialize canvas/fxcanvas
  153. try {
  154. Canvas.init(RFB.canvasID);
  155. } catch (exc) {
  156. RFB.updateState('fatal', "No working Canvas");
  157. }
  158. // Populate encoding lookup tables
  159. RFB.encHandlers = {};
  160. RFB.encNames = {};
  161. for (i=0; i < RFB.encodings.length; i+=1) {
  162. RFB.encHandlers[RFB.encodings[i][1]] = RFB[RFB.encodings[i][2]];
  163. RFB.encNames[RFB.encodings[i][1]] = RFB.encodings[i][0];
  164. }
  165. //Util.Debug("<< load");
  166. },
  167. connect: function (host, port, password) {
  168. //Util.Debug(">> connect");
  169. RFB.host = host;
  170. RFB.port = port;
  171. RFB.password = (password !== undefined) ? password : "";
  172. if ((!RFB.host) || (!RFB.port)) {
  173. RFB.updateState('failed', "Must set host and port");
  174. return;
  175. }
  176. RFB.updateState('connect');
  177. //Util.Debug("<< connect");
  178. },
  179. disconnect: function () {
  180. //Util.Debug(">> disconnect");
  181. RFB.updateState('disconnected', 'Disconnected');
  182. //Util.Debug("<< disconnect");
  183. },
  184. clipboardPasteFrom: function (text) {
  185. if (RFB.state !== "normal") { return; }
  186. //Util.Debug(">> clipboardPasteFrom: " + text.substr(0,40) + "...");
  187. RFB.send_array(RFB.clientCutText(text));
  188. //Util.Debug("<< clipboardPasteFrom");
  189. },
  190. /*
  191. * Private variables and methods
  192. */
  193. ws : null, // Web Socket object
  194. sendID : null,
  195. scanID : null, // TIGHT_PNG render image scanner
  196. // Receive and send queues
  197. RQ : [], // Receive Queue
  198. SQ : "", // Send Queue
  199. encHandlers : {},
  200. encNames : {},
  201. // Frame buffer update state
  202. FBU : {
  203. rects : 0,
  204. subrects : 0, // RRE and HEXTILE
  205. lines : 0, // RAW
  206. tiles : 0, // HEXTILE
  207. bytes : 0,
  208. x : 0,
  209. y : 0,
  210. width : 0,
  211. height : 0,
  212. encoding : 0,
  213. subencoding : -1,
  214. background : null,
  215. imgs : [] // TIGHT_PNG image queue
  216. },
  217. fb_Bpp : 4,
  218. fb_depth : 3,
  219. max_version : 3.8,
  220. version : 0,
  221. auth_scheme : '',
  222. state : 'disconnected',
  223. cuttext : 'none', // ServerCutText wait state
  224. ct_length : 0,
  225. shared : 1,
  226. check_rate : 217,
  227. scan_imgs_rate : 100,
  228. req_rate : 1413,
  229. last_req : 0,
  230. canvasID : 'VNC_canvas',
  231. fb_width : 0,
  232. fb_height : 0,
  233. fb_name : "",
  234. rre_chunk : 100,
  235. timing : {
  236. last_fbu : 0,
  237. fbu_total : 0,
  238. fbu_total_cnt : 0,
  239. full_fbu_total : 0,
  240. full_fbu_cnt : 0,
  241. fbu_rt_start : 0,
  242. fbu_rt_total : 0,
  243. fbu_rt_cnt : 0,
  244. history : [],
  245. history_start : 0,
  246. h_time : 0,
  247. h_rects : 0,
  248. h_fbus : 0,
  249. h_bytes : 0,
  250. h_pixels : 0
  251. },
  252. /* Mouse state */
  253. mouse_buttonmask : 0,
  254. mouse_arr : [],
  255. /*
  256. * Server message handlers
  257. */
  258. /* RFB/VNC initialisation */
  259. init_msg: function () {
  260. //Util.Debug(">> init_msg [RFB.state '" + RFB.state + "']");
  261. var RQ = RFB.RQ, strlen, reason, reason_len, sversion, cversion,
  262. i, types, num_types, challenge, response, bpp, depth,
  263. big_endian, true_color, name_length;
  264. //Util.Debug("RQ (" + RQ.length + ") " + RQ);
  265. switch (RFB.state) {
  266. case 'ProtocolVersion' :
  267. if (RQ.length < 12) {
  268. RFB.updateState('failed',
  269. "Disconnected: incomplete protocol version");
  270. return;
  271. }
  272. sversion = RQ.shiftStr(12).substr(4,7);
  273. Util.Info("Server ProtocolVersion: " + sversion);
  274. switch (sversion) {
  275. case "003.003": RFB.version = 3.3; break;
  276. case "003.007": RFB.version = 3.7; break;
  277. case "003.008": RFB.version = 3.8; break;
  278. default:
  279. RFB.updateState('failed',
  280. "Invalid server version " + sversion);
  281. return;
  282. }
  283. if (RFB.version > RFB.max_version) {
  284. RFB.version = RFB.max_version;
  285. }
  286. RFB.sendID = setInterval(function() {
  287. /*
  288. * Send updates either at a rate of one update every 50ms,
  289. * or whatever slower rate the network can handle
  290. */
  291. if (RFB.ws.bufferedAmount === 0) {
  292. if (RFB.SQ) {
  293. RFB.ws.send(RFB.SQ);
  294. RFB.SQ = "";
  295. }
  296. } else {
  297. Util.Debug("Delaying send");
  298. }
  299. }, 50);
  300. cversion = "00" + parseInt(RFB.version,10) +
  301. ".00" + ((RFB.version * 10) % 10);
  302. RFB.send_string("RFB " + cversion + "\n");
  303. RFB.updateState('Security', "Sent ProtocolVersion: " + sversion);
  304. break;
  305. case 'Security' :
  306. if (RFB.version >= 3.7) {
  307. num_types = RQ.shift8();
  308. if (num_types === 0) {
  309. strlen = RQ.shift32();
  310. reason = RQ.shiftStr(strlen);
  311. RFB.updateState('failed',
  312. "Disconnected: security failure: " + reason);
  313. return;
  314. }
  315. RFB.auth_scheme = 0;
  316. types = RQ.shiftBytes(num_types);
  317. for (i=0; i < types.length; i+=1) {
  318. if ((types[i] > RFB.auth_scheme) && (types[i] < 3)) {
  319. RFB.auth_scheme = types[i];
  320. }
  321. }
  322. if (RFB.auth_scheme === 0) {
  323. RFB.updateState('failed',
  324. "Disconnected: unsupported security types: " + types);
  325. return;
  326. }
  327. RFB.send_array([RFB.auth_scheme]);
  328. } else {
  329. if (RQ.length < 4) {
  330. RFB.updateState('failed', "Invalid security frame");
  331. return;
  332. }
  333. RFB.auth_scheme = RQ.shift32();
  334. }
  335. RFB.updateState('Authentication',
  336. "Authenticating using scheme: " + RFB.auth_scheme);
  337. // Fall through
  338. case 'Authentication' :
  339. //Util.Debug("Security auth scheme: " + RFB.auth_scheme);
  340. switch (RFB.auth_scheme) {
  341. case 0: // connection failed
  342. if (RQ.length < 4) {
  343. //Util.Debug(" waiting for auth reason bytes");
  344. return;
  345. }
  346. strlen = RQ.shift32();
  347. reason = RQ.shiftStr(strlen);
  348. RFB.updateState('failed',
  349. "Disconnected: auth failure: " + reason);
  350. return;
  351. case 1: // no authentication
  352. // RFB.send_array([RFB.shared]); // ClientInitialisation
  353. RFB.updateState('SecurityResult');
  354. break;
  355. case 2: // VNC authentication
  356. if (RFB.password.length === 0) {
  357. RFB.updateState('password', "Password Required");
  358. return;
  359. }
  360. if (RQ.length < 16) {
  361. //Util.Debug(" waiting for auth challenge bytes");
  362. return;
  363. }
  364. challenge = RQ.shiftBytes(16);
  365. //Util.Debug("Password: " + RFB.password);
  366. //Util.Debug("Challenge: " + challenge +
  367. // " (" + challenge.length + ")");
  368. response = RFB.DES(RFB.password, challenge);
  369. //Util.Debug("Response: " + response +
  370. // " (" + response.length + ")");
  371. //Util.Debug("Sending DES encrypted auth response");
  372. RFB.send_array(response);
  373. RFB.updateState('SecurityResult');
  374. break;
  375. default:
  376. RFB.updateState('failed',
  377. "Disconnected: unsupported auth scheme: " +
  378. RFB.auth_scheme);
  379. return;
  380. }
  381. break;
  382. case 'SecurityResult' :
  383. if (RQ.length < 4) {
  384. RFB.updateState('failed', "Invalid VNC auth response");
  385. return;
  386. }
  387. switch (RQ.shift32()) {
  388. case 0: // OK
  389. RFB.updateState('ServerInitialisation', "Authentication OK");
  390. break;
  391. case 1: // failed
  392. if (RFB.version >= 3.8) {
  393. reason_len = RQ.shift32();
  394. reason = RQ.shiftStr(reason_len);
  395. RFB.updateState('failed', reason);
  396. } else {
  397. RFB.updateState('failed', "Authentication failed");
  398. }
  399. return;
  400. case 2: // too-many
  401. RFB.updateState('failed',
  402. "Disconnected: too many auth attempts");
  403. return;
  404. }
  405. RFB.send_array([RFB.shared]); // ClientInitialisation
  406. break;
  407. case 'ServerInitialisation' :
  408. if (RQ.length < 24) {
  409. RFB.updateState('failed', "Invalid server initialisation");
  410. return;
  411. }
  412. /* Screen size */
  413. RFB.fb_width = RQ.shift16();
  414. RFB.fb_height = RQ.shift16();
  415. /* PIXEL_FORMAT */
  416. bpp = RQ.shift8();
  417. depth = RQ.shift8();
  418. big_endian = RQ.shift8();
  419. true_color = RQ.shift8();
  420. Util.Info("Screen: " + RFB.fb_width + "x" + RFB.fb_height +
  421. ", bpp: " + bpp + ", depth: " + depth +
  422. ", big_endian: " + big_endian +
  423. ", true_color: " + true_color);
  424. /* Connection name/title */
  425. RQ.shiftStr(12);
  426. name_length = RQ.shift32();
  427. RFB.fb_name = RQ.shiftStr(name_length);
  428. Canvas.resize(RFB.fb_width, RFB.fb_height, RFB.true_color);
  429. Canvas.start(RFB.keyPress, RFB.mouseButton, RFB.mouseMove);
  430. if (RFB.true_color) {
  431. RFB.fb_Bpp = 4;
  432. RFB.fb_depth = 3;
  433. } else {
  434. RFB.fb_Bpp = 1;
  435. RFB.fb_depth = 1;
  436. }
  437. response = RFB.pixelFormat();
  438. response = response.concat(RFB.clientEncodings());
  439. response = response.concat(RFB.fbUpdateRequest(0));
  440. RFB.timing.fbu_rt_start = (new Date()).getTime();
  441. RFB.send_array(response);
  442. /* Start pushing/polling */
  443. setTimeout(RFB.checkEvents, RFB.check_rate);
  444. setTimeout(RFB.scan_tight_imgs, RFB.scan_imgs_rate);
  445. RFB.timing.history_start = (new Date()).getTime();
  446. setTimeout(RFB.update_timings, 1000);
  447. if (RFB.encrypt) {
  448. RFB.updateState('normal', "Connected (encrypted) to: " + RFB.fb_name);
  449. } else {
  450. RFB.updateState('normal', "Connected (unencrypted) to: " + RFB.fb_name);
  451. }
  452. break;
  453. }
  454. //Util.Debug("<< init_msg");
  455. },
  456. /* Normal RFB/VNC server messages */
  457. normal_msg: function () {
  458. //Util.Debug(">> normal_msg");
  459. var RQ = RFB.RQ, ret = true, msg_type,
  460. c, first_colour, num_colours, red, green, blue;
  461. //Util.Debug(">> msg RQ.slice(0,10): " + RQ.slice(0,20));
  462. //Util.Debug(">> msg RQ.slice(-10,-1): " + RQ.slice(RQ.length-10,RQ.length));
  463. if (RFB.FBU.rects > 0) {
  464. msg_type = 0;
  465. } else if (RFB.cuttext !== 'none') {
  466. msg_type = 3;
  467. } else {
  468. msg_type = RQ.shift8();
  469. }
  470. switch (msg_type) {
  471. case 0: // FramebufferUpdate
  472. ret = RFB.framebufferUpdate();
  473. break;
  474. case 1: // SetColourMapEntries
  475. Util.Debug("SetColourMapEntries");
  476. RQ.shift8(); // Padding
  477. first_colour = RQ.shift16(); // First colour
  478. num_colours = RQ.shift16();
  479. for (c=0; c < num_colours; c+=1) {
  480. red = RQ.shift16();
  481. //Util.Debug("red before: " + red);
  482. red = parseInt(red / 256, 10);
  483. //Util.Debug("red after: " + red);
  484. green = parseInt(RQ.shift16() / 256, 10);
  485. blue = parseInt(RQ.shift16() / 256, 10);
  486. Canvas.colourMap[first_colour + c] = [red, green, blue];
  487. }
  488. Util.Info("Registered " + num_colours + " colourMap entries");
  489. //Util.Debug("colourMap: " + Canvas.colourMap);
  490. break;
  491. case 2: // Bell
  492. Util.Warn("Bell (unsupported)");
  493. break;
  494. case 3: // ServerCutText
  495. Util.Debug("ServerCutText");
  496. Util.Debug("RQ:" + RQ.slice(0,20));
  497. if (RFB.cuttext === 'none') {
  498. RFB.cuttext = 'header';
  499. }
  500. if (RFB.cuttext === 'header') {
  501. if (RQ.length < 7) {
  502. //Util.Debug("waiting for ServerCutText header");
  503. return false;
  504. }
  505. RQ.shiftBytes(3); // Padding
  506. RFB.ct_length = RQ.shift32();
  507. }
  508. RFB.cuttext = 'bytes';
  509. if (RQ.length < RFB.ct_length) {
  510. //Util.Debug("waiting for ServerCutText bytes");
  511. return false;
  512. }
  513. RFB.clipboardCopyTo(RQ.shiftStr(RFB.ct_length));
  514. RFB.cuttext = 'none';
  515. break;
  516. default:
  517. RFB.updateState('failed',
  518. "Disconnected: illegal server message type " + msg_type);
  519. Util.Debug("RQ.slice(0,30):" + RQ.slice(0,30));
  520. break;
  521. }
  522. //Util.Debug("<< normal_msg");
  523. return ret;
  524. },
  525. framebufferUpdate: function() {
  526. var RQ = RFB.RQ, FBU = RFB.FBU, timing = RFB.timing,
  527. now, fbu_rt_diff, last_bytes, last_rects,
  528. ret = true, msg;
  529. if (FBU.rects === 0) {
  530. //Util.Debug("New FBU: RQ.slice(0,20): " + RQ.slice(0,20));
  531. if (RQ.length < 3) {
  532. RQ.unshift(0); // FBU msg_type
  533. Util.Debug(" waiting for FBU header bytes");
  534. return false;
  535. }
  536. RQ.shift8();
  537. FBU.rects = RQ.shift16();
  538. //Util.Debug("FramebufferUpdate, rects:" + FBU.rects);
  539. FBU.bytes = 0;
  540. timing.cur_fbu = 0;
  541. timing.h_fbus += 1;
  542. if (timing.fbu_rt_start > 0) {
  543. now = (new Date()).getTime();
  544. Util.Info("First FBU latency: " + (now - timing.fbu_rt_start));
  545. }
  546. }
  547. while ((FBU.rects > 0) && (RQ.length >= FBU.bytes)) {
  548. if (FBU.bytes === 0) {
  549. if (RQ.length < 12) {
  550. //Util.Debug(" waiting for rect header bytes");
  551. return false;
  552. }
  553. /* New FramebufferUpdate */
  554. FBU.x = RQ.shift16();
  555. FBU.y = RQ.shift16();
  556. FBU.width = RQ.shift16();
  557. FBU.height = RQ.shift16();
  558. FBU.encoding = parseInt(RQ.shift32(), 10);
  559. timing.h_bytes += 12;
  560. if (RFB.encNames[FBU.encoding]) {
  561. // Debug:
  562. /*
  563. msg = "FramebufferUpdate rects:" + FBU.rects;
  564. msg += " x: " + FBU.x + " y: " + FBU.y
  565. msg += " width: " + FBU.width + " height: " + FBU.height;
  566. msg += " encoding:" + FBU.encoding;
  567. msg += "(" + RFB.encNames[FBU.encoding] + ")";
  568. msg += ", RQ.length: " + RQ.length;
  569. Util.Debug(msg);
  570. */
  571. } else {
  572. RFB.updateState('failed',
  573. "Disconnected: unsupported encoding " +
  574. FBU.encoding);
  575. return false;
  576. }
  577. }
  578. timing.last_fbu = (new Date()).getTime();
  579. last_bytes = RQ.length;
  580. last_rects = FBU.rects;
  581. ret = RFB.encHandlers[FBU.encoding]();
  582. now = (new Date()).getTime();
  583. timing.cur_fbu += (now - timing.last_fbu);
  584. timing.h_bytes += last_bytes-RQ.length;
  585. if (FBU.rects < last_rects) {
  586. // Some work was done
  587. timing.h_rects += last_rects-FBU.rects;
  588. timing.h_pixels += FBU.width*FBU.height;
  589. }
  590. if (FBU.rects === 0) {
  591. if (((FBU.width === RFB.fb_width) &&
  592. (FBU.height === RFB.fb_height)) ||
  593. (timing.fbu_rt_start > 0)) {
  594. timing.full_fbu_total += timing.cur_fbu;
  595. timing.full_fbu_cnt += 1;
  596. Util.Info("Timing of full FBU, cur: " +
  597. timing.cur_fbu + ", total: " +
  598. timing.full_fbu_total + ", cnt: " +
  599. timing.full_fbu_cnt + ", avg: " +
  600. (timing.full_fbu_total /
  601. timing.full_fbu_cnt));
  602. }
  603. if (timing.fbu_rt_start > 0) {
  604. fbu_rt_diff = now - timing.fbu_rt_start;
  605. timing.fbu_rt_total += fbu_rt_diff;
  606. timing.fbu_rt_cnt += 1;
  607. Util.Info("full FBU round-trip, cur: " +
  608. fbu_rt_diff + ", total: " +
  609. timing.fbu_rt_total + ", cnt: " +
  610. timing.fbu_rt_cnt + ", avg: " +
  611. (timing.fbu_rt_total /
  612. timing.fbu_rt_cnt));
  613. timing.fbu_rt_start = 0;
  614. }
  615. }
  616. if (RFB.state !== "normal") { return true; }
  617. }
  618. return ret;
  619. },
  620. /*
  621. * FramebufferUpdate encodings
  622. */
  623. display_raw: function () {
  624. //Util.Debug(">> display_raw");
  625. var RQ = RFB.RQ, FBU = RFB.FBU, cur_y, cur_height;
  626. if (FBU.lines === 0) {
  627. FBU.lines = FBU.height;
  628. }
  629. FBU.bytes = FBU.width * RFB.fb_Bpp; // At least a line
  630. if (RQ.length < FBU.bytes) {
  631. //Util.Debug(" waiting for " +
  632. // (FBU.bytes - RQ.length) + " RAW bytes");
  633. return;
  634. }
  635. cur_y = FBU.y + (FBU.height - FBU.lines);
  636. cur_height = Math.min(FBU.lines,
  637. Math.floor(RQ.length/(FBU.width * RFB.fb_Bpp)));
  638. Canvas.blitImage(FBU.x, cur_y, FBU.width, cur_height, RQ, 0);
  639. RQ.shiftBytes(FBU.width * cur_height * RFB.fb_Bpp);
  640. FBU.lines -= cur_height;
  641. if (FBU.lines > 0) {
  642. FBU.bytes = FBU.width * RFB.fb_Bpp; // At least another line
  643. } else {
  644. FBU.rects -= 1;
  645. FBU.bytes = 0;
  646. }
  647. },
  648. display_copy_rect: function () {
  649. //Util.Debug(">> display_copy_rect");
  650. var RQ = RFB.RQ, FBU = RFB.FBU, old_x, old_y;
  651. if (RQ.length < 4) {
  652. //Util.Debug(" waiting for " +
  653. // (FBU.bytes - RQ.length) + " COPYRECT bytes");
  654. return;
  655. }
  656. old_x = RQ.shift16();
  657. old_y = RQ.shift16();
  658. Canvas.copyImage(old_x, old_y, FBU.x, FBU.y, FBU.width, FBU.height);
  659. FBU.rects -= 1;
  660. FBU.bytes = 0;
  661. },
  662. display_rre: function () {
  663. //Util.Debug(">> display_rre (" + RFB.RQ.length + " bytes)");
  664. var RQ = RFB.RQ, FBU = RFB.FBU, color, x, y, width, height, chunk;
  665. if (FBU.subrects === 0) {
  666. if (RQ.length < 4 + RFB.fb_Bpp) {
  667. //Util.Debug(" waiting for " +
  668. // (4 + RFB.fb_Bpp - RQ.length) + " RRE bytes");
  669. return;
  670. }
  671. FBU.subrects = RQ.shift32();
  672. color = RQ.shiftBytes(RFB.fb_Bpp); // Background
  673. Canvas.fillRect(FBU.x, FBU.y, FBU.width, FBU.height, color);
  674. }
  675. while ((FBU.subrects > 0) && (RQ.length >= (RFB.fb_Bpp + 8))) {
  676. color = RQ.shiftBytes(RFB.fb_Bpp);
  677. x = RQ.shift16();
  678. y = RQ.shift16();
  679. width = RQ.shift16();
  680. height = RQ.shift16();
  681. Canvas.fillRect(FBU.x + x, FBU.y + y, width, height, color);
  682. FBU.subrects -= 1;
  683. }
  684. //Util.Debug(" display_rre: rects: " + FBU.rects +
  685. // ", FBU.subrects: " + FBU.subrects);
  686. if (FBU.subrects > 0) {
  687. chunk = Math.min(RFB.rre_chunk, FBU.subrects);
  688. FBU.bytes = (RFB.fb_Bpp + 8) * chunk;
  689. } else {
  690. FBU.rects -= 1;
  691. FBU.bytes = 0;
  692. }
  693. //Util.Debug("<< display_rre, FBU.bytes: " + FBU.bytes);
  694. },
  695. display_hextile: function() {
  696. //Util.Debug(">> display_hextile");
  697. var RQ = RFB.RQ, FBU = RFB.FBU,
  698. subencoding, subrects, idx, tile, color, cur_tile,
  699. tile_x, x, w, tile_y, y, h, xy, s, sx, sy, wh, sw, sh;
  700. if (FBU.tiles === 0) {
  701. FBU.tiles_x = Math.ceil(FBU.width/16);
  702. FBU.tiles_y = Math.ceil(FBU.height/16);
  703. FBU.total_tiles = FBU.tiles_x * FBU.tiles_y;
  704. FBU.tiles = FBU.total_tiles;
  705. }
  706. /* FBU.bytes comes in as 1, RQ.length at least 1 */
  707. while (FBU.tiles > 0) {
  708. FBU.bytes = 1;
  709. if (RQ.length < FBU.bytes) {
  710. //Util.Debug(" waiting for HEXTILE subencoding byte");
  711. return;
  712. }
  713. subencoding = RQ[0]; // Peek
  714. if (subencoding > 30) { // Raw
  715. RFB.updateState('failed',
  716. "Disconnected: illegal hextile subencoding " + subencoding);
  717. //Util.Debug("RQ.slice(0,30):" + RQ.slice(0,30));
  718. return;
  719. }
  720. subrects = 0;
  721. cur_tile = FBU.total_tiles - FBU.tiles;
  722. tile_x = cur_tile % FBU.tiles_x;
  723. tile_y = Math.floor(cur_tile / FBU.tiles_x);
  724. x = FBU.x + tile_x * 16;
  725. y = FBU.y + tile_y * 16;
  726. w = Math.min(16, (FBU.x + FBU.width) - x);
  727. h = Math.min(16, (FBU.y + FBU.height) - y);
  728. /* Figure out how much we are expecting */
  729. if (subencoding & 0x01) { // Raw
  730. //Util.Debug(" Raw subencoding");
  731. FBU.bytes += w * h * RFB.fb_Bpp;
  732. } else {
  733. if (subencoding & 0x02) { // Background
  734. FBU.bytes += RFB.fb_Bpp;
  735. }
  736. if (subencoding & 0x04) { // Foreground
  737. FBU.bytes += RFB.fb_Bpp;
  738. }
  739. if (subencoding & 0x08) { // AnySubrects
  740. FBU.bytes += 1; // Since we aren't shifting it off
  741. if (RQ.length < FBU.bytes) {
  742. /* Wait for subrects byte */
  743. //Util.Debug(" waiting for hextile subrects header byte");
  744. return;
  745. }
  746. subrects = RQ[FBU.bytes-1]; // Peek
  747. if (subencoding & 0x10) { // SubrectsColoured
  748. FBU.bytes += subrects * (RFB.fb_Bpp + 2);
  749. } else {
  750. FBU.bytes += subrects * 2;
  751. }
  752. }
  753. }
  754. //Util.Debug(" tile:" + cur_tile + "/" + (FBU.total_tiles - 1) +
  755. // ", subencoding:" + subencoding +
  756. // "(last: " + FBU.lastsubencoding + "), subrects:" +
  757. // subrects + ", tile:" + tile_x + "," + tile_y +
  758. // " [" + x + "," + y + "]@" + w + "x" + h +
  759. // ", d.length:" + RQ.length + ", bytes:" + FBU.bytes +
  760. // " last:" + RQ.slice(FBU.bytes-10, FBU.bytes) +
  761. // " next:" + RQ.slice(FBU.bytes-1, FBU.bytes+10));
  762. if (RQ.length < FBU.bytes) {
  763. //Util.Debug(" waiting for " +
  764. // (FBU.bytes - RQ.length) + " hextile bytes");
  765. return;
  766. }
  767. /* We know the encoding and have a whole tile */
  768. FBU.subencoding = RQ[0];
  769. idx = 1;
  770. if (FBU.subencoding === 0) {
  771. if (FBU.lastsubencoding & 0x01) {
  772. /* Weird: ignore blanks after RAW */
  773. Util.Debug(" Ignoring blank after RAW");
  774. } else {
  775. Canvas.fillRect(x, y, w, h, FBU.background);
  776. }
  777. } else if (FBU.subencoding & 0x01) { // Raw
  778. Canvas.blitImage(x, y, w, h, RQ, idx);
  779. } else {
  780. if (FBU.subencoding & 0x02) { // Background
  781. FBU.background = RQ.slice(idx, idx + RFB.fb_Bpp);
  782. idx += RFB.fb_Bpp;
  783. }
  784. if (FBU.subencoding & 0x04) { // Foreground
  785. FBU.foreground = RQ.slice(idx, idx + RFB.fb_Bpp);
  786. idx += RFB.fb_Bpp;
  787. }
  788. tile = Canvas.getTile(x, y, w, h, FBU.background);
  789. if (FBU.subencoding & 0x08) { // AnySubrects
  790. subrects = RQ[idx];
  791. idx += 1;
  792. for (s = 0; s < subrects; s += 1) {
  793. if (FBU.subencoding & 0x10) { // SubrectsColoured
  794. color = RQ.slice(idx, idx + RFB.fb_Bpp);
  795. idx += RFB.fb_Bpp;
  796. } else {
  797. color = FBU.foreground;
  798. }
  799. xy = RQ[idx];
  800. idx += 1;
  801. sx = (xy >> 4);
  802. sy = (xy & 0x0f);
  803. wh = RQ[idx];
  804. idx += 1;
  805. sw = (wh >> 4) + 1;
  806. sh = (wh & 0x0f) + 1;
  807. Canvas.setSubTile(tile, sx, sy, sw, sh, color);
  808. }
  809. }
  810. Canvas.putTile(tile);
  811. }
  812. RQ.shiftBytes(FBU.bytes);
  813. FBU.lastsubencoding = FBU.subencoding;
  814. FBU.bytes = 0;
  815. FBU.tiles -= 1;
  816. }
  817. if (FBU.tiles === 0) {
  818. FBU.rects -= 1;
  819. }
  820. //Util.Debug("<< display_hextile");
  821. },
  822. display_tight_png: function() {
  823. //Util.Debug(">> display_tight_png");
  824. var RQ = RFB.RQ, FBU = RFB.FBU,
  825. ctl, cmode, clength, getCLength, color, img;
  826. //Util.Debug(" FBU.rects: " + FBU.rects);
  827. //Util.Debug(" RQ.length: " + RQ.length);
  828. //Util.Debug(" RQ.slice(0,20): " + RQ.slice(0,20));
  829. FBU.bytes = 1; // compression-control byte
  830. if (RQ.length < FBU.bytes) {
  831. Util.Debug(" waiting for TIGHT compression-control byte");
  832. return;
  833. }
  834. // Get 'compact length' header and data size
  835. getCLength = function (arr, offset) {
  836. var header = 1, data = 0;
  837. data += arr[offset + 0] & 0x7f;
  838. if (arr[offset + 0] & 0x80) {
  839. header += 1;
  840. data += (arr[offset + 1] & 0x7f) << 7;
  841. if (arr[offset + 1] & 0x80) {
  842. header += 1;
  843. data += arr[offset + 2] << 14;
  844. }
  845. }
  846. return [header, data];
  847. };
  848. ctl = RQ[0];
  849. switch (ctl >> 4) {
  850. case 0x08: cmode = "fill"; break;
  851. case 0x09: cmode = "jpeg"; break;
  852. case 0x0A: cmode = "png"; break;
  853. default: throw("Illegal basic compression received, ctl: " + ctl);
  854. }
  855. switch (cmode) {
  856. // fill uses fb_depth because TPIXELs drop the padding byte
  857. case "fill": FBU.bytes += RFB.fb_depth; break; // TPIXEL
  858. case "jpeg": FBU.bytes += 3; break; // max clength
  859. case "png": FBU.bytes += 3; break; // max clength
  860. }
  861. if (RQ.length < FBU.bytes) {
  862. Util.Debug(" waiting for TIGHT " + cmode + " bytes");
  863. return;
  864. }
  865. //Util.Debug(" RQ.slice(0,20): " + RFB.RQ.slice(0,20) + " (" + RFB.RQ.length + ")");
  866. //Util.Debug(" cmode: " + cmode);
  867. // Determine FBU.bytes
  868. switch (cmode) {
  869. case "fill":
  870. RQ.shift8(); // shift off ctl
  871. color = RQ.shiftBytes(RFB.fb_depth);
  872. Canvas.fillRect(FBU.x, FBU.y, FBU.width, FBU.height, color);
  873. break;
  874. case "jpeg":
  875. case "png":
  876. clength = getCLength(RQ, 1);
  877. FBU.bytes = 1 + clength[0] + clength[1]; // ctl + clength size + jpeg-data
  878. if (RQ.length < FBU.bytes) {
  879. Util.Debug(" waiting for TIGHT " + cmode + " bytes");
  880. return;
  881. }
  882. // We have everything, render it
  883. //Util.Debug(" png, RQ.length: " + RQ.length + ", clength[0]: " + clength[0] + ", clength[1]: " + clength[1]);
  884. RQ.shiftBytes(1 + clength[0]); // shift off ctl + compact length
  885. img = new Image();
  886. img.onload = RFB.scan_tight_imgs;
  887. FBU.imgs.push([img, FBU.x, FBU.y]);
  888. img.src = "data:image/" + cmode +
  889. RFB.extract_data_uri(RQ.shiftBytes(clength[1]));
  890. img = null;
  891. break;
  892. }
  893. FBU.bytes = 0;
  894. FBU.rects -= 1;
  895. //Util.Debug(" ending RQ.length: " + RQ.length);
  896. //Util.Debug(" ending RQ.slice(0,20): " + RQ.slice(0,20));
  897. //Util.Debug("<< display_tight_png");
  898. },
  899. extract_data_uri : function (arr) {
  900. //var i, stra = [];
  901. //for (i=0; i< arr.length; i += 1) {
  902. // stra.push(String.fromCharCode(arr[i]));
  903. //}
  904. //return "," + escape(stra.join(''));
  905. return ";base64," + Base64.encode(arr);
  906. },
  907. scan_tight_imgs : function () {
  908. var img, imgs;
  909. if (RFB.state === 'normal') {
  910. imgs = RFB.FBU.imgs;
  911. while ((imgs.length > 0) && (imgs[0][0].complete)) {
  912. img = imgs.shift();
  913. Canvas.ctx.drawImage(img[0], img[1], img[2]);
  914. }
  915. setTimeout(RFB.scan_tight_imgs, RFB.scan_imgs_rate);
  916. }
  917. },
  918. set_desktopsize : function () {
  919. Util.Debug(">> set_desktopsize");
  920. RFB.fb_width = RFB.FBU.width;
  921. RFB.fb_height = RFB.FBU.height;
  922. Canvas.clear();
  923. Canvas.resize(RFB.fb_width, RFB.fb_height);
  924. RFB.timing.fbu_rt_start = (new Date()).getTime();
  925. // Send a new non-incremental request
  926. RFB.send_array(RFB.fbUpdateRequest(0));
  927. RFB.FBU.bytes = 0;
  928. RFB.FBU.rects -= 1;
  929. Util.Debug("<< set_desktopsize");
  930. },
  931. set_cursor: function () {
  932. var x, y, w, h, pixelslength, masklength;
  933. //Util.Debug(">> set_cursor");
  934. x = RFB.FBU.x; // hotspot-x
  935. y = RFB.FBU.y; // hotspot-y
  936. w = RFB.FBU.width;
  937. h = RFB.FBU.height;
  938. pixelslength = w * h * RFB.fb_Bpp;
  939. masklength = Math.floor((w + 7) / 8) * h;
  940. if (RFB.RQ.length < (pixelslength + masklength)) {
  941. //Util.Debug("waiting for cursor encoding bytes");
  942. RFB.FBU.bytes = pixelslength + masklength;
  943. return false;
  944. }
  945. //Util.Debug(" set_cursor, x: " + x + ", y: " + y + ", w: " + w + ", h: " + h);
  946. Canvas.changeCursor(RFB.RQ.shiftBytes(pixelslength),
  947. RFB.RQ.shiftBytes(masklength),
  948. x, y, w, h);
  949. RFB.FBU.bytes = 0;
  950. RFB.FBU.rects -= 1;
  951. //Util.Debug("<< set_cursor");
  952. },
  953. set_jpeg_quality : function () {
  954. Util.Debug(">> set_jpeg_quality");
  955. },
  956. set_compress_level: function () {
  957. Util.Debug(">> set_compress_level");
  958. },
  959. /*
  960. * Client message routines
  961. */
  962. pixelFormat: function () {
  963. //Util.Debug(">> pixelFormat");
  964. var arr;
  965. arr = [0]; // msg-type
  966. arr.push8(0); // padding
  967. arr.push8(0); // padding
  968. arr.push8(0); // padding
  969. arr.push8(RFB.fb_Bpp * 8); // bits-per-pixel
  970. arr.push8(RFB.fb_depth * 8); // depth
  971. arr.push8(0); // little-endian
  972. arr.push8(RFB.true_color); // true-color
  973. arr.push16(255); // red-max
  974. arr.push16(255); // green-max
  975. arr.push16(255); // blue-max
  976. arr.push8(0); // red-shift
  977. arr.push8(8); // green-shift
  978. arr.push8(16); // blue-shift
  979. arr.push8(0); // padding
  980. arr.push8(0); // padding
  981. arr.push8(0); // padding
  982. //Util.Debug("<< pixelFormat");
  983. return arr;
  984. },
  985. fixColourMapEntries: function () {
  986. },
  987. clientEncodings: function () {
  988. //Util.Debug(">> clientEncodings");
  989. var arr, i, encList = [];
  990. for (i=0; i<RFB.encodings.length; i += 1) {
  991. if ((RFB.encodings[i][0] === "Cursor") &&
  992. (! RFB.local_cursor)) {
  993. Util.Debug("Skipping Cursor pseudo-encoding");
  994. } else {
  995. //Util.Debug("Adding encoding: " + RFB.encodings[i][0]);
  996. encList.push(RFB.encodings[i][1]);
  997. }
  998. }
  999. arr = [2]; // msg-type
  1000. arr.push8(0); // padding
  1001. arr.push16(encList.length); // encoding count
  1002. for (i=0; i < encList.length; i += 1) {
  1003. arr.push32(encList[i]);
  1004. }
  1005. //Util.Debug("<< clientEncodings: " + arr);
  1006. return arr;
  1007. },
  1008. fbUpdateRequest: function (incremental, x, y, xw, yw) {
  1009. //Util.Debug(">> fbUpdateRequest");
  1010. if (!x) { x = 0; }
  1011. if (!y) { y = 0; }
  1012. if (!xw) { xw = RFB.fb_width; }
  1013. if (!yw) { yw = RFB.fb_height; }
  1014. var arr;
  1015. arr = [3]; // msg-type
  1016. arr.push8(incremental);
  1017. arr.push16(x);
  1018. arr.push16(y);
  1019. arr.push16(xw);
  1020. arr.push16(yw);
  1021. //Util.Debug("<< fbUpdateRequest");
  1022. return arr;
  1023. },
  1024. keyEvent: function (keysym, down) {
  1025. //Util.Debug(">> keyEvent, keysym: " + keysym + ", down: " + down);
  1026. var arr;
  1027. arr = [4]; // msg-type
  1028. arr.push8(down);
  1029. arr.push16(0);
  1030. arr.push32(keysym);
  1031. //Util.Debug("<< keyEvent");
  1032. return arr;
  1033. },
  1034. pointerEvent: function (x, y) {
  1035. //Util.Debug(">> pointerEvent, x,y: " + x + "," + y +
  1036. // " , mask: " + RFB.mouse_buttonMask);
  1037. var arr;
  1038. arr = [5]; // msg-type
  1039. arr.push8(RFB.mouse_buttonMask);
  1040. arr.push16(x);
  1041. arr.push16(y);
  1042. //Util.Debug("<< pointerEvent");
  1043. return arr;
  1044. },
  1045. clientCutText: function (text) {
  1046. //Util.Debug(">> clientCutText");
  1047. var arr;
  1048. arr = [6]; // msg-type
  1049. arr.push8(0); // padding
  1050. arr.push8(0); // padding
  1051. arr.push8(0); // padding
  1052. arr.push32(text.length);
  1053. arr.pushStr(text);
  1054. //Util.Debug("<< clientCutText:" + arr);
  1055. return arr;
  1056. },
  1057. /*
  1058. * Utility routines
  1059. */
  1060. encode_message: function(arr) {
  1061. if (RFB.b64encode) {
  1062. /* base64 encode */
  1063. RFB.SQ = RFB.SQ + Base64.encode(arr);
  1064. } else {
  1065. /* UTF-8 encode. 0 -> 256 to avoid WebSockets framing */
  1066. RFB.SQ = RFB.SQ + arr.map(function (num) {
  1067. if (num === 0) {
  1068. return String.fromCharCode(256);
  1069. } else {
  1070. return String.fromCharCode(num);
  1071. }
  1072. } ).join('');
  1073. }
  1074. },
  1075. decode_message: function(data) {
  1076. var raw, i, length, RQ = RFB.RQ;
  1077. //Util.Debug(">> decode_message: " + data);
  1078. if (RFB.b64encode) {
  1079. /* base64 decode */
  1080. RFB.RQ = RFB.RQ.concat(Base64.decode(data, 0));
  1081. } else {
  1082. /* UTF-8 decode. 256 -> 0 to WebSockets framing */
  1083. length = data.length;
  1084. for (i=0; i < length; i += 1) {
  1085. RQ.push(data.charCodeAt(i) % 256);
  1086. }
  1087. }
  1088. //Util.Debug(">> decode_message, RQ: " + RFB.RQ);
  1089. },
  1090. recv_message: function(e) {
  1091. //Util.Debug(">> recv_message");
  1092. try {
  1093. RFB.decode_message(e.data);
  1094. if (RFB.RQ.length > 0) {
  1095. RFB.handle_message();
  1096. } else {
  1097. Util.Debug("Ignoring empty message");
  1098. }
  1099. } catch (exc) {
  1100. if (typeof exc.stack !== 'undefined') {
  1101. Util.Warn("recv_message, caught exception: " + exc.stack);
  1102. } else if (typeof exc.description !== 'undefined') {
  1103. Util.Warn("recv_message, caught exception: " + exc.description);
  1104. } else {
  1105. Util.Warn("recv_message, caught exception:" + exc);
  1106. }
  1107. if (typeof exc.name !== 'undefined') {
  1108. RFB.updateState('failed', exc.name + ": " + exc.message);
  1109. } else {
  1110. RFB.updateState('failed', exc);
  1111. }
  1112. }
  1113. //Util.Debug("<< recv_message");
  1114. },
  1115. handle_message: function () {
  1116. //Util.Debug("RQ.slice(0,20): " + RFB.RQ.slice(0,20) + " (" + RFB.RQ.length + ")");
  1117. switch (RFB.state) {
  1118. case 'disconnected':
  1119. Util.Error("Got data while disconnected");
  1120. break;
  1121. case 'failed':
  1122. Util.Warn("Giving up!");
  1123. RFB.disconnect();
  1124. break;
  1125. case 'normal':
  1126. RFB.normal_msg();
  1127. /*
  1128. while (RFB.RQ.length > 0) {
  1129. if (RFB.normal_msg() && RFB.state === 'normal') {
  1130. Util.Debug("More to process");
  1131. } else {
  1132. break;
  1133. }
  1134. }
  1135. */
  1136. break;
  1137. default:
  1138. RFB.init_msg();
  1139. break;
  1140. }
  1141. },
  1142. send_string: function (str) {
  1143. //Util.Debug(">> send_string: " + str);
  1144. RFB.send_array(str.split('').map(
  1145. function (chr) { return chr.charCodeAt(0); } ) );
  1146. },
  1147. send_array: function (arr) {
  1148. //Util.Debug(">> send_array: " + arr);
  1149. RFB.encode_message(arr);
  1150. if (RFB.ws.bufferedAmount === 0) {
  1151. //Util.Debug("arr: " + arr);
  1152. //Util.Debug("RFB.SQ: " + RFB.SQ);
  1153. RFB.ws.send(RFB.SQ);
  1154. RFB.SQ = "";
  1155. } else {
  1156. Util.Debug("Delaying send");
  1157. }
  1158. },
  1159. DES: function (password, challenge) {
  1160. var i, passwd, response;
  1161. passwd = [];
  1162. response = challenge.slice();
  1163. for (i=0; i < password.length; i += 1) {
  1164. passwd.push(password.charCodeAt(i));
  1165. }
  1166. DES.setKeys(passwd);
  1167. DES.encrypt(response, 0, response, 0);
  1168. DES.encrypt(response, 8, response, 8);
  1169. return response;
  1170. },
  1171. flushClient: function () {
  1172. if (RFB.mouse_arr.length > 0) {
  1173. //RFB.send_array(RFB.mouse_arr.concat(RFB.fbUpdateRequest(1)));
  1174. RFB.send_array(RFB.mouse_arr);
  1175. setTimeout(function() {
  1176. RFB.send_array(RFB.fbUpdateRequest(1));
  1177. }, 50);
  1178. RFB.mouse_arr = [];
  1179. return true;
  1180. } else {
  1181. return false;
  1182. }
  1183. },
  1184. checkEvents: function () {
  1185. var now;
  1186. if (RFB.state === 'normal') {
  1187. if (! RFB.flushClient()) {
  1188. now = new Date().getTime();
  1189. if (now > RFB.last_req + RFB.req_rate) {
  1190. RFB.last_req = now;
  1191. RFB.send_array(RFB.fbUpdateRequest(1));
  1192. }
  1193. }
  1194. }
  1195. setTimeout(RFB.checkEvents, RFB.check_rate);
  1196. },
  1197. keyPress: function (keysym, down) {
  1198. var arr;
  1199. arr = RFB.keyEvent(keysym, down);
  1200. arr = arr.concat(RFB.fbUpdateRequest(1));
  1201. RFB.send_array(arr);
  1202. },
  1203. mouseButton: function(x, y, down, bmask) {
  1204. if (down) {
  1205. RFB.mouse_buttonMask |= bmask;
  1206. } else {
  1207. RFB.mouse_buttonMask ^= bmask;
  1208. }
  1209. RFB.mouse_arr = RFB.mouse_arr.concat( RFB.pointerEvent(x, y) );
  1210. RFB.flushClient();
  1211. },
  1212. mouseMove: function(x, y) {
  1213. //Util.Debug('>> mouseMove ' + x + "," + y);
  1214. RFB.mouse_arr = RFB.mouse_arr.concat( RFB.pointerEvent(x, y) );
  1215. },
  1216. clipboardCopyTo: function (text) {
  1217. Util.Debug(">> clipboardCopyTo stub");
  1218. // Stub
  1219. },
  1220. externalUpdateState: function(state, msg) {
  1221. Util.Debug(">> externalUpdateState stub");
  1222. // Stub
  1223. },
  1224. /*
  1225. * Running states:
  1226. * disconnected - idle state
  1227. * normal - connected
  1228. *
  1229. * Page states:
  1230. * loaded - page load, equivalent to disconnected
  1231. * connect - starting initialization
  1232. * password - waiting for password
  1233. * failed - abnormal transition to disconnected
  1234. * fatal - failed to load page, or fatal error
  1235. *
  1236. * VNC initialization states:
  1237. * ProtocolVersion
  1238. * Security
  1239. * Authentication
  1240. * SecurityResult
  1241. * ServerInitialization
  1242. */
  1243. updateState: function(state, statusMsg) {
  1244. var func, cmsg, oldstate = RFB.state;
  1245. if (state === oldstate) {
  1246. /* Already here, ignore */
  1247. Util.Debug("Already in state '" + state + "', ignoring.");
  1248. return;
  1249. }
  1250. if (oldstate === 'fatal') {
  1251. Util.Error("Fatal error, cannot continue");
  1252. }
  1253. if ((state === 'failed') || (state === 'fatal')) {
  1254. func = Util.Error;
  1255. } else {
  1256. func = Util.Warn;
  1257. }
  1258. cmsg = typeof(statusMsg) !== 'undefined' ? (" Msg: " + statusMsg) : "";
  1259. func("New state '" + state + "', was '" + oldstate + "'." + cmsg);
  1260. if ((oldstate === 'failed') && (state === 'disconnected')) {
  1261. // Do disconnect action, but stay in failed state.
  1262. RFB.state = 'failed';
  1263. } else {
  1264. RFB.state = state;
  1265. }
  1266. switch (state) {
  1267. case 'loaded':
  1268. case 'disconnected':
  1269. if (RFB.sendID) {
  1270. clearInterval(RFB.sendID);
  1271. RFB.sendID = null;
  1272. }
  1273. if (RFB.ws) {
  1274. if (RFB.ws.readyState === WebSocket.OPEN) {
  1275. RFB.ws.close();
  1276. }
  1277. RFB.ws.onmessage = function (e) { return; };
  1278. }
  1279. if (Canvas.ctx) {
  1280. Canvas.stop();
  1281. if (! /__debug__$/i.test(document.location.href)) {
  1282. Canvas.clear();
  1283. }
  1284. }
  1285. RFB.show_timings();
  1286. break;
  1287. case 'connect':
  1288. RFB.init_vars();
  1289. if ((RFB.ws) && (RFB.ws.readyState === WebSocket.OPEN)) {
  1290. RFB.ws.close();
  1291. }
  1292. RFB.init_ws(); // onopen transitions to 'ProtocolVersion'
  1293. break;
  1294. case 'password':
  1295. // Ignore password state by default
  1296. break;
  1297. case 'normal':
  1298. if ((oldstate === 'disconnected') || (oldstate === 'failed')) {
  1299. Util.Error("Invalid transition from 'disconnected' or 'failed' to 'normal'");
  1300. }
  1301. break;
  1302. case 'failed':
  1303. if (oldstate === 'disconnected') {
  1304. Util.Error("Invalid transition from 'disconnected' to 'failed'");
  1305. }
  1306. if (oldstate === 'normal') {
  1307. Util.Error("Error while connected.");
  1308. }
  1309. if (oldstate === 'init') {
  1310. Util.Error("Error while initializing.");
  1311. }
  1312. if ((RFB.ws) && (RFB.ws.readyState === WebSocket.OPEN)) {
  1313. RFB.ws.close();
  1314. }
  1315. // Make sure we transition to disconnected
  1316. setTimeout(function() { RFB.updateState('disconnected'); }, 50);
  1317. break;
  1318. default:
  1319. // Invalid state transition
  1320. }
  1321. if ((oldstate === 'failed') && (state === 'disconnected')) {
  1322. // Leave the failed message
  1323. RFB.externalUpdateState(state);
  1324. } else {
  1325. RFB.externalUpdateState(state, statusMsg);
  1326. }
  1327. },
  1328. update_timings: function() {
  1329. var now, timing = RFB.timing, offset;
  1330. now = (new Date()).getTime();
  1331. timing.history.push([now,
  1332. timing.h_fbus,
  1333. timing.h_rects,
  1334. timing.h_bytes,
  1335. timing.h_pixels]);
  1336. timing.h_fbus = 0;
  1337. timing.h_rects = 0;
  1338. timing.h_bytes = 0;
  1339. timing.h_pixels = 0;
  1340. if ((RFB.state !== 'disconnected') && (RFB.state !== 'failed')) {
  1341. // Try for every second
  1342. offset = (now - timing.history_start) % 1000;
  1343. if (offset < 500) {
  1344. setTimeout(RFB.update_timings, 1000 - offset);
  1345. } else {
  1346. setTimeout(RFB.update_timings, 2000 - offset);
  1347. }
  1348. }
  1349. },
  1350. show_timings: function() {
  1351. var i, timing = RFB.timing, history, msg,
  1352. delta, tot_time = 0, tot_fbus = 0, tot_rects = 0,
  1353. tot_bytes = 0, tot_pixels = 0;
  1354. if (timing.history_start === 0) { return; }
  1355. //Util.Debug(">> show_timings");
  1356. RFB.update_timings(); // Final accumulate
  1357. msg = "\nTimings\n";
  1358. msg += " time: fbus,rects,bytes,pixels\n";
  1359. for (i=0; i < timing.history.length; i += 1) {
  1360. history = timing.history[i];
  1361. delta = ((history[0]-timing.history_start)/1000);
  1362. tot_time = delta;
  1363. tot_fbus += history[1];
  1364. tot_rects += history[2];
  1365. tot_bytes += history[3];
  1366. tot_pixels += history[4];
  1367. msg += " " + delta.toFixed(3);
  1368. msg += ": " + history.slice(1) + "\n";
  1369. }
  1370. msg += "\nTotals:\n";
  1371. msg += " time: fbus,rects,bytes,pixels\n";
  1372. msg += " " + tot_time.toFixed(3);
  1373. msg += ": " + tot_fbus + "," + tot_rects;
  1374. msg += "," + tot_bytes + "," + tot_pixels;
  1375. Util.Info(msg);
  1376. //Util.Debug("<< show_timings");
  1377. },
  1378. /*
  1379. * Setup routines
  1380. */
  1381. init_ws: function () {
  1382. //Util.Debug(">> init_ws");
  1383. var uri = "", vars = [];
  1384. if (RFB.encrypt) {
  1385. uri = "wss://";
  1386. } else {
  1387. uri = "ws://";
  1388. }
  1389. uri += RFB.host + ":" + RFB.port + "/";
  1390. if (RFB.b64encode) {
  1391. vars.push("b64encode");
  1392. }
  1393. if (vars.length > 0) {
  1394. uri += "?" + vars.join("&");
  1395. }
  1396. Util.Info("connecting to " + uri);
  1397. RFB.ws = new WebSocket(uri);
  1398. RFB.ws.onmessage = RFB.recv_message;
  1399. RFB.ws.onopen = function(e) {
  1400. Util.Debug(">> WebSocket.onopen");
  1401. if (RFB.state === "connect") {
  1402. RFB.updateState('ProtocolVersion', "Starting VNC handshake");
  1403. } else {
  1404. RFB.updateState('failed', "Got unexpected WebSockets connection");
  1405. }
  1406. Util.Debug("<< WebSocket.onopen");
  1407. };
  1408. RFB.ws.onclose = function(e) {
  1409. Util.Debug(">> WebSocket.onclose");
  1410. if (RFB.state === 'normal') {
  1411. RFB.updateState('failed', 'Server disconnected');
  1412. } else if (RFB.state === 'ProtocolVersion') {
  1413. RFB.updateState('failed', 'Failed to connect to server');
  1414. } else {
  1415. RFB.updateState('disconnected', 'VNC disconnected');
  1416. }
  1417. Util.Debug("<< WebSocket.onclose");
  1418. };
  1419. RFB.ws.onerror = function(e) {
  1420. Util.Debug(">> WebSocket.onerror");
  1421. RFB.updateState('failed', "WebSocket error");
  1422. Util.Debug("<< WebSocket.onerror");
  1423. };
  1424. setTimeout(function () {
  1425. if (RFB.ws.readyState === WebSocket.CONNECTING) {
  1426. RFB.updateState('failed', "Connect timeout");
  1427. }
  1428. }, RFB.connectTimeout);
  1429. //Util.Debug("<< init_ws");
  1430. },
  1431. init_vars: function () {
  1432. /* Reset state */
  1433. RFB.cuttext = 'none';
  1434. RFB.ct_length = 0;
  1435. RFB.RQ = [];
  1436. RFB.SQ = "";
  1437. RFB.FBU.rects = 0;
  1438. RFB.FBU.subrects = 0; // RRE and HEXTILE
  1439. RFB.FBU.lines = 0; // RAW
  1440. RFB.FBU.tiles = 0; // HEXTILE
  1441. RFB.FBU.imgs = []; // TIGHT_PNG image queue
  1442. RFB.mouse_buttonmask = 0;
  1443. RFB.mouse_arr = [];
  1444. RFB.timing.history_start = 0;
  1445. RFB.timing.history = [];
  1446. RFB.timing.h_fbus = 0;
  1447. RFB.timing.h_rects = 0;
  1448. RFB.timing.h_bytes = 0;
  1449. RFB.timing.h_pixels = 0;
  1450. }
  1451. }; /* End of RFB */