From eb2be13a1ea813076e5e98ed342962d5928c7367 Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:24:16 +0530 Subject: [PATCH] fix(http-client): read pasted cURL commands as cURL does (#7861) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pasted curl command often became a different request: -sX POST URL turned into GET POST, -D headers.txt URL into GET headers.txt, -I into a GET, -d @body.json was sent as that text, and commands copied with $'…' (bash) or ^"…^" (cmd) quoting were not converted. The command is now split into words like the shell it was written for, every cURL option that takes a value is known and short-flag clusters are read, and data, form, upload, header and credential options map to what cURL sends. A command a request file can't express (standard input, several files joined with &, several commands) is pasted as it is. A test runs 31 commands through the real curl against a loopback server and compares them with the converted requests. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- crates/ide-http/src/curl.rs | 216 +-------------------- crates/ide-http/src/curl/form.rs | 127 ++++++++++++ crates/ide-http/src/curl/import.rs | 282 +++++++++++++++++++++++++++ crates/ide-http/src/curl/options.rs | 108 +++++++++++ crates/ide-http/src/curl/words.rs | 288 ++++++++++++++++++++++++++++ crates/ide-http/tests/curl_paste.rs | 190 ++++++++++++++++++ 6 files changed, 1002 insertions(+), 209 deletions(-) create mode 100644 crates/ide-http/src/curl/form.rs create mode 100644 crates/ide-http/src/curl/import.rs create mode 100644 crates/ide-http/src/curl/options.rs create mode 100644 crates/ide-http/src/curl/words.rs create mode 100644 crates/ide-http/tests/curl_paste.rs diff --git a/crates/ide-http/src/curl.rs b/crates/ide-http/src/curl.rs index 3167b93afa..c84fd64671 100644 --- a/crates/ide-http/src/curl.rs +++ b/crates/ide-http/src/curl.rs @@ -1,6 +1,13 @@ //! cURL ⇄ `.http` request: Convert to cURL and Copy, and the conversion of a pasted //! `curl …` command into a request. +mod form; +mod import; +mod options; +mod words; + +pub use import::from_curl; + use crate::PreparedRequest; use crate::body::BodyChunk; @@ -44,215 +51,6 @@ fn quote(s: &str) -> String { format!("'{}'", s.replace('\'', r"'\''")) } -/// The request a `curl …` command sends, as `.http` text; `None` when `cmd` is not a cURL -/// command or names no URL. -pub fn from_curl(cmd: &str) -> Option { - let words = split_words(cmd)?; - let mut args = words.iter().map(String::as_str); - if args.next() != Some("curl") { - return None; - } - let mut method: Option = None; - let mut url: Option = None; - let mut headers: Vec<(String, String)> = Vec::new(); - let mut data: Vec = Vec::new(); - let mut form: Vec<(String, String)> = Vec::new(); - let mut get = false; - let header = |headers: &mut Vec<(String, String)>, line: &str| { - if let Some((k, v)) = line.split_once(':') { - headers.push((k.trim().to_owned(), v.trim().to_owned())); - } - }; - while let Some(arg) = args.next() { - // `--opt=value` and `-Xvalue` forms. - let (flag, inline) = match arg.split_once('=') { - Some((f, v)) if arg.starts_with("--") => (f, Some(v.to_owned())), - _ if arg.len() > 2 && arg.starts_with('-') && !arg.starts_with("--") && takes_value(&arg[..2]) => { - (&arg[..2], Some(arg[2..].to_owned())) - } - _ => (arg, None), - }; - let mut value = || inline.clone().or_else(|| args.next().map(str::to_owned)); - match flag { - "-X" | "--request" => method = value(), - "-H" | "--header" => header(&mut headers, &value()?), - "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" | "--data-urlencode" => { - data.push(value()?) - } - "--json" => { - data.push(value()?); - headers.push(("Content-Type".into(), "application/json".into())); - headers.push(("Accept".into(), "application/json".into())); - } - "-F" | "--form" | "--form-string" => { - let v = value()?; - let (k, v) = v.split_once('=')?; - form.push((k.to_owned(), v.to_owned())); - } - "-u" | "--user" => { - let v = value()?; - let (user, pass) = v.split_once(':').unwrap_or((&v, "")); - headers.push(("Authorization".into(), format!("Basic {user} {pass}").trim_end().to_owned())); - } - "-b" | "--cookie" => headers.push(("Cookie".into(), value()?)), - "-A" | "--user-agent" => headers.push(("User-Agent".into(), value()?)), - "-e" | "--referer" => headers.push(("Referer".into(), value()?)), - "--url" => url = value(), - "-G" | "--get" => get = true, - f if f.starts_with('-') => { - // Options with a value the request doesn't need (timeouts, output, proxy…). - if takes_value(f) { - value(); - } - } - u => { - if url.is_none() { - url = Some(u.to_owned()); - } - } - } - } - let mut url = url?; - if get && !data.is_empty() { - url.push(if url.contains('?') { '&' } else { '?' }); - url.push_str(&data.join("&")); - data.clear(); - } - let method = method.unwrap_or_else(|| if data.is_empty() && form.is_empty() { "GET" } else { "POST" }.into()); - let mut body = None; - if !form.is_empty() { - const BOUNDARY: &str = "WebAppBoundary"; - headers.retain(|(k, _)| !k.eq_ignore_ascii_case("content-type")); - headers.push(("Content-Type".into(), format!("multipart/form-data; boundary={BOUNDARY}"))); - let mut text = String::new(); - for (name, value) in &form { - text.push_str(&format!("--{BOUNDARY}\n")); - match value.strip_prefix('@') { - Some(file) => { - let file = file.split(';').next().unwrap_or(file); - let base = file.rsplit(['/', '\\']).next().unwrap_or(file); - text.push_str(&format!( - "Content-Disposition: form-data; name=\"{name}\"; filename=\"{base}\"\n\n< {file}\n" - )); - } - None => text.push_str(&format!("Content-Disposition: form-data; name=\"{name}\"\n\n{value}\n")), - } - } - text.push_str(&format!("--{BOUNDARY}--")); - body = Some(text); - } else if !data.is_empty() { - if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) { - headers.push(("Content-Type".into(), "application/x-www-form-urlencoded".into())); - } - body = Some(data.join("&")); - } - let mut out = format!("{method} {url}\n"); - for (k, v) in &headers { - out.push_str(&format!("{k}: {v}\n")); - } - if let Some(body) = body { - out.push('\n'); - out.push_str(&body); - out.push('\n'); - } - Some(out) -} - -/// Options that take a value, so it isn't read as the URL. -fn takes_value(flag: &str) -> bool { - matches!( - flag, - "-X" | "-H" - | "-d" - | "-F" - | "-u" - | "-b" - | "-A" - | "-e" - | "-o" - | "-x" - | "-m" - | "-c" - | "-E" - | "-T" - | "-w" - | "-r" - | "-K" - | "--output" - | "--proxy" - | "--max-time" - | "--connect-timeout" - | "--cookie-jar" - | "--cert" - | "--key" - | "--cacert" - | "--upload-file" - | "--write-out" - | "--range" - | "--config" - | "--retry" - | "--resolve" - | "--interface" - ) -} - -/// Shell words of `cmd`: single and double quotes, backslash escapes and line continuations -/// (also `^` / backtick continuations from Windows shells). `None` for an unclosed quote. -fn split_words(cmd: &str) -> Option> { - let mut words = Vec::new(); - let mut cur = String::new(); - let mut in_word = false; - let mut chars = cmd.trim().chars().peekable(); - while let Some(c) = chars.next() { - match c { - '\'' => { - in_word = true; - loop { - match chars.next()? { - '\'' => break, - c => cur.push(c), - } - } - } - '"' => { - in_word = true; - loop { - match chars.next()? { - '"' => break, - '\\' if matches!(chars.peek(), Some('"' | '\\' | '$' | '`')) => cur.push(chars.next()?), - c => cur.push(c), - } - } - } - '\\' | '^' | '`' if matches!(chars.peek(), Some('\n' | '\r')) => { - while matches!(chars.peek(), Some('\n' | '\r')) { - chars.next(); - } - } - '\\' => { - in_word = true; - if let Some(n) = chars.next() { - cur.push(n); - } - } - c if c.is_whitespace() => { - if in_word { - words.push(std::mem::take(&mut cur)); - in_word = false; - } - } - c => { - in_word = true; - cur.push(c); - } - } - } - if in_word { - words.push(cur); - } - Some(words) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ide-http/src/curl/form.rs b/crates/ide-http/src/curl/form.rs new file mode 100644 index 0000000000..a372925bd4 --- /dev/null +++ b/crates/ide-http/src/curl/form.rs @@ -0,0 +1,127 @@ +//! Multipart fields (`-F name=content`). + +/// Also the boundary written in the request. +pub(super) const BOUNDARY: &str = "WebAppBoundary"; + +enum Content { + Text(String), + File(String), +} + +pub(super) struct Field { + name: String, + content: Content, + filename: Option, + content_type: Option, + headers: Vec, +} + +const ATTRIBUTES: [&str; 4] = ["type=", "filename=", "headers=", "encoder="]; + +impl Field { + /// `--form-string name=text`: nothing in the text is special. + pub(super) fn literal(value: &str) -> Option { + let (name, text) = value.split_once('=')?; + Some(Self::new(name, Content::Text(text.to_owned()))) + } + + /// `-F name=content;attribute=…`. `None` for what one part of a request file can't express: + /// nested parts, several files, standard input, encoders and header files. + pub(super) fn parse(value: &str) -> Option { + let (name, content) = value.split_once('=')?; + let content = content.trim_start(); + if content.starts_with('(') || (name.is_empty() && content.starts_with(')')) { + return None; + } + let (mut field, mut rest) = if let Some(file) = content.strip_prefix(['@', '<']) { + let (path, quoted, rest) = word(file); + if path.is_empty() || path == "-" || (!quoted && path.contains(',')) { + return None; + } + let base = path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned(); + let filename = content.starts_with('@').then_some(base); + (Self { filename, ..Self::new(name, Content::File(path)) }, rest) + } else { + let (text, _, rest) = word(content); + (Self::new(name, Content::Text(text)), rest) + }; + while !rest.is_empty() { + let attribute = attribute(rest); + let value = attribute.map_or(rest, |a| &rest[a.len()..]); + let (text, _, next) = word(value); + rest = next; + match attribute { + Some("type=") => { + let mut mime = text; + // Its own parameters (`; charset=utf-8`) are not attributes of the field. + while !rest.is_empty() && self::attribute(rest).is_none() { + let (parameter, _, next) = word(rest); + mime.push_str("; "); + mime.push_str(¶meter); + rest = next; + } + field.content_type = Some(mime); + } + Some("filename=") => field.filename = Some(text), + Some("headers=") if !text.starts_with(['@', '<']) => field.headers.push(text), + Some(_) => return None, + // cURL skips what it doesn't know, with a warning. + None => {} + } + } + Some(field) + } + + fn new(name: &str, content: Content) -> Self { + Self { name: name.to_owned(), content, filename: None, content_type: None, headers: Vec::new() } + } + + pub(super) fn write(&self, out: &mut String) { + out.push_str(&format!("--{BOUNDARY}\nContent-Disposition: form-data; name=\"{}\"", escape(&self.name))); + if let Some(filename) = &self.filename { + out.push_str(&format!("; filename=\"{}\"", escape(filename))); + } + out.push('\n'); + if let Some(content_type) = &self.content_type { + out.push_str(&format!("Content-Type: {content_type}\n")); + } + for header in &self.headers { + out.push_str(&format!("{header}\n")); + } + match &self.content { + Content::Text(text) => out.push_str(&format!("\n{text}\n")), + Content::File(path) => out.push_str(&format!("\n< {path}\n")), + } + } +} + +/// The attribute name `s` starts with. +fn attribute(s: &str) -> Option<&'static str> { + ATTRIBUTES.into_iter().find(|a| s.get(..a.len()).is_some_and(|start| start.eq_ignore_ascii_case(a))) +} + +/// A value up to the next `;` or in double quotes: the value, whether it was quoted, and what +/// follows the `;`. +fn word(s: &str) -> (String, bool, &str) { + let s = s.trim_start(); + if let Some(inner) = s.strip_prefix('"') { + let mut value = String::new(); + let mut chars = inner.char_indices(); + while let Some((i, c)) = chars.next() { + match c { + '"' => { + let rest = inner[i + 1..].split_once(';').map_or("", |(_, rest)| rest); + return (value, true, rest.trim_start()); + } + '\\' if inner[i + 1..].starts_with(['\\', '"']) => value.extend(chars.next().map(|(_, c)| c)), + c => value.push(c), + } + } + } + let (value, rest) = s.split_once(';').unwrap_or((s, "")); + (value.trim_end().to_owned(), false, rest.trim_start()) +} + +fn escape(s: &str) -> String { + s.replace('"', "%22").replace('\r', "%0D").replace('\n', "%0A") +} diff --git a/crates/ide-http/src/curl/import.rs b/crates/ide-http/src/curl/import.rs new file mode 100644 index 0000000000..e93b17906d --- /dev/null +++ b/crates/ide-http/src/curl/import.rs @@ -0,0 +1,282 @@ +//! A pasted `curl …` command as a request. + +use super::form::{BOUNDARY, Field}; +use super::{options, words}; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; + +/// The request a `curl …` command sends, as `.http` text; `None` when `cmd` is not a cURL +/// command, names no URL, or sends something a request file can't express (standard input, several +/// files joined into one body). +pub fn from_curl(cmd: &str) -> Option { + let words = words::split(cmd)?; + let (command, args) = words.split_first()?; + if command != "curl" { + return None; + } + let mut request = Request::default(); + for (name, value) in options::parse(args)? { + if name == "next" { + break; + } + request.apply(name, value)?; + } + request.into_http() +} + +enum Data { + Text(String), + File(String), +} + +#[derive(Default)] +struct Request { + method: Option, + url: Option, + globoff: bool, + headers: Vec
, + /// Headers cURL is told not to send (`-H 'Name:'`), in lower case. + removed: Vec, + data: Vec, + query: Vec, + form: Vec, + upload: Option, + json: bool, + get: bool, + head: bool, +} + +struct Header { + name: String, + value: String, + /// Set with `-H`, which wins over the options that set the same header. + explicit: bool, +} + +impl Request { + fn apply(&mut self, name: &str, value: &str) -> Option<()> { + match name { + "request" => self.method = Some(value.to_owned()), + "url" if self.url.is_none() => self.url = Some(value.to_owned()), + "globoff" => self.globoff = true, + "header" => self.header(value), + "data" | "data-ascii" | "data-binary" => self.data.push(data(value)?), + "data-raw" => self.data.push(Data::Text(value.to_owned())), + "data-urlencode" => self.data.push(Data::Text(urlencode(value)?)), + "json" => { + // Unlike other data, several `--json` are joined without a `&`. + match (self.data.last_mut(), data(value)?) { + (Some(Data::Text(last)), Data::Text(more)) => last.push_str(&more), + (_, more) => self.data.push(more), + } + self.json = true; + } + "url-query" => self.query.push(match value.strip_prefix('+') { + Some(raw) => raw.to_owned(), + None => urlencode(value)?, + }), + "form" => self.form.push(Field::parse(value)?), + "form-string" => self.form.push(Field::literal(value)?), + "upload-file" if matches!(value, "" | "-" | ".") => return None, + "upload-file" => self.upload = Some(value.to_owned()), + "user" => self.derive("Authorization", basic(value)), + "oauth2-bearer" => self.derive("Authorization", format!("Bearer {value}")), + // Without a `=` it names a file to read cookies from. + "cookie" if value.contains('=') => { + match self.headers.iter_mut().find(|h| !h.explicit && h.name == "Cookie") { + Some(cookie) => cookie.value = format!("{};{value}", cookie.value), + None => self.derive("Cookie", value.to_owned()), + } + } + "user-agent" => self.derive("User-Agent", value.to_owned()), + "referer" => self.derive("Referer", value.strip_suffix(";auto").unwrap_or(value).to_owned()), + "get" => self.get = true, + "head" => self.head = true, + _ => {} + } + Some(()) + } + + fn header(&mut self, line: &str) { + let (name, value) = match (line.split_once(':'), line.strip_suffix(';')) { + (Some((name, value)), _) if value.trim().is_empty() => { + self.removed.push(name.trim().to_ascii_lowercase()); + return; + } + (Some((name, value)), _) => (name, value), + (None, Some(name)) => (name, ""), + // A file of headers. + (None, None) => return, + }; + self.headers.push(Header { name: name.trim().to_owned(), value: value.trim().to_owned(), explicit: true }); + } + + /// The header an option sets; the last such option wins. + fn derive(&mut self, name: &str, value: String) { + self.headers.retain(|h| h.explicit || h.name != name); + if !value.is_empty() { + self.headers.push(Header { name: name.to_owned(), value, explicit: false }); + } + } + + fn into_http(mut self) -> Option { + let mut url = self.url.take()?; + if !self.globoff { + for bracket in ['[', ']', '{', '}'] { + url = url.replace(&format!("\\{bracket}"), &bracket.to_string()); + } + } + let has_body = !self.form.is_empty() || (!self.data.is_empty() && !self.get); + let default_method = match (self.head, &self.upload) { + (true, _) => "HEAD", + (_, Some(_)) => "PUT", + _ if has_body => "POST", + _ => "GET", + }; + let method = self.method.take().unwrap_or_else(|| default_method.to_owned()); + if let Some(path) = &self.upload { + url = upload_url(url, path); + } + let mut query = Vec::new(); + if self.get { + for data in std::mem::take(&mut self.data) { + match data { + Data::Text(text) => query.push(text), + Data::File(_) => return None, + } + } + } + query.append(&mut self.query); + if !query.is_empty() { + url = with_query(&url, &query.join("&")); + } + let body = self.body()?; + let headers: Vec<&Header> = self + .headers + .iter() + .filter(|h| h.explicit || !(self.sets(&h.name) || self.removed.contains(&h.name.to_ascii_lowercase()))) + .collect(); + let mut out = format!("{method} {url}\n"); + for header in headers { + out.push_str(format!("{}: {}", header.name, header.value).trim_end()); + out.push('\n'); + } + if let Some(body) = body { + out.push('\n'); + out.push_str(&body); + out.push('\n'); + } + Some(out) + } + + /// Whether a `-H` option sets header `name`. + fn sets(&self, name: &str) -> bool { + self.headers.iter().any(|h| h.explicit && h.name.eq_ignore_ascii_case(name)) + } + + /// The body text, with the headers it implies added. + fn body(&mut self) -> Option> { + if !self.form.is_empty() { + self.headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type")); + self.derive("Content-Type", format!("multipart/form-data; boundary={BOUNDARY}")); + let mut text = String::new(); + for field in &self.form { + field.write(&mut text); + } + text.push_str(&format!("--{BOUNDARY}--")); + return Some(Some(text)); + } + if let Some(path) = &self.upload { + return Some(Some(format!("< {path}"))); + } + if self.data.is_empty() { + return Some(None); + } + if self.json { + self.derive("Content-Type", "application/json".to_owned()); + self.derive("Accept", "application/json".to_owned()); + } else { + self.derive("Content-Type", "application/x-www-form-urlencoded".to_owned()); + } + if let [Data::File(path)] = self.data.as_slice() { + return Some(Some(format!("< {path}"))); + } + let mut parts = Vec::new(); + for data in &self.data { + match data { + Data::Text(text) => parts.push(text.as_str()), + // A file is a line of its own in a request file, so it can't be joined with `&`. + Data::File(_) => return None, + } + } + Some(Some(parts.join("&"))) + } +} + +/// The value of `-d`: text, or `@file`. `None` for standard input. +fn data(value: &str) -> Option { + match value.strip_prefix('@') { + Some("" | "-") => None, + Some(path) => Some(Data::File(path.to_owned())), + None => Some(Data::Text(value.to_owned())), + } +} + +/// `content`, `=content` or `name=content`, with the content encoded; `None` for `@file` and +/// `name@file`. +fn urlencode(value: &str) -> Option { + let (name, content) = match value.split_once('=') { + Some((name, content)) => (name, content), + None if value.contains('@') => return None, + None => ("", value), + }; + let mut out = String::new(); + if !name.is_empty() { + out.push_str(name); + out.push('='); + } + for byte in content.bytes() { + match byte { + b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => out.push(byte as char), + b' ' => out.push('+'), + _ => out.push_str(&format!("%{byte:02X}")), + } + } + Some(out) +} + +/// `Basic user password`, which is encoded when the request is sent; encoded here when it can't be +/// written as two words. +fn basic(user: &str) -> String { + let (name, password) = user.split_once(':').unwrap_or((user, "")); + let is_word = |s: &str| !s.is_empty() && !s.contains(char::is_whitespace); + if is_word(name) && is_word(password) { + format!("Basic {name} {password}") + } else { + format!("Basic {}", STANDARD.encode(format!("{name}:{password}"))) + } +} + +/// An upload to a folder goes to the file of the same name in it. +fn upload_url(url: String, path: &str) -> String { + let end = url.find(['?', '#']).unwrap_or(url.len()); + let (target, rest) = url.split_at(end); + let after_scheme = target.split_once("://").map_or(target, |(_, after)| after); + let slash = match after_scheme.rsplit_once('/') { + None => "/", + Some((_, "")) => "", + Some(_) => return url, + }; + let base = path.rsplit(['/', '\\']).next().unwrap_or(path); + format!("{target}{slash}{base}{rest}") +} + +fn with_query(url: &str, query: &str) -> String { + let (target, fragment) = url.split_at(url.find('#').unwrap_or(url.len())); + let separator = match target.split_once('?') { + None => "?", + Some((_, "")) => "", + Some(_) => "&", + }; + format!("{target}{separator}{query}{fragment}") +} diff --git a/crates/ide-http/src/curl/options.rs b/crates/ide-http/src/curl/options.rs new file mode 100644 index 0000000000..acb55b93dd --- /dev/null +++ b/crates/ide-http/src/curl/options.rs @@ -0,0 +1,108 @@ +//! cURL's command-line options: which ones take a value, and clusters of short ones (`-sXPOST`). + +/// The options of `args` in order as `(long name, value)`, flags with an empty value and URLs as +/// `url`. `None` when an option lacks its value. +pub(super) fn parse(args: &[String]) -> Option> { + let mut out = Vec::new(); + let mut args = args.iter().map(String::as_str); + while let Some(arg) = args.next() { + if arg == "--" { + out.extend(args.by_ref().map(|url| ("url", url))); + } else if let Some(long) = arg.strip_prefix("--") { + // cURL itself has no `--opt=value`, but it is often written. + let (name, inline) = match long.split_once('=') { + Some((name, value)) if LONG_WITH_VALUE.contains(&name) => (name, Some(value)), + _ => (long, None), + }; + let value = match inline { + Some(value) => value, + None if LONG_WITH_VALUE.contains(&name) => args.next()?, + None => "", + }; + out.push((name, value)); + } else if let Some(cluster) = arg.strip_prefix('-').filter(|c| !c.is_empty()) { + for (i, flag) in cluster.char_indices() { + if !SHORT_WITH_VALUE.contains(flag) { + out.push((long_name(flag), "")); + continue; + } + let rest = &cluster[i + flag.len_utf8()..]; + out.push((long_name(flag), if rest.is_empty() { args.next()? } else { rest })); + break; + } + } else { + out.push(("url", arg)); + } + } + Some(out) +} + +/// The long name of a short option that says something about the request; empty for the others. +fn long_name(flag: char) -> &'static str { + match flag { + 'A' => "user-agent", + 'b' => "cookie", + 'd' => "data", + 'e' => "referer", + 'F' => "form", + 'G' => "get", + 'H' => "header", + 'I' => "head", + 'T' => "upload-file", + 'u' => "user", + 'X' => "request", + ':' => "next", + _ => "", + } +} + +const SHORT_WITH_VALUE: &str = "ACDEFHKPQTUXYbcdemortuwxyz"; + +/// From `curl --help all`, including options newer than the cURL most systems ship. +#[rustfmt::skip] +const LONG_WITH_VALUE: &[&str] = &[ + "abstract-unix-socket", "alt-svc", "aws-sigv4", "cacert", "capath", "cert", "cert-type", "ciphers", "config", + "connect-timeout", "connect-to", "continue-at", "cookie", "cookie-jar", "create-file-mode", "crlfile", "curves", + "data", "data-ascii", "data-binary", "data-raw", "data-urlencode", "delegation", "dns-interface", + "dns-ipv4-addr", "dns-ipv6-addr", "dns-servers", "doh-url", "dump-header", "ech", "egd-file", "engine", + "etag-compare", "etag-save", "expect100-timeout", "form", "form-string", "ftp-account", + "ftp-alternative-to-user", "ftp-method", "ftp-port", "ftp-ssl-ccc-mode", "happy-eyeballs-timeout-ms", + "haproxy-clientip", "header", "hostpubmd5", "hostpubsha256", "hsts", "interface", "ip-tos", "ipfs-gateway", + "json", "keepalive-cnt", "keepalive-time", "key", "key-type", "knownhosts", "krb", "libcurl", "limit-rate", + "local-port", "login-options", "mail-auth", "mail-from", "mail-rcpt", "max-filesize", "max-redirs", "max-time", + "netrc-file", "noproxy", "oauth2-bearer", "output", "output-dir", "parallel-max", "parallel-max-host", "pass", + "pinnedpubkey", "preproxy", "proto", "proto-default", "proto-redir", "proxy", "proxy-cacert", "proxy-capath", + "proxy-cert", "proxy-cert-type", "proxy-ciphers", "proxy-crlfile", "proxy-header", "proxy-key", + "proxy-key-type", "proxy-pass", "proxy-pinnedpubkey", "proxy-service-name", "proxy-tls13-ciphers", + "proxy-tlsauthtype", "proxy-tlspassword", "proxy-tlsuser", "proxy-user", "proxy1.0", "pubkey", "quote", + "random-file", "range", "rate", "referer", "request", "request-target", "resolve", "retry", "retry-delay", + "retry-max-time", "sasl-authzid", "service-name", "sigalgs", "socks4", "socks4a", "socks5", + "socks5-gssapi-service", "socks5-hostname", "speed-limit", "speed-time", "stderr", "telnet-option", + "tftp-blksize", "time-cond", "tls-max", "tls13-ciphers", "tlsauthtype", "tlspassword", "tlsuser", "trace", + "trace-ascii", "trace-config", "unix-socket", "upload-file", "upload-flags", "url", "url-query", "user", + "user-agent", "variable", "vlan-priority", "write-out", +]; + +#[cfg(test)] +mod tests { + use super::parse; + + #[test] + fn clusters_and_values() { + let cases: &[(&str, &[(&str, &str)])] = &[ + ("-sX POST u", &[("", ""), ("request", "POST"), ("url", "u")]), + ("-sXPUT u", &[("", ""), ("request", "PUT"), ("url", "u")]), + ("-kd@f -I u", &[("", ""), ("data", "@f"), ("head", ""), ("url", "u")]), + ("-D h.txt --dump-header h u", &[("", "h.txt"), ("dump-header", "h"), ("url", "u")]), + ("-X=A u", &[("request", "=A"), ("url", "u")]), + ("--url=u --compressed=x", &[("url", "u"), ("compressed=x", "")]), + ("-d x -- -u", &[("data", "x"), ("url", "-u")]), + ]; + for (args, options) in cases { + let args: Vec = args.split(' ').map(str::to_owned).collect(); + assert_eq!(parse(&args).as_deref(), Some(*options), "{args:?}"); + } + assert_eq!(parse(&["-X".to_owned()]), None); + assert_eq!(parse(&["--max-time".to_owned()]), None); + } +} diff --git a/crates/ide-http/src/curl/words.rs b/crates/ide-http/src/curl/words.rs new file mode 100644 index 0000000000..a0aae97baa --- /dev/null +++ b/crates/ide-http/src/curl/words.rs @@ -0,0 +1,288 @@ +//! Splits a pasted command into words, as the shell it was written for does. + +/// The words of the command: POSIX quoting (with bash's `$'…'`), or `cmd.exe` quoting when a caret +/// escapes a quote or continues a line. Output redirections and pipes end the command. `None` for an +/// unclosed quote, or when another command follows. +pub(super) fn split(cmd: &str) -> Option> { + let cmd = cmd.trim().replace("\r\n", "\n"); + let chars: Vec = cmd.chars().collect(); + let mut words = Words::default(); + let mut i = 0; + while let Some(&c) = chars.get(i) { + i += 1; + let next = chars.get(i).copied(); + match c { + '^' if matches!(next, Some('"' | '\n')) => return split_cmd(&chars), + '\\' | '`' if next == Some('\n') => i += 1, + '\'' => { + let len = chars[i..].iter().position(|&c| c == '\'')?; + words.push_str(&chars[i..i + len]); + i += len + 1; + } + '$' if next == Some('\'') => i = ansi_c(&chars, i + 1, &mut words)?, + '$' if next == Some('"') => {} + '"' => { + words.in_word = true; + loop { + let c = *chars.get(i)?; + let next = chars.get(i + 1).copied(); + i += 1; + match (c, next) { + ('"', _) => break, + ('\\', Some('\n')) => i += 1, + ('\\', Some(escaped @ ('"' | '\\' | '$' | '`'))) => { + words.push(escaped); + i += 1; + } + _ => words.push(c), + } + } + } + '\\' => { + words.in_word = true; + words.current.extend(next); + i += 1; + } + c if c.is_whitespace() => words.end(), + c => match operator(c, next, words.in_word) { + Operator::None => words.push(c), + Operator::Output => break, + Operator::Separator => return chars[i..].iter().all(|c| c.is_whitespace()).then(|| words.finish()), + }, + } + } + Some(words.finish()) +} + +#[derive(Default)] +struct Words { + words: Vec, + current: String, + in_word: bool, +} + +impl Words { + fn push(&mut self, c: char) { + self.in_word = true; + self.current.push(c); + } + + fn push_str(&mut self, chars: &[char]) { + self.in_word = true; + self.current.extend(chars); + } + + fn end(&mut self) { + if std::mem::take(&mut self.in_word) { + self.words.push(std::mem::take(&mut self.current)); + } + } + + fn finish(mut self) -> Vec { + self.end(); + self.words + } +} + +enum Operator { + None, + /// A pipe or a redirection of the output. + Output, + /// `;`, `&` or `&&`. + Separator, +} + +/// The unquoted `c` as a shell operator. Inside a word `;`, `&`, `<` and `>` are kept: URLs and +/// placeholders are often pasted unquoted. +fn operator(c: char, next: Option, in_word: bool) -> Operator { + let ends_word = next.is_none_or(char::is_whitespace); + match c { + '|' => Operator::Output, + '>' | '<' if !in_word => Operator::Output, + ';' if ends_word => Operator::Separator, + '&' if ends_word || !in_word => Operator::Separator, + _ => Operator::None, + } +} + +/// Reads bash's `$'…'` from `i` (after its opening quote); the index after the closing one. +fn ansi_c(chars: &[char], mut i: usize, words: &mut Words) -> Option { + // `\xHH` and octal escapes are bytes; several may make up one character. + let mut bytes: Vec = Vec::new(); + loop { + let c = *chars.get(i)?; + i += 1; + if c == '\'' { + break; + } + if c != '\\' { + push_char(&mut bytes, c); + continue; + } + let escape = *chars.get(i)?; + i += 1; + let (radix, max_digits) = match escape { + 'x' => (16, 2), + 'u' => (16, 4), + 'U' => (16, 8), + '0'..='7' => { + i -= 1; + (8, 3) + } + _ => { + let c = match escape { + 'a' => '\x07', + 'b' => '\x08', + 'e' | 'E' => '\x1b', + 'f' => '\x0c', + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + 'v' => '\x0b', + 'c' => { + let control = *chars.get(i)?; + i += 1; + (control.to_ascii_uppercase() as u8 & 0x1f) as char + } + '\\' | '\'' | '"' | '?' => escape, + _ => { + bytes.push(b'\\'); + escape + } + }; + push_char(&mut bytes, c); + continue; + } + }; + let digits: String = chars[i..].iter().take(max_digits).take_while(|c| c.is_digit(radix)).collect(); + i += digits.len(); + match u32::from_str_radix(&digits, radix) { + Err(_) => bytes.extend([b'\\', escape as u8]), + Ok(code) if matches!(escape, 'u' | 'U') => push_char(&mut bytes, char::from_u32(code)?), + Ok(byte) => bytes.push(byte as u8), + } + } + words.in_word = true; + words.current.push_str(&String::from_utf8_lossy(&bytes)); + Some(i) +} + +fn push_char(bytes: &mut Vec, c: char) { + bytes.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()); +} + +/// `cmd.exe` removes the carets that escape a character outside quotes, then the program splits +/// what is left by the rules of the Microsoft C runtime. +fn split_cmd(chars: &[char]) -> Option> { + let mut line = Vec::new(); + let mut quoted = false; + let mut i = 0; + while let Some(&c) = chars.get(i) { + i += 1; + match c { + '"' => quoted = !quoted, + '^' if !quoted => { + // After a continued line the first character is taken as it is, carets included. + if chars.get(i) == Some(&'\n') { + i += 1; + } + line.extend(chars.get(i)); + i += 1; + continue; + } + _ if !quoted => { + let in_word = line.last().is_some_and(|c: &char| !c.is_whitespace()); + match operator(c, chars.get(i).copied(), in_word) { + Operator::None => {} + Operator::Output => break, + Operator::Separator if chars[i..].iter().all(|c| c.is_whitespace()) => break, + Operator::Separator => return None, + } + } + _ => {} + } + line.push(c); + } + split_crt(&line) +} + +fn split_crt(chars: &[char]) -> Option> { + let mut words = Words::default(); + let mut quoted = false; + let mut i = 0; + while let Some(&c) = chars.get(i) { + i += 1; + match c { + '\\' => { + let run = 1 + chars[i..].iter().take_while(|&&c| c == '\\').count(); + i += run - 1; + let before_quote = chars.get(i) == Some(&'"'); + words.push_str(&vec!['\\'; if before_quote { run / 2 } else { run }]); + if before_quote && run % 2 == 1 { + words.push('"'); + i += 1; + } + } + '"' if quoted && chars.get(i) == Some(&'"') => { + words.push('"'); + i += 1; + } + '"' => { + words.in_word = true; + quoted = !quoted; + } + c if c.is_whitespace() && !quoted => words.end(), + c => words.push(c), + } + } + (!quoted).then(|| words.finish()) +} + +#[cfg(test)] +mod tests { + use super::split; + + #[test] + fn posix_words() { + let cases: &[(&str, &[&str])] = &[ + (r#"a 'b c'"d\"e\$f"\ g"#, &["a", "b cd\"e$f g"]), + ("a \\\n b \\\r\n c `\n d", &["a", "b", "c", "d"]), + ("a \"b\\\nc\"", &["a", "bc"]), + ("a '' \"\"", &["a", "", ""]), + (r"a $'it\'s\n\t\\ \u0021\x41\101\U1f600 \q'", &["a", "it's\n\t\\ !AA\u{1f600} \\q"]), + (r"a $'\xc3\xa9' $'\cA'x", &["a", "é", "\u{1}x"]), + (r#"a $"b" $c d$"#, &["a", "b", "$c", "d$"]), + ("a http://h/?x=1&y=2;z= b", &["a", "http://h/?x=1&y=2;z=", "b"]), + ("a b | jq .x", &["a", "b"]), + ("a b > out.json", &["a", "b"]), + ("a b;", &["a", "b"]), + ]; + for (cmd, words) in cases { + assert_eq!(split(cmd).as_deref().unwrap_or_default(), *words, "{cmd}"); + } + } + + #[test] + fn cmd_words() { + let cases: &[(&str, &[&str])] = &[ + // What Chrome and Firefox escape a JSON body to. + (r#"a ^"^{^"^"b^"^":^"^"c d^"^"^}^""#, &["a", r#"{"b":"c d"}"#]), + (r#"a ^"^{^\^"b^\^":1^}^""#, &["a", r#"{"b":1}"#]), + ("a ^\n ^\"b^\" ^\r\n -c", &["a", "b", "-c"]), + ("a ^\"one^\n\ntwo^\"", &["a", "one\ntwo"]), + (r#"a ^"x^%^41^&y^|z^" "q^r" 'b c'"#, &["a", "x%41&y|z", "q^r", "'b", "c'"]), + (r#"a ^"c:\dir\\^" ^"\\x^""#, &["a", r"c:\dir\", r"\\x"]), + ("a ^\"b^\" | jq", &["a", "b"]), + ]; + for (cmd, words) in cases { + assert_eq!(split(cmd).as_deref().unwrap_or_default(), *words, "{cmd}"); + } + } + + #[test] + fn unclosed_quotes_and_several_commands_are_rejected() { + for cmd in ["a 'b", "a \"b", "a $'b", "a ^\"b", "a b ;\na c", "a b && a c", "a ^\"b^\" &\r\na c"] { + assert_eq!(split(cmd), None, "{cmd}"); + } + } +} diff --git a/crates/ide-http/tests/curl_paste.rs b/crates/ide-http/tests/curl_paste.rs new file mode 100644 index 0000000000..3cfeafa247 --- /dev/null +++ b/crates/ide-http/tests/curl_paste.rs @@ -0,0 +1,190 @@ +//! A pasted cURL command, converted and run by the HTTP Client, sends what the real cURL sends. +#![cfg(unix)] + +use ide_core::CancellationToken; +use ide_http::RunInput; +use ide_http::curl::from_curl; +use std::path::Path; +use std::process::Command; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +#[derive(Debug, PartialEq)] +struct Received { + request_line: String, + headers: Vec, + body: String, +} + +async fn receive(listener: &TcpListener) -> Received { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 4096]; + loop { + let read = socket.read(&mut buffer).await.unwrap(); + assert!(read > 0, "request ended before its body"); + request.extend_from_slice(&buffer[..read]); + let text = String::from_utf8(request.clone()).unwrap(); + let Some((head, body)) = text.split_once("\r\n\r\n") else { continue }; + let (request_line, lines) = head.split_once("\r\n").unwrap(); + let mut headers: Vec = lines.lines().map(str::to_owned).collect(); + let header = |name: &str| { + headers.iter().find_map(|h| { + let (n, v) = h.split_once(':')?; + n.eq_ignore_ascii_case(name).then(|| v.trim().to_owned()) + }) + }; + if body.len() < header("content-length").map_or(0, |l| l.parse().unwrap()) { + continue; + } + socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await.unwrap(); + // The boundary is up to the sender, and so is the line break after the last one. + let boundary = header("content-type").and_then(|v| Some(v.split_once("boundary=")?.1.to_owned())); + let unify = |s: &str| boundary.as_ref().map_or(s.to_owned(), |b| s.replace(b, "B").trim_end().to_owned()); + headers = headers + .iter() + .map(|h| { + let (name, value) = h.split_once(':').unwrap(); + format!("{}: {}", name.to_ascii_lowercase(), unify(value.trim())).trim_end().to_owned() + }) + // What each client sends on its own. + .filter(|h| { + !["host:", "content-length:", "accept: */*", "user-agent: curl/"].iter().any(|p| h.starts_with(p)) + }) + .filter(|h| !h.starts_with("accept-encoding:") && !h.starts_with("user-agent: OpenIDEA")) + .collect(); + headers.sort(); + return Received { request_line: request_line.to_owned(), headers, body: unify(body) }; + } +} + +/// `None` when the installed cURL is too old for an option. +async fn sent_by_curl(dir: &Path, command: &str, listener: &TcpListener) -> Option { + let command = command.replacen("curl ", "curl --noproxy '*' --max-time 5 -sS -o /dev/null ", 1); + let mut child = tokio::process::Command::new("bash").args(["-c", &command]).current_dir(dir).spawn().unwrap(); + tokio::select! { + received = receive(listener) => { + assert!(child.wait().await.unwrap().success(), "{command}"); + Some(received) + } + status = child.wait() => { + assert_eq!(status.unwrap().code(), Some(2), "{command}"); + None + } + } +} + +/// `None` when the request doesn't reach the server. +async fn sent_by_the_client(dir: &Path, text: &str, listener: &TcpListener) -> Option { + let file = dir.join("requests.http"); + let cancel = CancellationToken::new(); + let input = RunInput { text, index: 0, file: Some(&file), root: Some(dir), env: None }; + let both = async { tokio::join!(ide_http::run(input, &cancel), receive(listener)).1 }; + tokio::time::timeout(Duration::from_secs(5), both).await.ok() +} + +fn missing(tool: &str) -> bool { + !Command::new(tool).arg("--version").output().is_ok_and(|o| o.status.success()) +} + +const COMMANDS: &[&str] = &[ + // Clusters, and options whose value is not the URL. + "curl -sX POST {url}/a", + "curl -sXPUT -dfoo {url}/a", + "curl -D /dev/null -C 0 -y 5 -Y 1 {url}/a", + "curl --dump-header /dev/null --max-redirs 3 --retry-delay 1 --retry-max-time 5 {url}/a", + // Methods. + "curl -I {url}/a", + "curl -I -G -d q=1 {url}/a", + "curl -T f.json {url}/dir/", + "curl -T f.json {url}", + "curl -T f.json -X POST {url}/up?x=1", + // Data. + "curl -d @f.json -H 'Content-Type: application/json' {url}/a", + "curl --data-binary @f.json {url}/a", + "curl --data-raw @f.json {url}/a", + "curl -d a=1 --data-urlencode 'b=x y&é/~' --data-urlencode '=p=q' --data-urlencode 'x y' {url}/a", + "curl -G -d a=1 --data-urlencode 'b=c d' '{url}/a?z'", + "curl -G -d a=1 '{url}/a?'", + "curl --json '{\"a\":' --json '1}' -H 'Content-Type: x/y' {url}/a", + "curl --url-query 'q=a b' --url-query '+r=1' -d body '{url}/a?z=1'", + // Forms. + "curl -F 'note=hi;type=text/plain' -F 'n2= x y ; type=text/html; charset=utf-8;filename=\"q\\\"r.txt\"' {url}/a", + "curl -F 'f=@f.json;type=application/json;filename=z.json' -F 'g=