use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use reqwest::header::{ACCEPT, CONTENT_TYPE, COOKIE, REFERER, SET_COOKIE, USER_AGENT};
#[derive(Debug, Clone)]
pub struct ReqOptions {
pub method: Option<String>,
pub headers: Vec<String>,
pub data: Vec<String>,
pub json: Option<String>,
pub head: bool,
pub follow: bool,
pub max_redirs: usize,
pub silent: bool,
pub verbose: bool,
pub max_time: Option<f64>,
pub basic_auth: Option<String>,
pub cookie: Option<String>,
pub cookiejar: Option<PathBuf>,
pub proxy: Option<String>,
pub insecure: bool,
pub cert: Option<PathBuf>,
pub key: Option<PathBuf>,
pub user_agent: Option<String>,
pub referer: Option<String>,
pub output: Option<PathBuf>,
}
impl Default for ReqOptions {
fn default() -> Self {
Self {
method: None,
headers: Vec::new(),
data: Vec::new(),
json: None,
head: false,
follow: false,
max_redirs: 10,
silent: false,
verbose: false,
max_time: None,
basic_auth: None,
cookie: None,
cookiejar: None,
proxy: None,
insecure: false,
cert: None,
key: None,
user_agent: None,
referer: None,
output: None,
}
}
}
#[derive(Debug)]
pub struct FetchResult {
pub status: u16,
pub version: String,
pub headers: reqwest::header::HeaderMap,
pub body: Vec<u8>,
pub final_url: String,
}
pub fn parsed_http_url(url: &str) -> Result<url::Url> {
let u = url::Url::parse(url).with_context(|| format!("invalid URL: {url}"))?;
match u.scheme() {
"http" | "https" => Ok(u),
other => bail!(
"xget req handles only http(s): {url} (scheme '{other}' is out of scope — ftp/smtp/imap need a dedicated client like curl or lftp)"
),
}
}
pub fn parse_header_arg(s: &str) -> Result<(String, String)> {
let (name, value) = s
.split_once(':')
.with_context(|| format!("bad header (need 'Name: value'): {s}"))?;
if name.trim().is_empty() {
bail!("bad header (need 'Name: value'): {s}");
}
Ok((name.trim().to_string(), value.trim().to_string()))
}
fn body_for(
data: &[String],
json: Option<&str>,
) -> Result<(Option<Vec<u8>>, Option<&'static str>)> {
if let Some(j) = json {
if !data.is_empty() {
bail!("cannot combine --data with --json");
}
return Ok((Some(j.as_bytes().to_vec()), Some("application/json")));
}
if data.is_empty() {
return Ok((None, None));
}
Ok((
Some(data.join("&").into_bytes()),
Some("application/x-www-form-urlencoded"),
))
}
fn cookie_header_value(arg: &str) -> Result<String> {
if arg.contains('=') {
return Ok(arg.to_string());
}
let raw =
std::fs::read_to_string(arg).with_context(|| format!("cannot read cookie file: {arg}"))?;
let pairs = parse_netscape_jar(&raw);
if pairs.is_empty() {
return Ok(raw.lines().next().unwrap_or("").trim().to_string());
}
Ok(pairs
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect::<Vec<_>>()
.join("; "))
}
pub fn parse_netscape_jar(text: &str) -> Vec<(String, String)> {
text.lines()
.filter(|l| {
let t = l.trim();
!t.is_empty() && !t.starts_with('#')
})
.filter_map(|l| {
let f: Vec<&str> = l.split('\t').collect();
if f.len() >= 7 {
Some((f[5].to_string(), f[6].to_string()))
} else {
None
}
})
.collect()
}
pub fn save_cookiejar(path: &Path, domain: &str, set_cookies: &[String]) -> Result<()> {
let mut jar: BTreeMap<String, String> = BTreeMap::new();
if path.exists()
&& let Ok(raw) = std::fs::read_to_string(path)
{
for (k, v) in parse_netscape_jar(&raw) {
jar.insert(k, v);
}
}
for sc in set_cookies {
let first = sc.split(';').next().unwrap_or("").trim();
if let Some((k, v)) = first.split_once('=')
&& !k.trim().is_empty()
{
jar.insert(k.trim().to_string(), v.trim().to_string());
}
}
let mut out = String::from("# Netscape HTTP Cookie File\n");
for (k, v) in &jar {
out.push_str(&format!("{domain}\tTRUE\t/\tFALSE\t0\t{k}\t{v}\n"));
}
if let Some(p) = path.parent()
&& !p.as_os_str().is_empty()
{
std::fs::create_dir_all(p).with_context(|| format!("cannot create {}", p.display()))?;
}
std::fs::write(path, out).with_context(|| format!("cannot write {}", path.display()))
}
fn build_client(o: &ReqOptions) -> Result<reqwest::Client> {
let mut b = reqwest::Client::builder();
b = if o.follow {
b.redirect(reqwest::redirect::Policy::limited(o.max_redirs))
} else {
b.redirect(reqwest::redirect::Policy::none())
};
if let Some(t) = o.max_time {
if t <= 0.0 {
bail!("--max-time must be > 0");
}
b = b.timeout(Duration::from_secs_f64(t));
}
if let Some(p) = &o.proxy {
b = b.proxy(reqwest::Proxy::all(p).with_context(|| format!("bad proxy URL: {p}"))?);
}
if o.insecure {
b = b.danger_accept_invalid_certs(true);
}
if let Some(cert) = &o.cert {
let mut pem = std::fs::read(cert)
.with_context(|| format!("cannot read --cert {}", cert.display()))?;
if let Some(key) = &o.key {
pem.extend_from_slice(
&std::fs::read(key)
.with_context(|| format!("cannot read --key {}", key.display()))?,
);
}
b = b.identity(
reqwest::Identity::from_pem(&pem)
.context("bad --cert/--key (need a client certificate in PEM)")?,
);
} else if o.key.is_some() {
bail!("--key needs --cert with the matching certificate");
}
b.build().context("cannot create HTTP client")
}
fn version_label(v: reqwest::Version) -> &'static str {
match v {
reqwest::Version::HTTP_09 => "HTTP/0.9",
reqwest::Version::HTTP_10 => "HTTP/1.0",
reqwest::Version::HTTP_11 => "HTTP/1.1",
reqwest::Version::HTTP_2 => "HTTP/2",
reqwest::Version::HTTP_3 => "HTTP/3",
_ => "HTTP/?",
}
}
pub async fn fetch(url: &str, o: &ReqOptions) -> Result<FetchResult> {
let parsed = parsed_http_url(url)?;
let (body, default_ct) = body_for(&o.data, o.json.as_deref())?;
let method_s = o.method.clone().unwrap_or_else(|| {
if o.head {
"HEAD".into()
} else if body.is_some() {
"POST".into()
} else {
"GET".into()
}
});
let method = reqwest::Method::from_bytes(method_s.as_bytes())
.with_context(|| format!("bad method: {method_s}"))?;
let mut headers = reqwest::header::HeaderMap::new();
let mut explicit_ct = false;
let mut explicit_accept = false;
let mut explicit_ua = false;
let mut explicit_referer = false;
let mut explicit_cookie = false;
for h in &o.headers {
let (n, v) = parse_header_arg(h)?;
let name = reqwest::header::HeaderName::from_bytes(n.as_bytes())
.with_context(|| format!("bad header name: {n}"))?;
let value = reqwest::header::HeaderValue::from_str(&v)
.with_context(|| format!("bad header value for {n}"))?;
explicit_ct |= name == CONTENT_TYPE;
explicit_accept |= name == ACCEPT;
explicit_ua |= name == USER_AGENT;
explicit_referer |= name == REFERER;
explicit_cookie |= name == COOKIE;
headers.insert(name, value);
}
if !explicit_ua {
headers.insert(
USER_AGENT,
reqwest::header::HeaderValue::from_str(
o.user_agent.as_deref().unwrap_or("xget-req/0.1"),
)
.context("bad --user-agent")?,
);
}
if !explicit_referer && let Some(r) = &o.referer {
headers.insert(
REFERER,
reqwest::header::HeaderValue::from_str(r).context("bad --referer")?,
);
}
if let Some(ct) = default_ct
&& !explicit_ct
{
headers.insert(CONTENT_TYPE, reqwest::header::HeaderValue::from_static(ct));
}
if o.json.is_some() && !explicit_accept {
headers.insert(
ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
}
if !explicit_cookie && let Some(c) = &o.cookie {
let v = cookie_header_value(c)?;
if !v.is_empty() {
headers.insert(
COOKIE,
reqwest::header::HeaderValue::from_str(&v).context("bad cookie value")?,
);
}
}
let client = build_client(o)?;
let mut rb = client
.request(method.clone(), parsed.as_str())
.headers(headers);
if let Some(a) = &o.basic_auth {
let (user, pass) = a
.split_once(':')
.map(|(u, p)| (u, Some(p)))
.unwrap_or((a.as_str(), None));
rb = rb.basic_auth(user, pass);
}
if let Some(b) = body {
rb = rb.body(b);
}
let req = rb.build().context("cannot build request")?;
if o.verbose {
let target = parsed.path();
let target = match parsed.query() {
Some(q) => format!("{target}?{q}"),
None => target.to_string(),
};
eprintln!("> {} {target} HTTP/1.1", req.method());
if let Some(h) = parsed.host_str() {
eprintln!("> Host: {h}");
}
for (k, v) in req.headers() {
eprintln!("> {}: {}", k, v.to_str().unwrap_or("?"));
}
eprintln!(">");
}
let res = client
.execute(req)
.await
.with_context(|| format!("request failed: {url}"))?;
let status = res.status().as_u16();
let version = version_label(res.version()).to_string();
let headers = res.headers().clone();
let final_url = res.url().to_string();
if o.verbose {
eprintln!(
"< {version} {status} {}",
res.status().canonical_reason().unwrap_or("")
);
for (k, v) in &headers {
eprintln!("< {}: {}", k, v.to_str().unwrap_or("?"));
}
eprintln!("<");
}
if let Some(jar) = &o.cookiejar {
let set: Vec<String> = headers
.get_all(SET_COOKIE)
.iter()
.filter_map(|v| v.to_str().ok().map(str::to_string))
.collect();
if !set.is_empty() {
save_cookiejar(jar, parsed.host_str().unwrap_or(""), &set)?;
}
}
let body = res
.bytes()
.await
.context("cannot read response body")?
.to_vec();
Ok(FetchResult {
status,
version,
headers,
body,
final_url,
})
}
pub async fn run_req(url: &str, o: &ReqOptions) -> Result<()> {
let res = fetch(url, o).await?;
if o.head {
println!("{} {} {}", res.version, res.status, reason_of(res.status));
for (k, v) in &res.headers {
println!("{}: {}", k, v.to_str().unwrap_or("?"));
}
return Ok(());
}
match &o.output {
Some(p) if p.as_os_str() == "/dev/null" => {}
Some(p) => {
if let Some(parent) = p.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::create_dir_all(parent)
.with_context(|| format!("cannot create {}", parent.display()))?;
}
std::fs::write(p, &res.body)
.with_context(|| format!("cannot write {}", p.display()))?;
}
None => {
std::io::stdout()
.lock()
.write_all(&res.body)
.context("cannot write to stdout")?;
}
}
if !o.silent {
let via = if res.final_url != url {
format!(" (via {})", res.final_url)
} else {
String::new()
};
match &o.output {
Some(p) => eprintln!(
"xget req: HTTP {} {} B -> {}{via}",
res.status,
res.body.len(),
p.display()
),
None => eprintln!("xget req: HTTP {} {} B{via}", res.status, res.body.len()),
}
}
Ok(())
}
fn reason_of(status: u16) -> &'static str {
reqwest::StatusCode::from_u16(status)
.ok()
.and_then(|s| s.canonical_reason())
.unwrap_or("")
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
fn opts() -> ReqOptions {
ReqOptions::default()
}
async fn handle_conn(mut sock: tokio::net::TcpStream) {
let mut buf: Vec<u8> = Vec::new();
let mut tmp = [0u8; 4096];
let head_end = loop {
match sock.read(&mut tmp).await {
Ok(0) => return,
Ok(n) => {
buf.extend_from_slice(&tmp[..n]);
if buf.len() > 2_000_000 {
return;
}
if let Some(i) = find_headers_end(&buf) {
break i;
}
}
Err(_) => return,
}
};
let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
let mut lines = head.lines();
let request_line = lines.next().unwrap_or("").to_string();
let mut hm: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for l in lines {
if let Some((k, v)) = l.split_once(':') {
hm.insert(k.trim().to_lowercase(), v.trim().to_string());
}
}
let cl: usize = hm
.get("content-length")
.and_then(|v| v.parse().ok())
.unwrap_or(0);
while buf.len() < head_end + cl && buf.len() < 5_000_000 {
match sock.read(&mut tmp).await {
Ok(0) => break,
Ok(n) => buf.extend_from_slice(&tmp[..n]),
Err(_) => break,
}
}
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("").to_string();
let target = parts.next().unwrap_or("/").to_string();
let body = String::from_utf8_lossy(
&buf[head_end..head_end + cl.min(buf.len().saturating_sub(head_end))],
)
.to_string();
let (status, extra, payload) = if target == "/redir" {
(302, "location: /echo\r\n".to_string(), "go".to_string())
} else if target == "/setcookie" {
(
200,
"set-cookie: jar1=tasty; Path=/\r\n".to_string(),
echo_json(&method, &target, &hm, &body),
)
} else {
(200, String::new(), echo_json(&method, &target, &hm, &body))
};
let reason = match status {
200 => "OK",
302 => "Found",
_ => "?",
};
let resp = format!(
"HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n{extra}\r\n{payload}",
payload.len()
);
let _ = sock.write_all(resp.as_bytes()).await;
}
fn echo_json(
method: &str,
target: &str,
hm: &std::collections::HashMap<String, String>,
body: &str,
) -> String {
let get = |k: &str| hm.get(k).cloned().unwrap_or_default();
serde_json::json!({
"method": method,
"path": target,
"body": body,
"cookie": get("cookie"),
"echo": get("x-echo"),
"ua": get("user-agent"),
"referer": get("referer"),
"auth": get("authorization"),
"content_type": get("content-type"),
})
.to_string()
}
fn find_headers_end(buf: &[u8]) -> Option<usize> {
buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4)
}
async fn spawn_echo() -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let a = l.local_addr().unwrap();
let h = tokio::spawn(async move {
loop {
let Ok((s, _)) = l.accept().await else { break };
tokio::spawn(handle_conn(s));
}
});
(a, h)
}
async fn echo_body(
addr: &std::net::SocketAddr,
path: &str,
o: ReqOptions,
) -> serde_json::Value {
let r = fetch(&format!("http://{addr}{path}"), &o).await.unwrap();
assert_eq!(r.status, 200);
serde_json::from_slice(&r.body).unwrap()
}
#[tokio::test]
async fn rejects_non_http() {
for u in [
"ftp://h/f",
"smtp://h",
"imap://h/x",
"magnet:?xt=urn:btih:abc",
] {
let e = format!("{}", fetch(u, &opts()).await.unwrap_err());
assert!(e.contains("only http(s)"), "unexpected: {e}");
}
}
#[tokio::test]
async fn sends_method_headers_body() {
let (a, _h) = spawn_echo().await;
let mut o = opts();
o.method = Some("PUT".into());
o.headers = vec!["X-Echo: ping".into()];
o.data = vec!["a=1".into(), "b=2".into()];
let v = echo_body(&a, "/echo", o).await;
assert_eq!(v["method"], "PUT");
assert_eq!(v["echo"], "ping");
assert_eq!(v["body"], "a=1&b=2");
assert_eq!(v["content_type"], "application/x-www-form-urlencoded");
}
#[tokio::test]
async fn json_sets_content_type_and_post() {
let (a, _h) = spawn_echo().await;
let mut o = opts();
o.json = Some(r#"{"a":1}"#.into());
let v = echo_body(&a, "/echo", o).await;
assert_eq!(v["method"], "POST");
assert_eq!(v["body"], r#"{"a":1}"#);
assert_eq!(v["content_type"], "application/json");
}
#[tokio::test]
async fn redirect_only_with_follow() {
let (a, _h) = spawn_echo().await;
let plain = fetch(&format!("http://{a}/redir"), &opts()).await.unwrap();
assert_eq!(plain.status, 302);
let mut o = opts();
o.follow = true;
let r = fetch(&format!("http://{a}/redir"), &o).await.unwrap();
assert_eq!(r.status, 200);
assert!(
r.final_url.ends_with("/echo"),
"unexpected: {}",
r.final_url
);
}
#[tokio::test]
async fn cookie_send_and_jar_save() {
let (a, _h) = spawn_echo().await;
let mut o = opts();
o.cookie = Some("a=1; b=2".into());
let v = echo_body(&a, "/echo", o).await;
assert_eq!(v["cookie"], "a=1; b=2");
let dir = std::env::temp_dir().join(format!("xget-req-test-{}", std::process::id()));
let jar = dir.join("jar.txt");
let mut o2 = opts();
o2.cookiejar = Some(jar.clone());
fetch(&format!("http://{a}/setcookie"), &o2).await.unwrap();
let raw = std::fs::read_to_string(&jar).unwrap();
assert!(raw.contains("jar1\ttasty"), "unexpected jar: {raw}");
let mut o3 = opts();
o3.cookie = Some(jar.to_string_lossy().to_string());
let v3 = echo_body(&a, "/echo", o3).await;
assert!(v3["cookie"].as_str().unwrap().contains("jar1=tasty"));
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn auth_ua_referer_and_output_file() {
let (a, _h) = spawn_echo().await;
let dir = std::env::temp_dir().join(format!("xget-req-test-{}.2", std::process::id()));
let out = dir.join("out.json");
let mut o = opts();
o.basic_auth = Some("me:secret".into());
o.user_agent = Some("ua-test/1".into());
o.referer = Some("http://ref.example/".into());
o.output = Some(out.clone());
o.silent = true;
run_req(&format!("http://{a}/echo"), &o).await.unwrap();
let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap();
assert_eq!(v["ua"], "ua-test/1");
assert_eq!(v["referer"], "http://ref.example/");
assert!(v["auth"].as_str().unwrap().starts_with("Basic "));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn header_arg_rules() {
assert!(parse_header_arg("X-A: b").is_ok());
assert!(parse_header_arg("no-colon").is_err());
assert!(parse_header_arg(": v").is_err());
}
}