vnc.js 46 KB

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