дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Several -b cookies of a pasted curl command are joined into one Cookie header with "; ", the RFC 6265 separator. The curl comparison test now ignores the whitespace after ";" in Cookie headers, since curl releases differ there (macOS curl 8.7 sends "a=1;b=2", ubuntu-latest sends "a=1; b=2").
197 рядки
8.4 KiB
Rust
197 рядки
8.4 KiB
Rust
//! 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<String>,
|
|
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<String> = 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();
|
|
let name = name.to_ascii_lowercase();
|
|
let mut value = unify(value.trim());
|
|
// curl releases join several -b with `;` or `; `.
|
|
if name == "cookie" {
|
|
value = value.split(';').map(str::trim).collect::<Vec<_>>().join("; ");
|
|
}
|
|
format!("{name}: {value}").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<Received> {
|
|
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<Received> {
|
|
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 '[email protected];type=application/json;filename=z.json' -F 'g=<f.json' -F 'q=\"a;b\"' {url}/a",
|
|
"curl --form-string 'a=@x;type=b' {url}/a",
|
|
// Headers.
|
|
"curl -H 'X-Empty;' -H 'X-None:' -H 'X-Trim: v ' {url}/a",
|
|
"curl -H 'Content-Type:' -d x {url}/a",
|
|
"curl -b a=1 -b 'b=2; c=3' -b cookies.txt -A agent -e 'http://r;auto' {url}/a",
|
|
"curl -u bob:secret {url}/a",
|
|
"curl -u bob: {url}/a",
|
|
"curl -u 'bob:se cret:x' {url}/a",
|
|
"curl -u bob:secret -H 'Authorization: mine' {url}/a",
|
|
"curl --oauth2-bearer abc {url}/a",
|
|
// Quoting, as Chrome copies it, and the rest of a command line.
|
|
r#"curl --url '{url}/a' -X $'PUT' -H $'x-title: it\'s!' --data-raw $'{"a":"b\\né"}'"#,
|
|
"curl '{url}/\\[a\\]'",
|
|
"curl -s {url}/a | cat",
|
|
];
|
|
|
|
#[tokio::test]
|
|
async fn a_converted_command_sends_what_curl_sends() {
|
|
if missing("curl") || missing("bash") {
|
|
eprintln!("skipped: no curl or bash on PATH");
|
|
return;
|
|
}
|
|
let dir = tempfile::tempdir().unwrap();
|
|
std::fs::write(dir.path().join("f.json"), "{\"from\": \"file\"}").unwrap();
|
|
let mut failures = Vec::new();
|
|
for command in COMMANDS {
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let command = command.replace("{url}", &format!("http://{}", listener.local_addr().unwrap()));
|
|
let expected =
|
|
tokio::time::timeout(Duration::from_secs(20), sent_by_curl(dir.path(), &command, &listener)).await.unwrap();
|
|
if expected.is_none() {
|
|
eprintln!("skipped, not known to this curl: {command}");
|
|
continue;
|
|
}
|
|
let Some(text) = from_curl(&command) else {
|
|
failures.push(format!("{command}\n not converted"));
|
|
continue;
|
|
};
|
|
let sent = sent_by_the_client(dir.path(), &text, &listener).await;
|
|
if sent != expected {
|
|
failures.push(format!("{command}\n curl {expected:?}\n client {sent:?}\n from {text:?}"));
|
|
}
|
|
}
|
|
assert!(failures.is_empty(), "{} of {} differ\n{}", failures.len(), COMMANDS.len(), failures.join("\n"));
|
|
}
|
|
|
|
/// What a request file can't express stays as pasted.
|
|
#[test]
|
|
fn commands_that_cannot_be_expressed_are_not_converted() {
|
|
for command in [
|
|
"curl -d @- http://h",
|
|
"curl -T - http://h",
|
|
"curl -d a=1 -d @f.json http://h",
|
|
"curl -G -d @f.json http://h",
|
|
"curl --data-urlencode [email protected] http://h",
|
|
"curl -F 'f=@a,b' http://h",
|
|
"curl -F '=(;type=multipart/mixed' http://h",
|
|
"curl 'http://h/1' ;\ncurl 'http://h/2'",
|
|
"curl -X",
|
|
] {
|
|
assert_eq!(from_curl(command), None, "{command}");
|
|
}
|
|
}
|
|
|
|
/// Chrome's "Copy as cURL (cmd)".
|
|
#[test]
|
|
fn a_windows_command_is_converted() {
|
|
let command = "curl --url ^\"https://example.com/api?q=1^&r=^%^20^\" ^\r\n -X ^\"PUT^\" ^\r\n \
|
|
-H ^\"accept: */*^\" ^\r\n -H ^\"sec-ch-ua: ^\"^\"Chromium^\"^\";v=^\"^\"140^\"^\"^\" ^\r\n \
|
|
-H ^\"content-type: application/json^\" ^\r\n --data-raw ^\"^{^\"^\"a^\"^\":^\"^\"b c^\"^\"^}^\"";
|
|
assert_eq!(
|
|
from_curl(command).unwrap(),
|
|
"PUT https://example.com/api?q=1&r=%20\naccept: */*\nsec-ch-ua: \"Chromium\";v=\"140\"\n\
|
|
content-type: application/json\n\n{\"a\":\"b c\"}\n"
|
|
);
|
|
}
|