You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

622 lines
17 KiB

  1. /**
  2. * Wrapper for built-in http.js to emulate the browser XMLHttpRequest object.
  3. *
  4. * This can be used with JS designed for browsers to improve reuse of code and
  5. * allow the use of existing libraries.
  6. *
  7. * Usage: include("XMLHttpRequest.js") and use XMLHttpRequest per W3C specs.
  8. *
  9. * @author Dan DeFelippi <dan@driverdan.com>
  10. * @contributor David Ellis <d.f.ellis@ieee.org>
  11. * @license MIT
  12. */
  13. var fs = require('fs');
  14. var Url = require('url');
  15. var spawn = require('child_process').spawn;
  16. /**
  17. * Module exports.
  18. */
  19. module.exports = XMLHttpRequest;
  20. // backwards-compat
  21. XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
  22. /**
  23. * `XMLHttpRequest` constructor.
  24. *
  25. * Supported options for the `opts` object are:
  26. *
  27. * - `agent`: An http.Agent instance; http.globalAgent may be used; if 'undefined', agent usage is disabled
  28. *
  29. * @param {Object} opts optional "options" object
  30. */
  31. function XMLHttpRequest(opts) {
  32. /**
  33. * Private variables
  34. */
  35. var self = this;
  36. var http = require('http');
  37. var https = require('https');
  38. // Holds http.js objects
  39. var request;
  40. var response;
  41. // Request settings
  42. var settings = {};
  43. // Disable header blacklist.
  44. // Not part of XHR specs.
  45. var disableHeaderCheck = false;
  46. // Set some default headers
  47. var defaultHeaders = {
  48. "User-Agent": "node-XMLHttpRequest",
  49. "Accept": "*/*"
  50. };
  51. var headers = defaultHeaders;
  52. // These headers are not user setable.
  53. // The following are allowed but banned in the spec:
  54. // * user-agent
  55. var forbiddenRequestHeaders = [
  56. "accept-charset",
  57. "accept-encoding",
  58. "access-control-request-headers",
  59. "access-control-request-method",
  60. "connection",
  61. "content-length",
  62. "content-transfer-encoding",
  63. "cookie",
  64. "cookie2",
  65. "date",
  66. "expect",
  67. "host",
  68. "keep-alive",
  69. "origin",
  70. "referer",
  71. "te",
  72. "trailer",
  73. "transfer-encoding",
  74. "upgrade",
  75. "via"
  76. ];
  77. // These request methods are not allowed
  78. var forbiddenRequestMethods = [
  79. "TRACE",
  80. "TRACK",
  81. "CONNECT"
  82. ];
  83. // Send flag
  84. var sendFlag = false;
  85. // Error flag, used when errors occur or abort is called
  86. var errorFlag = false;
  87. // Event listeners
  88. var listeners = {};
  89. /**
  90. * Constants
  91. */
  92. this.UNSENT = 0;
  93. this.OPENED = 1;
  94. this.HEADERS_RECEIVED = 2;
  95. this.LOADING = 3;
  96. this.DONE = 4;
  97. /**
  98. * Public vars
  99. */
  100. // Current state
  101. this.readyState = this.UNSENT;
  102. // default ready state change handler in case one is not set or is set late
  103. this.onreadystatechange = null;
  104. // Result & response
  105. this.responseText = "";
  106. this.responseXML = "";
  107. this.status = null;
  108. this.statusText = null;
  109. /**
  110. * Private methods
  111. */
  112. /**
  113. * Check if the specified header is allowed.
  114. *
  115. * @param string header Header to validate
  116. * @return boolean False if not allowed, otherwise true
  117. */
  118. var isAllowedHttpHeader = function(header) {
  119. return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
  120. };
  121. /**
  122. * Check if the specified method is allowed.
  123. *
  124. * @param string method Request method to validate
  125. * @return boolean False if not allowed, otherwise true
  126. */
  127. var isAllowedHttpMethod = function(method) {
  128. return (method && forbiddenRequestMethods.indexOf(method) === -1);
  129. };
  130. /**
  131. * Public methods
  132. */
  133. /**
  134. * Open the connection. Currently supports local server requests.
  135. *
  136. * @param string method Connection method (eg GET, POST)
  137. * @param string url URL for the connection.
  138. * @param boolean async Asynchronous connection. Default is true.
  139. * @param string user Username for basic authentication (optional)
  140. * @param string password Password for basic authentication (optional)
  141. */
  142. this.open = function(method, url, async, user, password) {
  143. this.abort();
  144. errorFlag = false;
  145. // Check for valid request method
  146. if (!isAllowedHttpMethod(method)) {
  147. throw "SecurityError: Request method not allowed";
  148. }
  149. settings = {
  150. "method": method,
  151. "url": url.toString(),
  152. "async": (typeof async !== "boolean" ? true : async),
  153. "user": user || null,
  154. "password": password || null
  155. };
  156. setState(this.OPENED);
  157. };
  158. /**
  159. * Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
  160. * This does not conform to the W3C spec.
  161. *
  162. * @param boolean state Enable or disable header checking.
  163. */
  164. this.setDisableHeaderCheck = function(state) {
  165. disableHeaderCheck = state;
  166. };
  167. /**
  168. * Sets a header for the request.
  169. *
  170. * @param string header Header name
  171. * @param string value Header value
  172. */
  173. this.setRequestHeader = function(header, value) {
  174. if (this.readyState != this.OPENED) {
  175. throw "INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN";
  176. }
  177. if (!isAllowedHttpHeader(header)) {
  178. console.warn('Refused to set unsafe header "' + header + '"');
  179. return;
  180. }
  181. if (sendFlag) {
  182. throw "INVALID_STATE_ERR: send flag is true";
  183. }
  184. headers[header] = value;
  185. };
  186. /**
  187. * Gets a header from the server response.
  188. *
  189. * @param string header Name of header to get.
  190. * @return string Text of the header or null if it doesn't exist.
  191. */
  192. this.getResponseHeader = function(header) {
  193. if (typeof header === "string"
  194. && this.readyState > this.OPENED
  195. && response.headers[header.toLowerCase()]
  196. && !errorFlag
  197. ) {
  198. return response.headers[header.toLowerCase()];
  199. }
  200. return null;
  201. };
  202. /**
  203. * Gets all the response headers.
  204. *
  205. * @return string A string with all response headers separated by CR+LF
  206. */
  207. this.getAllResponseHeaders = function() {
  208. if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
  209. return "";
  210. }
  211. var result = "";
  212. for (var i in response.headers) {
  213. // Cookie headers are excluded
  214. if (i !== "set-cookie" && i !== "set-cookie2") {
  215. result += i + ": " + response.headers[i] + "\r\n";
  216. }
  217. }
  218. return result.substr(0, result.length - 2);
  219. };
  220. /**
  221. * Gets a request header
  222. *
  223. * @param string name Name of header to get
  224. * @return string Returns the request header or empty string if not set
  225. */
  226. this.getRequestHeader = function(name) {
  227. // @TODO Make this case insensitive
  228. if (typeof name === "string" && headers[name]) {
  229. return headers[name];
  230. }
  231. return "";
  232. };
  233. /**
  234. * Sends the request to the server.
  235. *
  236. * @param string data Optional data to send as request body.
  237. */
  238. this.send = function(data) {
  239. if (this.readyState != this.OPENED) {
  240. throw "INVALID_STATE_ERR: connection must be opened before send() is called";
  241. }
  242. if (sendFlag) {
  243. throw "INVALID_STATE_ERR: send has already been called";
  244. }
  245. var ssl = false, local = false;
  246. var url = Url.parse(settings.url);
  247. var host;
  248. // Determine the server
  249. switch (url.protocol) {
  250. case 'https:':
  251. ssl = true;
  252. // SSL & non-SSL both need host, no break here.
  253. case 'http:':
  254. host = url.hostname;
  255. break;
  256. case 'file:':
  257. local = true;
  258. break;
  259. case undefined:
  260. case '':
  261. host = "localhost";
  262. break;
  263. default:
  264. throw "Protocol not supported.";
  265. }
  266. // Load files off the local filesystem (file://)
  267. if (local) {
  268. if (settings.method !== "GET") {
  269. throw "XMLHttpRequest: Only GET method is supported";
  270. }
  271. if (settings.async) {
  272. fs.readFile(url.pathname, 'utf8', function(error, data) {
  273. if (error) {
  274. self.handleError(error);
  275. } else {
  276. self.status = 200;
  277. self.responseText = data;
  278. setState(self.DONE);
  279. }
  280. });
  281. } else {
  282. try {
  283. this.responseText = fs.readFileSync(url.pathname, 'utf8');
  284. this.status = 200;
  285. setState(self.DONE);
  286. } catch(e) {
  287. this.handleError(e);
  288. }
  289. }
  290. return;
  291. }
  292. // Default to port 80. If accessing localhost on another port be sure
  293. // to use http://localhost:port/path
  294. var port = url.port || (ssl ? 443 : 80);
  295. // Add query string if one is used
  296. var uri = url.pathname + (url.search ? url.search : '');
  297. // Set the Host header or the server may reject the request
  298. headers["Host"] = host;
  299. if (!((ssl && port === 443) || port === 80)) {
  300. headers["Host"] += ':' + url.port;
  301. }
  302. // Set Basic Auth if necessary
  303. if (settings.user) {
  304. if (typeof settings.password == "undefined") {
  305. settings.password = "";
  306. }
  307. var authBuf = new Buffer(settings.user + ":" + settings.password);
  308. headers["Authorization"] = "Basic " + authBuf.toString("base64");
  309. }
  310. // Set content length header
  311. if (settings.method === "GET" || settings.method === "HEAD") {
  312. data = null;
  313. } else if (data) {
  314. headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
  315. if (!headers["Content-Type"]) {
  316. headers["Content-Type"] = "text/plain;charset=UTF-8";
  317. }
  318. } else if (settings.method === "POST") {
  319. // For a post with no data set Content-Length: 0.
  320. // This is required by buggy servers that don't meet the specs.
  321. headers["Content-Length"] = 0;
  322. }
  323. var agent = false;
  324. if (opts && opts.agent) {
  325. agent = opts.agent;
  326. }
  327. var options = {
  328. host: host,
  329. port: port,
  330. path: uri,
  331. method: settings.method,
  332. headers: headers,
  333. agent: agent
  334. };
  335. // Reset error flag
  336. errorFlag = false;
  337. // Handle async requests
  338. if (settings.async) {
  339. // Use the proper protocol
  340. var doRequest = ssl ? https.request : http.request;
  341. // Request is being sent, set send flag
  342. sendFlag = true;
  343. // As per spec, this is called here for historical reasons.
  344. self.dispatchEvent("readystatechange");
  345. // Handler for the response
  346. function responseHandler(resp) {
  347. // Set response var to the response we got back
  348. // This is so it remains accessable outside this scope
  349. response = resp;
  350. // Check for redirect
  351. // @TODO Prevent looped redirects
  352. if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
  353. // Change URL to the redirect location
  354. settings.url = response.headers.location;
  355. var url = Url.parse(settings.url);
  356. // Set host var in case it's used later
  357. host = url.hostname;
  358. // Options for the new request
  359. var newOptions = {
  360. hostname: url.hostname,
  361. port: url.port,
  362. path: url.path,
  363. method: response.statusCode === 303 ? 'GET' : settings.method,
  364. headers: headers
  365. };
  366. // Issue the new request
  367. request = doRequest(newOptions, responseHandler).on('error', errorHandler);
  368. request.end();
  369. // @TODO Check if an XHR event needs to be fired here
  370. return;
  371. }
  372. response.setEncoding("utf8");
  373. setState(self.HEADERS_RECEIVED);
  374. self.status = response.statusCode;
  375. response.on('data', function(chunk) {
  376. // Make sure there's some data
  377. if (chunk) {
  378. self.responseText += chunk;
  379. }
  380. // Don't emit state changes if the connection has been aborted.
  381. if (sendFlag) {
  382. setState(self.LOADING);
  383. }
  384. });
  385. response.on('end', function() {
  386. if (sendFlag) {
  387. // Discard the 'end' event if the connection has been aborted
  388. setState(self.DONE);
  389. sendFlag = false;
  390. }
  391. });
  392. response.on('error', function(error) {
  393. self.handleError(error);
  394. });
  395. }
  396. // Error handler for the request
  397. function errorHandler(error) {
  398. self.handleError(error);
  399. }
  400. // Create the request
  401. request = doRequest(options, responseHandler).on('error', errorHandler);
  402. // Node 0.4 and later won't accept empty data. Make sure it's needed.
  403. if (data) {
  404. request.write(data);
  405. }
  406. request.end();
  407. self.dispatchEvent("loadstart");
  408. } else { // Synchronous
  409. // Create a temporary file for communication with the other Node process
  410. var contentFile = ".node-xmlhttprequest-content-" + process.pid;
  411. var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
  412. fs.writeFileSync(syncFile, "", "utf8");
  413. // The async request the other Node process executes
  414. var execString = "var http = require('http'), https = require('https'), fs = require('fs');"
  415. + "var doRequest = http" + (ssl ? "s" : "") + ".request;"
  416. + "var options = " + JSON.stringify(options) + ";"
  417. + "var responseText = '';"
  418. + "var req = doRequest(options, function(response) {"
  419. + "response.setEncoding('utf8');"
  420. + "response.on('data', function(chunk) {"
  421. + " responseText += chunk;"
  422. + "});"
  423. + "response.on('end', function() {"
  424. + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');"
  425. + "fs.unlinkSync('" + syncFile + "');"
  426. + "});"
  427. + "response.on('error', function(error) {"
  428. + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
  429. + "fs.unlinkSync('" + syncFile + "');"
  430. + "});"
  431. + "}).on('error', function(error) {"
  432. + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
  433. + "fs.unlinkSync('" + syncFile + "');"
  434. + "});"
  435. + (data ? "req.write('" + data.replace(/'/g, "\\'") + "');":"")
  436. + "req.end();";
  437. // Start the other Node Process, executing this string
  438. var syncProc = spawn(process.argv[0], ["-e", execString]);
  439. var statusText;
  440. while(fs.existsSync(syncFile)) {
  441. // Wait while the sync file is empty
  442. }
  443. self.responseText = fs.readFileSync(contentFile, 'utf8');
  444. // Kill the child process once the file has data
  445. syncProc.stdin.end();
  446. // Remove the temporary file
  447. fs.unlinkSync(contentFile);
  448. if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
  449. // If the file returned an error, handle it
  450. var errorObj = self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, "");
  451. self.handleError(errorObj);
  452. } else {
  453. // If the file returned okay, parse its data and move to the DONE state
  454. self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, "$1");
  455. self.responseText = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, "$1");
  456. setState(self.DONE);
  457. }
  458. }
  459. };
  460. /**
  461. * Called when an error is encountered to deal with it.
  462. */
  463. this.handleError = function(error) {
  464. this.status = 503;
  465. this.statusText = error;
  466. this.responseText = error.stack;
  467. errorFlag = true;
  468. setState(this.DONE);
  469. };
  470. /**
  471. * Aborts a request.
  472. */
  473. this.abort = function() {
  474. if (request) {
  475. request.abort();
  476. request = null;
  477. }
  478. headers = defaultHeaders;
  479. this.responseText = "";
  480. this.responseXML = "";
  481. errorFlag = true;
  482. if (this.readyState !== this.UNSENT
  483. && (this.readyState !== this.OPENED || sendFlag)
  484. && this.readyState !== this.DONE) {
  485. sendFlag = false;
  486. setState(this.DONE);
  487. }
  488. this.readyState = this.UNSENT;
  489. };
  490. /**
  491. * Adds an event listener. Preferred method of binding to events.
  492. */
  493. this.addEventListener = function(event, callback) {
  494. if (!(event in listeners)) {
  495. listeners[event] = [];
  496. }
  497. // Currently allows duplicate callbacks. Should it?
  498. listeners[event].push(callback);
  499. };
  500. /**
  501. * Remove an event callback that has already been bound.
  502. * Only works on the matching funciton, cannot be a copy.
  503. */
  504. this.removeEventListener = function(event, callback) {
  505. if (event in listeners) {
  506. // Filter will return a new array with the callback removed
  507. listeners[event] = listeners[event].filter(function(ev) {
  508. return ev !== callback;
  509. });
  510. }
  511. };
  512. /**
  513. * Dispatch any events, including both "on" methods and events attached using addEventListener.
  514. */
  515. this.dispatchEvent = function(event) {
  516. if (typeof self["on" + event] === "function") {
  517. self["on" + event]();
  518. }
  519. if (event in listeners) {
  520. for (var i = 0, len = listeners[event].length; i < len; i++) {
  521. listeners[event][i].call(self);
  522. }
  523. }
  524. };
  525. /**
  526. * Changes readyState and calls onreadystatechange.
  527. *
  528. * @param int state New state
  529. */
  530. var setState = function(state) {
  531. if (self.readyState !== state) {
  532. self.readyState = state;
  533. if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
  534. self.dispatchEvent("readystatechange");
  535. }
  536. if (self.readyState === self.DONE && !errorFlag) {
  537. self.dispatchEvent("load");
  538. // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
  539. self.dispatchEvent("loadend");
  540. }
  541. }
  542. };
  543. };