mod others;
use crate::route::{Partial, RequestPath};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Seen {
pub(crate) program: &'static str,
pub(crate) host: Option<String>,
pub(crate) methods: Option<Vec<String>>,
pub(crate) target: Target,
pub(crate) headers: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Target {
Known(String),
Partial(Vec<Partial>),
Unknown,
}
const EXPANDED: &[char] = &['$', '`'];
const GLOB: &[char] = &['{', '}', '[', ']'];
pub(crate) fn read(argv: &[String]) -> Vec<Seen> {
let Some((first, words)) = argv.split_first() else {
return Vec::new();
};
let base = first.rsplit(['/', '\\']).next().unwrap_or(first);
let base = base.trim_start_matches('\\').to_ascii_lowercase();
let base = base.strip_suffix(".exe").unwrap_or(&base);
match base {
"curl" => curl(words),
"wget" => wget(words),
"http" => others::httpie(words, "http", "http"),
"https" => others::httpie(words, "https", "https"),
"xh" => others::httpie(words, "xh", "http"),
"xhs" => others::httpie(words, "xhs", "https"),
"curlie" => others::httpie(words, "curlie", "https"),
"gh" => others::gh(words),
other => others::inline(other, words),
}
}
pub(crate) fn fetch(url: &str) -> Option<Seen> {
let (host, target) = url_parts(url, "https", false)?;
Some(Seen {
program: "fetch tool",
host,
methods: Some(vec!["GET".to_owned()]),
target,
headers: Vec::new(),
})
}
pub(crate) fn url_parts(
word: &str,
default: &str,
globs: bool,
) -> Option<(Option<String>, Target)> {
let unknown = |c: char| EXPANDED.contains(&c) || (globs && GLOB.contains(&c));
let (scheme, rest) = word.split_once("://").unwrap_or((default, word));
if scheme.contains(unknown) {
return Some((None, Target::Unknown));
}
if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
return None;
}
let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let (authority, tail) = rest.split_at(end);
let tail = tail.split('#').next().unwrap_or_default();
let host = if authority.contains(unknown) {
None
} else {
let after_user = authority.rsplit('@').next().unwrap_or(authority);
let host = match after_user.rsplit_once(':') {
Some((h, port)) if port.bytes().all(|b| b.is_ascii_digit()) => h,
_ => after_user,
};
let host = host.trim_end_matches('.').to_ascii_lowercase();
if host.contains('%') {
None
} else if host.is_empty() {
Some("localhost".to_owned())
} else {
Some(host)
}
};
let target = if tail.starts_with('/') {
tail.to_owned()
} else {
format!("/{tail}")
};
let target = target_of(&target, &unknown, &|_| false);
if host.is_none() {
return Some((None, unhosted(target)));
}
Some((host, target))
}
fn unhosted(target: Target) -> Target {
let mut parts = vec![Partial::Rest];
match target {
Target::Known(known) => parts.extend(
RequestPath::parse(&known)
.ok()
.into_iter()
.flat_map(|p| p.segments().to_vec())
.map(Partial::Known),
),
Target::Partial(rest) => parts.extend(rest),
Target::Unknown => return Target::Unknown,
}
Target::Partial(parts)
}
pub(crate) fn unknown_request(program: &'static str) -> Seen {
Seen {
program,
host: None,
methods: None,
target: Target::Unknown,
headers: Vec::new(),
}
}
pub(crate) fn target_of(
target: &str,
unknown: &dyn Fn(char) -> bool,
one: &dyn Fn(&str) -> bool,
) -> Target {
let path = target.split('?').next().unwrap_or_default();
if !target.contains(unknown) && !path.split('/').any(one) {
return Target::Known(target.to_owned());
}
let segments = path
.split('/')
.skip(1)
.map(|segment| {
if segment.contains(unknown) {
Partial::Rest
} else if one(segment) {
Partial::One
} else {
match RequestPath::parse(&format!("/{segment}")) {
Ok(p) => p
.segments()
.first()
.map_or(Partial::Known(String::new()), |s| Partial::Known(s.clone())),
Err(_) => Partial::Rest,
}
}
})
.collect();
Target::Partial(segments)
}
pub(crate) fn header_name(value: &str) -> Option<String> {
let (name, _) = value.split_once(':')?;
let name = name.trim();
(!name.is_empty() && !name.contains(EXPANDED)).then(|| name.to_owned())
}
const CURL_VALUED_LONG: &[&str] = &[
"--output",
"--user",
"--user-agent",
"--referer",
"--proxy",
"--proxy-user",
"--cookie",
"--cookie-jar",
"--cacert",
"--capath",
"--cert",
"--key",
"--max-time",
"--connect-timeout",
"--retry",
"--retry-delay",
"--retry-max-time",
"--write-out",
"--resolve",
"--connect-to",
"--dump-header",
"--limit-rate",
"--range",
"--interface",
"--oauth2-bearer",
"--unix-socket",
"--abstract-unix-socket",
"--proto",
"--proto-redir",
"--proto-default",
"--max-redirs",
"--stderr",
"--trace",
"--trace-ascii",
"--netrc-file",
"--keepalive-time",
"--url-query",
"--variable",
"--aws-sigv4",
"--ciphers",
"--local-port",
"--dns-servers",
"--doh-url",
"--pinnedpubkey",
"--hsts",
"--alt-svc",
"--etag-save",
"--etag-compare",
"--output-dir",
"--create-file-mode",
"--mail-from",
"--mail-rcpt",
"--quote",
"--socks5",
"--socks5-hostname",
"--preproxy",
"--noproxy",
"--time-cond",
"--tls-max",
"--max-filesize",
"--speed-limit",
"--speed-time",
"--continue-at",
"--cert-type",
"--key-type",
"--pass",
"--engine",
"--happy-eyeballs-timeout-ms",
"--expect100-timeout",
"--parallel-max",
];
const CURL_VALUED: &str = "AbcCdDeEFHKmoPQrtTuUwxXyYz";
#[derive(Default)]
#[expect(
clippy::struct_excessive_bools,
reason = "each is one curl option that decides the method; an enum per flag would only \
rename them"
)]
struct Curl<'a> {
method: Option<String>,
data: bool,
upload: bool,
head: bool,
get: bool,
globoff: bool,
unknown: bool,
config: bool,
target: bool,
rerouted: bool,
headers: Vec<String>,
urls: Vec<&'a str>,
}
impl<'a> Curl<'a> {
fn take(&mut self, name: &str, value: Option<&'a str>) {
match name {
"--request" | "-X" => self.method = value.map(str::to_owned),
"--data" | "-d" | "--data-ascii" | "--data-binary" | "--data-raw"
| "--data-urlencode" | "--json" | "--form" | "-F" | "--form-string" => self.data = true,
"--upload-file" | "-T" => self.upload = true,
"--url" => self.urls.extend(value),
"--header" | "-H" => {
let name = value.and_then(header_name);
let unknown = value.is_some_and(|v| v.contains(EXPANDED) || !v.contains(':'));
if unknown
|| name
.as_deref()
.is_some_and(|n| n.eq_ignore_ascii_case("host"))
{
self.rerouted = true;
}
self.headers.extend(name);
}
"--get" | "-G" => self.get = true,
"--head" | "-I" => self.head = true,
"--globoff" | "-g" => self.globoff = true,
"--config" | "-K" => self.config = true,
"--request-target" => self.target = true,
"--connect-to" | "--resolve" => self.rerouted = true,
"--next" | "-:" => self.unknown = true,
other if other.starts_with("--expand-") => self.unknown = true,
_ => {}
}
}
fn valued_long(name: &str) -> bool {
matches!(
name,
"--request"
| "--data"
| "--data-ascii"
| "--data-binary"
| "--data-raw"
| "--data-urlencode"
| "--json"
| "--form"
| "--form-string"
| "--upload-file"
| "--url"
| "--header"
| "--config"
| "--request-target"
) || name.starts_with("--expand-")
|| CURL_VALUED_LONG.contains(&name)
}
fn methods(&self) -> Option<Vec<String>> {
if self.unknown || self.config || self.method.as_ref().is_some_and(|m| m.contains(EXPANDED))
{
return None;
}
let method = match &self.method {
Some(method) => method.as_str(),
None if self.head => "HEAD",
None if self.upload => "PUT",
None if self.data && !self.get => "POST",
None => "GET",
};
Some(vec![method.to_owned()])
}
}
fn curl(args: &[String]) -> Vec<Seen> {
let mut c = Curl::default();
let mut i = 0;
let mut options = true;
while let Some(word) = args.get(i) {
i += 1;
if !options || !word.starts_with('-') || word == "-" {
c.urls.push(word);
continue;
}
if word == "--" {
options = false;
} else if let Some((name, value)) = word.split_once('=').filter(|_| word.starts_with("--"))
{
c.take(name, Some(value));
} else if word.starts_with("--") {
let value = if Curl::valued_long(word) {
i += 1;
args.get(i - 1).map(String::as_str)
} else {
None
};
c.take(word, value);
} else {
for (at, letter) in word.char_indices().skip(1) {
let name = format!("-{letter}");
if CURL_VALUED.contains(letter) {
let rest = &word[at + letter.len_utf8()..];
let value = if rest.is_empty() {
i += 1;
args.get(i - 1).map(String::as_str)
} else {
Some(rest)
};
c.take(&name, value);
break;
}
c.take(&name, None);
}
}
}
let methods = c.methods();
let mut seen: Vec<Seen> = c
.urls
.iter()
.filter_map(|url| url_parts(url, "http", !c.globoff))
.map(|(host, target)| {
let (host, target) = match (c.rerouted, c.target) {
(_, true) => (host.filter(|_| !c.rerouted), Target::Unknown),
(true, false) => (None, unhosted(target)),
(false, false) => (host, target),
};
Seen {
program: "curl",
host,
methods: methods.clone(),
target,
headers: c.headers.clone(),
}
})
.collect();
if c.config || c.unknown {
seen.push(unknown_request("curl"));
}
seen
}
const WGET_VALUED: &str = "aABDeiIlOoPQTtUwX";
const WGET_VALUED_LONG: &[&str] = &[
"--method",
"--post-data",
"--post-file",
"--body-data",
"--body-file",
"--header",
"--execute",
"--input-file",
"--config",
"--output-document",
"--output-file",
"--user",
"--password",
"--http-user",
"--http-password",
"--user-agent",
"--referer",
"--directory-prefix",
"--tries",
"--timeout",
"--wait",
"--load-cookies",
"--save-cookies",
"--ca-certificate",
"--certificate",
"--private-key",
"--level",
"--accept",
"--reject",
"--domains",
"--limit-rate",
];
fn wget(args: &[String]) -> Vec<Seen> {
let (mut method, mut post, mut unknown) = (None::<String>, false, false);
let mut headers = Vec::new();
let mut urls: Vec<&str> = Vec::new();
let mut take = |name: &str, value: Option<&str>| match name {
"--method" => method = value.map(str::to_owned),
"--post-data" | "--post-file" => post = true,
"--header" => headers.extend(value.and_then(header_name)),
"--execute" | "-e" | "--input-file" | "-i" | "--config" => unknown = true,
_ => {}
};
let mut i = 0;
while let Some(word) = args.get(i) {
i += 1;
if !word.starts_with('-') {
urls.push(word);
} else if let Some((name, value)) = word.split_once('=').filter(|_| word.starts_with("--"))
{
take(name, Some(value));
} else if word.starts_with("--") {
let value = WGET_VALUED_LONG.contains(&word.as_str()).then(|| {
i += 1;
args.get(i - 1).map(String::as_str)
});
take(word, value.flatten());
} else {
for (at, letter) in word.char_indices().skip(1) {
if WGET_VALUED.contains(letter) {
if word[at + letter.len_utf8()..].is_empty() {
i += 1;
}
take(&format!("-{letter}"), None);
break;
}
}
}
}
let methods = if unknown || method.as_ref().is_some_and(|m| m.contains(EXPANDED)) {
None
} else {
Some(vec![method.unwrap_or_else(|| {
if post { "POST" } else { "GET" }.to_owned()
})])
};
let mut seen: Vec<Seen> = urls
.iter()
.filter_map(|url| url_parts(url, "http", false))
.map(|(host, target)| Seen {
program: "wget",
host,
methods: methods.clone(),
target,
headers: headers.clone(),
})
.collect();
if unknown {
seen.push(unknown_request("wget"));
}
seen
}
#[cfg(test)]
mod tests;