curl.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. /*
  6. * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
  7. * Copyright (C) 2008, 2009 Anthony Ricaud <rik@webkit.org>
  8. * Copyright (C) 2011 Google Inc. All rights reserved.
  9. * Copyright (C) 2009 Mozilla Foundation. All rights reserved.
  10. * Copyright (C) 2022 Moonchild Productions. All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or without
  13. * modification, are permitted provided that the following conditions
  14. * are met:
  15. *
  16. * 1. Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. * 2. Redistributions in binary form must reproduce the above copyright
  19. * notice, this list of conditions and the following disclaimer in the
  20. * documentation and/or other materials provided with the distribution.
  21. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
  22. * its contributors may be used to endorse or promote products derived
  23. * from this software without specific prior written permission.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  26. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  27. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  28. * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  29. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  30. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  32. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  34. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35. */
  36. "use strict";
  37. const Services = require("Services");
  38. const DEFAULT_HTTP_VERSION = "HTTP/1.1";
  39. const Curl = {
  40. /**
  41. * Generates a cURL command string which can be used from the command line etc.
  42. *
  43. * @param object data
  44. * Datasource to create the command from.
  45. * The object must contain the following properties:
  46. * - url:string, the URL of the request.
  47. * - method:string, the request method upper cased. HEAD / GET / POST etc.
  48. * - headers:array, an array of request headers {name:x, value:x} tuples.
  49. * - httpVersion:string, http protocol version rfc2616 formatted. Eg. "HTTP/1.1"
  50. * - postDataText:string, optional - the request payload.
  51. *
  52. * @return string
  53. * A cURL command.
  54. */
  55. generateCommand: function (data) {
  56. const utils = CurlUtils;
  57. let command = ["curl"];
  58. // Make sure to use the following helpers to sanitize arguments before execution.
  59. const addParam = value => {
  60. const safe = /^[a-zA-Z-]+$/.test(value) ? value : escapeString(value);
  61. command.push(safe);
  62. };
  63. const addPostData = value => {
  64. const safe = /^[a-zA-Z-]+$/.test(value) ? value : escapeString(value);
  65. postData.push(safe);
  66. };
  67. let ignoredHeaders = new Set();
  68. // The cURL command is expected to run on the same platform that Firefox runs
  69. // (it may be different from the inspected page platform).
  70. let escapeString = Services.appinfo.OS == "WINNT" ?
  71. utils.escapeStringWin : utils.escapeStringPosix;
  72. // Add URL.
  73. addParam(data.url);
  74. let postDataText = null;
  75. let multipartRequest = utils.isMultipartRequest(data);
  76. // Create post data.
  77. let postData = [];
  78. if (utils.isUrlEncodedRequest(data) ||
  79. ["PUT", "POST", "PATCH"].includes(data.method)) {
  80. postDataText = data.postDataText;
  81. addPostData("--data-raw");
  82. addPostData(utils.writePostDataTextParams(postDataText));
  83. ignoredHeaders.add("content-length");
  84. } else if (multipartRequest) {
  85. postDataText = data.postDataText;
  86. addPostData("--data-binary");
  87. let boundary = utils.getMultipartBoundary(data);
  88. let text = utils.removeBinaryDataFromMultipartText(postDataText, boundary);
  89. addPostData(text);
  90. ignoredHeaders.add("content-length");
  91. }
  92. // Add method.
  93. // For GET and POST requests this is not necessary as GET is the
  94. // default. If --data or --binary is added POST is the default.
  95. if (!(data.method == "GET" || data.method == "POST")) {
  96. addParam("-X");
  97. addParam(data.method);
  98. }
  99. // Add -I (HEAD)
  100. // For servers that supports HEAD.
  101. // This will fetch the header of a document only.
  102. if (data.method == "HEAD") {
  103. addParam("-I");
  104. }
  105. // Add http version.
  106. if (data.httpVersion && data.httpVersion != DEFAULT_HTTP_VERSION) {
  107. let version = data.httpVersion.split("/")[1];
  108. // curl accepts --http1.0, --http1.1 and --http2 for HTTP/1.0, HTTP/1.1
  109. // and HTTP/2 protocols respectively. But the corresponding values in
  110. // data.httpVersion are HTTP/1.0, HTTP/1.1 and HTTP/2.0
  111. // So in case of HTTP/2.0 (which should ideally be HTTP/2) we are using
  112. // only major version, and full version in other cases
  113. addParam("--http" + (version == "2.0" ? version.split(".")[0] : version));
  114. }
  115. // Add request headers.
  116. let headers = data.headers;
  117. if (multipartRequest) {
  118. let multipartHeaders = utils.getHeadersFromMultipartText(postDataText);
  119. headers = headers.concat(multipartHeaders);
  120. }
  121. for (let i = 0; i < headers.length; i++) {
  122. let header = headers[i];
  123. if (header.name.toLowerCase() === "accept-encoding") {
  124. addParam("--compressed");
  125. continue;
  126. }
  127. if (ignoredHeaders.has(header.name.toLowerCase())) {
  128. continue;
  129. }
  130. addParam("-H");
  131. addParam(header.name + ": " + header.value);
  132. }
  133. // Add post data.
  134. command = command.concat(postData);
  135. return command.join(" ");
  136. }
  137. };
  138. exports.Curl = Curl;
  139. /**
  140. * Utility functions for the Curl command generator.
  141. */
  142. const CurlUtils = {
  143. /**
  144. * Check if the request is an URL encoded request.
  145. *
  146. * @param object data
  147. * The data source. See the description in the Curl object.
  148. * @return boolean
  149. * True if the request is URL encoded, false otherwise.
  150. */
  151. isUrlEncodedRequest: function (data) {
  152. let postDataText = data.postDataText;
  153. if (!postDataText) {
  154. return false;
  155. }
  156. postDataText = postDataText.toLowerCase();
  157. if (postDataText.includes("content-type: application/x-www-form-urlencoded")) {
  158. return true;
  159. }
  160. let contentType = this.findHeader(data.headers, "content-type");
  161. return (contentType &&
  162. contentType.toLowerCase().includes("application/x-www-form-urlencoded"));
  163. },
  164. /**
  165. * Check if the request is a multipart request.
  166. *
  167. * @param object data
  168. * The data source.
  169. * @return boolean
  170. * True if the request is multipart reqeust, false otherwise.
  171. */
  172. isMultipartRequest: function (data) {
  173. let postDataText = data.postDataText;
  174. if (!postDataText) {
  175. return false;
  176. }
  177. postDataText = postDataText.toLowerCase();
  178. if (postDataText.includes("content-type: multipart/form-data")) {
  179. return true;
  180. }
  181. let contentType = this.findHeader(data.headers, "content-type");
  182. return (contentType &&
  183. contentType.toLowerCase().includes("multipart/form-data;"));
  184. },
  185. /**
  186. * Write out paramters from post data text.
  187. *
  188. * @param object postDataText
  189. * Post data text.
  190. * @return string
  191. * Post data parameters.
  192. */
  193. writePostDataTextParams: function (postDataText) {
  194. if (!postDataText) {
  195. return "";
  196. }
  197. let lines = postDataText.split("\r\n");
  198. return lines[lines.length - 1];
  199. },
  200. /**
  201. * Finds the header with the given name in the headers array.
  202. *
  203. * @param array headers
  204. * Array of headers info {name:x, value:x}.
  205. * @param string name
  206. * The header name to find.
  207. * @return string
  208. * The found header value or null if not found.
  209. */
  210. findHeader: function (headers, name) {
  211. if (!headers) {
  212. return null;
  213. }
  214. name = name.toLowerCase();
  215. for (let header of headers) {
  216. if (name == header.name.toLowerCase()) {
  217. return header.value;
  218. }
  219. }
  220. return null;
  221. },
  222. /**
  223. * Returns the boundary string for a multipart request.
  224. *
  225. * @param string data
  226. * The data source. See the description in the Curl object.
  227. * @return string
  228. * The boundary string for the request.
  229. */
  230. getMultipartBoundary: function (data) {
  231. let boundaryRe = /\bboundary=(-{3,}\w+)/i;
  232. // Get the boundary string from the Content-Type request header.
  233. let contentType = this.findHeader(data.headers, "Content-Type");
  234. if (boundaryRe.test(contentType)) {
  235. return contentType.match(boundaryRe)[1];
  236. }
  237. // Temporary workaround. As of 2014-03-11 the requestHeaders array does not
  238. // always contain the Content-Type header for mulitpart requests. See bug 978144.
  239. // Find the header from the request payload.
  240. let boundaryString = data.postDataText.match(boundaryRe)[1];
  241. if (boundaryString) {
  242. return boundaryString;
  243. }
  244. return null;
  245. },
  246. /**
  247. * Removes the binary data from multipart text.
  248. *
  249. * @param string multipartText
  250. * Multipart form data text.
  251. * @param string boundary
  252. * The boundary string.
  253. * @return string
  254. * The multipart text without the binary data.
  255. */
  256. removeBinaryDataFromMultipartText: function (multipartText, boundary) {
  257. let result = "";
  258. boundary = "--" + boundary;
  259. let parts = multipartText.split(boundary);
  260. for (let part of parts) {
  261. // Each part is expected to have a content disposition line.
  262. let contentDispositionLine = part.trimLeft().split("\r\n")[0];
  263. if (!contentDispositionLine) {
  264. continue;
  265. }
  266. contentDispositionLine = contentDispositionLine.toLowerCase();
  267. if (contentDispositionLine.includes("content-disposition: form-data")) {
  268. if (contentDispositionLine.includes("filename=")) {
  269. // The header lines and the binary blob is separated by 2 CRLF's.
  270. // Add only the headers to the result.
  271. let headers = part.split("\r\n\r\n")[0];
  272. result += boundary + "\r\n" + headers + "\r\n\r\n";
  273. } else {
  274. result += boundary + "\r\n" + part;
  275. }
  276. }
  277. }
  278. result += boundary + "--\r\n";
  279. return result;
  280. },
  281. /**
  282. * Get the headers from a multipart post data text.
  283. *
  284. * @param string multipartText
  285. * Multipart post text.
  286. * @return array
  287. * An array of header objects {name:x, value:x}
  288. */
  289. getHeadersFromMultipartText: function (multipartText) {
  290. let headers = [];
  291. if (!multipartText || multipartText.startsWith("---")) {
  292. return headers;
  293. }
  294. // Get the header section.
  295. let index = multipartText.indexOf("\r\n\r\n");
  296. if (index == -1) {
  297. return headers;
  298. }
  299. // Parse the header lines.
  300. let headersText = multipartText.substring(0, index);
  301. let headerLines = headersText.split("\r\n");
  302. let lastHeaderName = null;
  303. for (let line of headerLines) {
  304. // Create a header for each line in fields that spans across multiple lines.
  305. // Subsquent lines always begins with at least one space or tab character.
  306. // (rfc2616)
  307. if (lastHeaderName && /^\s+/.test(line)) {
  308. headers.push({ name: lastHeaderName, value: line.trim() });
  309. continue;
  310. }
  311. let indexOfColon = line.indexOf(":");
  312. if (indexOfColon == -1) {
  313. continue;
  314. }
  315. let header = [line.slice(0, indexOfColon), line.slice(indexOfColon + 1)];
  316. if (header.length != 2) {
  317. continue;
  318. }
  319. lastHeaderName = header[0].trim();
  320. headers.push({ name: lastHeaderName, value: header[1].trim() });
  321. }
  322. return headers;
  323. },
  324. /**
  325. * Escape util function for POSIX oriented operating systems.
  326. * Credit: Google DevTools
  327. */
  328. escapeStringPosix: function (str) {
  329. function escapeCharacter(x) {
  330. let code = x.charCodeAt(0);
  331. if (code < 256) {
  332. // Add leading zero when needed to not care about the next character.
  333. return code < 16 ? "\\x0" + code.toString(16) : "\\x" + code.toString(16);
  334. }
  335. code = code.toString(16);
  336. return "\\u" + ("0000" + code).substr(code.length, 4);
  337. }
  338. if (/[^\x20-\x7E]|\'/.test(str)) {
  339. // Use ANSI-C quoting syntax.
  340. return "$\'" + str.replace(/\\/g, "\\\\")
  341. .replace(/\'/g, "\\\'")
  342. .replace(/\n/g, "\\n")
  343. .replace(/\r/g, "\\r")
  344. .replace(/!/g, "\\041")
  345. .replace(/[^\x20-\x7E]/g, escapeCharacter) + "'";
  346. }
  347. // Use single quote syntax.
  348. return "'" + str + "'";
  349. },
  350. /**
  351. * Escape util function for Windows systems.
  352. * Credit: Google DevTools
  353. */
  354. escapeStringWin: function (str) {
  355. /*
  356. Replace the backtick character ` with `` in order to escape it.
  357. The backtick character is an escape character in PowerShell and
  358. can, among other things, be used to disable the effect of some
  359. of the other escapes created below.
  360. Replace dollar sign because of commands in powershell when using
  361. double quotes. e.g $(calc.exe).
  362. Also see http://www.rlmueller.net/PowerShellEscape.htm for details.
  363. Replace quote by double quote (but not by \") because it is
  364. recognized by both cmd.exe and MS Crt arguments parser.
  365. Replace % by "%" because it could be expanded to an environment
  366. variable value. So %% becomes "%""%". Even if an env variable ""
  367. (2 doublequotes) is declared, the cmd.exe will not
  368. substitute it with its value.
  369. Replace each backslash with double backslash to make sure
  370. MS Crt arguments parser won't collapse them.
  371. Replace new line outside of quotes since cmd.exe doesn't let
  372. us do it inside.
  373. */
  374. return "\"" +
  375. str.replaceAll("`", "``")
  376. .replaceAll("$", "`$")
  377. .replaceAll('"', '""')
  378. .replaceAll("%", '"%"')
  379. .replace(/\\/g, "\\\\")
  380. .replace(/[\r\n]+/g, "\"^$&\"") + "\"";
  381. }
  382. };
  383. exports.CurlUtils = CurlUtils;