diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 6e4421f88..406e76bf0 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -128,9 +128,7 @@ jobs: max_len: 65536 - target: fuzz_enrichers_config max_len: 65536 - - target: fuzz_command_argv - max_len: 4096 - - target: fuzz_command_argv_clusters + - target: fuzz_command_strict max_len: 1024 - target: fuzz_extract_jq max_len: 4096 diff --git a/CHANGELOG.md b/CHANGELOG.md index ce27d5896..613d72132 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ All notable changes to RSigma are documented in this file. Each entry correspond ## [Unreleased] +- Fired deadman correlations no longer leave their suppression entries in memory forever: an entry is dropped when its group fires without suppression, and otherwise once its suppression window passes on that tenant's own clock (#863) - A shed batch still runs its `template`, `lookup`, `stix`, and `mmdb` enrichers, and a detection whose dedup, `group_by`, or risk-object selector reads the field of a skipped or shed enricher is no longer folded into a different detection or credited to an entity; it counts in `rsigma_alert_identity_incomplete_total` (#862) - A `dns` enricher's circuit breaker now opens only when its resolver cannot be reached, since an event picks the zone whose owner decides SERVFAIL, REFUSED, timeouts, and slow answers, and when its cooldown ends it asks the resolver for the root zone's `NS` records instead of using a detection's query as the probe (#861) - An `http` enricher no longer sends a request whose rendered URL or header value is over 8 KiB or whose rendered body is over 1 MiB, and such a request, or one the client cannot build, applies `on_error` without counting against the circuit breaker (#861) @@ -11,6 +12,12 @@ All notable changes to RSigma are documented in this file. Each entry correspond - An enricher skipped by its open circuit breaker or shed for want of capacity now leaves its `inject_field` absent and records `skipped` or `shed` under its id in the result's top-level `enrichment_status`, so no selector, matcher, or entity graph reads the status as an enriched value, and an `entity_graph` selector that resolves to an object or array no longer forms a join edge (#860) - PostgreSQL substring field references no longer hide matches in rows with more than 1024 values; such rows are returned as matches (#859) +### Command enrichers take event values only through `env` (#864) + +**Breaking changes:** command enrichers can no longer place event values in argv; use env instead. + +Migration: move each event value from argv into env and read it as `"$NAME"` (sh) or `$env:NAME` (pwsh). Put `--` before it where the tool supports it. See docs: [Passing event values safely](https://rsigma.io/guide/enrichers/#passing-event-values-safely). + ### A new state database is created with one commit (#858) `engine daemon --state-db` created each table of a new state database, and added each migrated column, in a statement of its own, so a new database took nine commits before the daemon started listening. Every commit flushes to disk, which is slow on Windows and slower still on a busy disk: on a loaded Windows CI runner, a daemon with a new state database did not finish startup within 10 seconds. The schema is now created or migrated, and then checked, in one transaction, so a new or earlier database takes one commit and a current one takes none. On the Windows runner, opening a new state database now takes about 40 ms instead of about 100 ms, and at most 50 ms under load instead of 500 ms. diff --git a/crates/rsigma-cli/README.md b/crates/rsigma-cli/README.md index 704ba5f0e..79b791001 100644 --- a/crates/rsigma-cli/README.md +++ b/crates/rsigma-cli/README.md @@ -1608,8 +1608,8 @@ Per-result `tokio::process::Command` invocation with template-expanded argv and inject_field: ip_reputation command: - "/usr/local/bin/check-ip-rep" - - "${detection.fields.SourceIp}" env: + SOURCE_IP: "${detection.fields.SourceIp}" REP_LOCAL_DB: "/var/lib/iprep.db" output: json # json (default) | raw timeout: 3s diff --git a/crates/rsigma-eval/src/correlation_engine/mod.rs b/crates/rsigma-eval/src/correlation_engine/mod.rs index 6fde35c28..75d48b293 100644 --- a/crates/rsigma-eval/src/correlation_engine/mod.rs +++ b/crates/rsigma-eval/src/correlation_engine/mod.rs @@ -253,6 +253,9 @@ pub struct CorrelationEngine { /// Each pending group's `fire_at` in `deadlines`, so its entry is found /// without a scan. deadline_of: HashMap, + /// Newest tenant clock at the last `last_alert` reclaim from the deadline + /// path, which scans every entry and so runs at most once per second. + last_alert_reclaimed_at: Option, } impl CorrelationEngine { @@ -303,6 +306,7 @@ impl CorrelationEngine { wall_clock_tenants: std::collections::HashSet::new(), deadlines: HashMap::new(), deadline_of: HashMap::new(), + last_alert_reclaimed_at: None, } } @@ -2115,14 +2119,23 @@ impl CorrelationEngine { } } - /// Drop an absence group after its deadman fired. Its `last_alert` entry - /// stays so suppression survives until the next heartbeat re-arms it. + /// Drop an absence group after its deadman fired. When the correlation + /// suppresses, its `last_alert` entry stays so suppression survives until + /// the next heartbeat re-arms it. fn drop_absence_group(&mut self, key: &StateKey) { self.state.remove(key); self.note_tenant_removal(key); self.event_buffers.remove(key); self.event_ref_buffers.remove(key); self.index_clear(key); + let suppress = self + .correlations + .get(key.corr_idx) + .and_then(|correlation| correlation.suppress_secs) + .or(self.config.suppress); + if suppress.is_none() { + self.last_alert.remove(key); + } } /// Fire one due obligation and chain its result into parent correlations. @@ -2310,6 +2323,10 @@ impl CorrelationEngine { } self.refresh_absence_index(&key); } + if self.last_alert_reclaimed_at.is_none_or(|at| before > at) { + self.last_alert_reclaimed_at = Some(before); + self.reclaim_last_alert(self.high_water); + } out } @@ -3169,8 +3186,17 @@ impl CorrelationEngine { } // Phase 3: Evict last_alert entries whose suppress window has passed. - // An alert after `now_secs` counts as expired, as in the suppression - // check, so it cannot outlive its window. + self.reclaim_last_alert(now_secs); + } + + /// Drop `last_alert` entries whose suppress window has passed. + /// + /// Each entry is measured against its own tenant's clock, so a tenant + /// running ahead neither ends another tenant's suppression early nor makes + /// its alerts look like they lie in the future. `now_secs` stands in for a + /// tenant without a clock. An alert after the reference counts as expired, + /// as in the suppression check, so it cannot outlive its window. + fn reclaim_last_alert(&mut self, now_secs: i64) { self.last_alert.retain(|key, &mut alert_ts| { let suppress = if key.corr_idx < self.correlations.len() { self.correlations[key.corr_idx] @@ -3180,7 +3206,8 @@ impl CorrelationEngine { } else { 0 }; - suppression_active(alert_ts, now_secs, suppress) + let reference = self.clocks.get(&key.tenant).copied().unwrap_or(now_secs); + suppression_active(alert_ts, reference, suppress) }); } diff --git a/crates/rsigma-eval/src/correlation_engine/tests.rs b/crates/rsigma-eval/src/correlation_engine/tests.rs index 60841d323..5b87cffb0 100644 --- a/crates/rsigma-eval/src/correlation_engine/tests.rs +++ b/crates/rsigma-eval/src/correlation_engine/tests.rs @@ -6603,6 +6603,121 @@ correlation: assert_eq!(armed.deadline, 260); } +#[test] +fn fired_deadman_groups_do_not_accumulate_last_alert() { + let yaml = r#"--- +title: Silent +correlation: + type: temporal + group-by: [User] + timespan: 60s + condition: not a +"#; + let groups = 10_000; + for suppress in [None, Some(300)] { + let config = CorrelationConfig { + suppress, + ..CorrelationConfig::default() + }; + let mut engine = absence_engine(yaml, config); + assert!(groups < engine.config.max_state_entries); + for i in 0..groups { + hit(&mut engine, "a", &format!("user{i}"), 100); + } + assert_eq!(engine.advance_clock(None, 161).len(), groups); + assert_eq!(engine.state_count(), 0); + // A group keeps its alert only for its suppress window. + let kept = if suppress.is_some() { groups } else { 0 }; + assert_eq!(engine.last_alert.len(), kept, "suppress {suppress:?}"); + + assert!(engine.advance_clock(None, 460).is_empty()); + assert_eq!(engine.last_alert.len(), 0, "suppress {suppress:?}"); + } +} + +#[test] +fn suppression_still_honored_before_expiry() { + let yaml = r#"--- +title: Silent +correlation: + type: temporal + group-by: [User] + timespan: 60s + condition: not a +rsigma.suppress: 300s +--- +title: Many B +correlation: + type: event_count + rules: [b] + group-by: [User] + timespan: 1h + condition: + gte: 1000 +"#; + let tenant_a = TenantId::new("a").unwrap(); + let tenant_b = TenantId::new("b").unwrap(); + let send = |engine: &mut CorrelationEngine, tenant: &TenantId, action: &str, user: &str, ts| { + let event = json!({"Action": action, "User": user}); + engine + .process_event_at_for_tenant(&JsonEvent::borrow(&event), ts, Some(tenant)) + .into_iter() + .filter(|r| r.header.rule_title == "Silent") + .count() + }; + let tick = |engine: &mut CorrelationEngine, tenant: &TenantId, ts| { + engine + .advance_clock(Some(tenant), ts) + .into_iter() + .filter(|r| r.header.rule_title == "Silent") + .count() + }; + + // Tenant B running far ahead does not end tenant A's suppression early. + let mut engine = absence_engine(yaml, CorrelationConfig::default()); + send(&mut engine, &tenant_a, "a", "host", 100); + assert_eq!(tick(&mut engine, &tenant_a, 161), 1); + send(&mut engine, &tenant_b, "a", "host", 900); + assert_eq!(tick(&mut engine, &tenant_b, 1000), 1); + assert_eq!(send(&mut engine, &tenant_a, "a", "host", 200), 0); + assert_eq!( + tick(&mut engine, &tenant_a, 261), + 0, + "A's 160 alert still suppresses 260" + ); + assert_eq!(send(&mut engine, &tenant_a, "a", "host", 500), 0); + assert_eq!( + tick(&mut engine, &tenant_a, 561), + 1, + "suppression ends at 460" + ); + + // An alert fired by an idle tick lies ahead of every event so far. A + // lagging tenant's events and ticks, which also reclaim through the + // state cap, must not treat it as expired. + let mut engine = absence_engine( + yaml, + CorrelationConfig { + max_state_entries: 2, + max_absence_entries: 2, + ..CorrelationConfig::default() + }, + ); + send(&mut engine, &tenant_a, "a", "host", 300); + send(&mut engine, &tenant_b, "a", "host", 500); + assert_eq!(tick(&mut engine, &tenant_b, 561), 1); + for (user, ts) in [("u1", 301), ("u2", 302), ("u3", 303)] { + send(&mut engine, &tenant_a, "b", user, ts); + } + assert_eq!(tick(&mut engine, &tenant_a, 304), 0); + assert_eq!(send(&mut engine, &tenant_b, "a", "host", 600), 0); + assert_eq!( + tick(&mut engine, &tenant_b, 661), + 0, + "B's 560 alert still suppresses 660" + ); +} + #[test] fn fallback_timestamps_do_not_advance_the_clock() { let mut engine = absence_engine(TEMPORAL, CorrelationConfig::default()); diff --git a/crates/rsigma-runtime/src/enrichment/command.rs b/crates/rsigma-runtime/src/enrichment/command.rs index f7f0d2e65..87b67312b 100644 --- a/crates/rsigma-runtime/src/enrichment/command.rs +++ b/crates/rsigma-runtime/src/enrichment/command.rs @@ -21,13 +21,10 @@ //! so operators can see what went wrong without grepping the daemon's //! tracing output. //! -//! The argv runs without a shell, so each rendered element is one argument. -//! An argv that would hand an event value to a program as code (a shell -//! script, an interpreter's inline code, the program path itself, an -//! option of a wrapper) fails every call, and the config loader rejects -//! it. An argument whose template starts with an event value is refused -//! when the value starts with `-`, unless a `--` of the program that -//! receives it comes earlier, so a value cannot pose as an option. +//! The argv runs without a shell, and no argv entry may take an event +//! value: event values reach the command only through `env`. A command +//! that breaks the rules in [`super::command_rules`] fails every call, and +//! the config loader rejects it. use std::collections::HashMap; use std::time::Duration; @@ -37,7 +34,7 @@ use rsigma_eval::EvaluationResult; use tokio::io::{AsyncRead, AsyncReadExt}; use tokio::process::Command; -use super::command_argv::{ArgvAnalysis, analyze, argv_problem, leading_dash_problem}; +use super::command_rules::{command_problem, has_result_ref}; use super::{ EnrichError, EnrichErrorKind, Enricher, EnricherKind, OnError, Scope, inject_enrichment, render_enricher_template, @@ -77,7 +74,6 @@ pub struct CommandEnricher { on_error: OnError, scope: Scope, output: OutputFormat, - analysis: ArgvAnalysis, argv_problem: Option, } @@ -94,8 +90,7 @@ impl CommandEnricher { scope: Scope, output: OutputFormat, ) -> Self { - let analysis = analyze(&argv); - let argv_problem = argv_problem(&argv, &env, &analysis); + let argv_problem = command_problem(&argv, &env).map(|(_, message)| message); Self { id, kind, @@ -106,7 +101,6 @@ impl CommandEnricher { on_error, scope, output, - analysis, argv_problem, } } @@ -217,6 +211,10 @@ impl Enricher for CommandEnricher { return Err(self.rejected("empty argv".to_string())); } if let Some(problem) = &self.argv_problem { + debug_assert!( + !self.argv.iter().any(|arg| has_result_ref(arg)), + "the config loader refuses this argv: {problem}" + ); return Err(self.rejected(problem.clone())); } @@ -225,9 +223,6 @@ impl Enricher for CommandEnricher { .iter() .map(|a| render_enricher_template(a, result)) .collect(); - if let Some(problem) = leading_dash_problem(&self.argv, &rendered, &self.analysis) { - return Err(self.rejected(problem)); - } let env: Vec<(&String, String)> = self .env diff --git a/crates/rsigma-runtime/src/enrichment/command_argv.rs b/crates/rsigma-runtime/src/enrichment/command_argv.rs deleted file mode 100644 index f6a7390dd..000000000 --- a/crates/rsigma-runtime/src/enrichment/command_argv.rs +++ /dev/null @@ -1,4355 +0,0 @@ -//! Static checks on a `command` enricher's argv. -//! -//! The enricher runs its argv directly, with no shell, so every rendered -//! element is one argument. That keeps an event value from splitting into -//! several arguments, but not from becoming code when the program treats an -//! argument as a program of its own: the script after `sh -c`, the command -//! line after `cmd /c`, the code after `python -c`, an `awk` or `jq` -//! program, or the command a wrapper such as `env` or `timeout` runs. -//! -//! [`analyze`] reads argv the way each shell, interpreter, and wrapper listed -//! here reads its own arguments, follows wrappers into the command they run, -//! and gives every argument a [`Role`]. A `${detection.*}` or -//! `${correlation.*}` reference may only appear where the program that -//! receives it takes data. For a program listed here, an argument the parser -//! cannot classify (an option it does not know, a sub-command it does not -//! model) is a place a reference cannot go, so the check fails closed. -//! Programs not listed here take every argument as data. - -use std::collections::HashMap; - -use super::template::{TemplateRef, template_refs}; - -/// How the program that reads an argument uses it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Role { - /// The program to run. - Program, - /// An option, option value, or operand the program uses itself: a - /// wrapper's user or timeout, an interpreter's settings. - Own, - /// Code, a script, or a module the program runs or loads. - Code, - /// An environment assignment that can make a program load code, or - /// whose variable name comes from a reference. - LoaderVariable, - /// A value the program passes on as data. - Data, - /// The value of an option, which the program takes verbatim even when - /// it starts with `-`. - OptionValue, - /// The parser cannot tell how the program reads it. - Unknown, -} - -impl Role { - fn allows_reference(self) -> bool { - matches!(self, Role::Data | Role::OptionValue) - } -} - -/// The [`Role`] of every argument of one argv. -#[derive(Debug, Clone)] -pub(crate) struct ArgvAnalysis { - roles: Vec, - /// The index of the program that reads each argument. - owners: Vec, - /// Whether the program at each index reads a `+` argument as an option. - plus_options: Vec, - /// Whether each argument is the separate value of the option before it. - option_values: Vec, - /// Where the `NAME=VALUE` text starts in each argument, past an option - /// it is attached to (`--env=NAME=VALUE`). - assignment_starts: Vec, - args_start: usize, -} - -impl ArgvAnalysis { - /// The role of `argv[index]`. - pub(crate) fn role(&self, index: usize) -> Role { - self.roles.get(index).copied().unwrap_or(Role::Unknown) - } - - /// Where the argument list of the program that receives the data - /// starts: after the wrappers, after an interpreter's options and code. - /// A `--` counts as the end of that program's options only at or after - /// this index. - pub(crate) fn args_start(&self) -> usize { - self.args_start - } - - /// Whether `argv[index]` is an option's value, so a `--` there does not - /// end the options. - fn is_option_value(&self, index: usize) -> bool { - self.option_values.get(index).copied().unwrap_or(false) - } - - fn mark_option_value(&mut self, index: usize) { - if let Some(slot) = self.option_values.get_mut(index) { - *slot = true; - } - } - - /// Whether the program that reads `argv[index]` takes `+` options. - fn reads_plus_options(&self, index: usize) -> bool { - self.owners - .get(index) - .and_then(|owner| self.plus_options.get(*owner)) - .copied() - .unwrap_or(false) - } - - fn set(&mut self, index: usize, role: Role, owner: usize) { - if let Some(slot) = self.roles.get_mut(index) { - *slot = role; - self.owners[index] = owner; - } - } - - fn rest(&mut self, from: usize, role: Role, owner: usize) { - for index in from..self.roles.len() { - self.set(index, role, owner); - } - } - - /// The `NAME=VALUE` text of `argv[index]`. - fn assignment<'s>(&self, index: usize, arg: &'s str) -> &'s str { - let start = self.assignment_starts.get(index).copied().unwrap_or(0); - arg.get(start..).unwrap_or(arg) - } - - /// Keep, for every argument from `from` on, the stricter role of this - /// reading and `other`: one a reference cannot use over one it can, and - /// data over an option value, which the leading-dash check skips. - fn merge(&mut self, other: &ArgvAnalysis, from: usize) { - for index in from..self.roles.len() { - let theirs = other.roles[index]; - if self.roles[index].allows_reference() - && (!theirs.allows_reference() || theirs == Role::Data) - { - self.roles[index] = theirs; - self.owners[index] = other.owners[index]; - } - } - for (mine, theirs) in self.option_values.iter_mut().zip(&other.option_values) { - *mine |= theirs; - } - for (mine, theirs) in self.plus_options.iter_mut().zip(&other.plus_options) { - *mine |= theirs; - } - } -} - -/// Why `argv` would let a rendered event value become a program or code, -/// or `None` when it does not. -pub(crate) fn command_argv_problem( - argv: &[String], - env: &HashMap, -) -> Option { - argv_problem(argv, env, &analyze(argv)) -} - -/// Like [`command_argv_problem`], for an argv already analyzed. -pub(crate) fn argv_problem( - argv: &[String], - env: &HashMap, - analysis: &ArgvAnalysis, -) -> Option { - const REF: &str = "${detection.*} or ${correlation.*}"; - let program_at = |index: usize| program_name(&resolve_env(&argv[analysis.owners[index]])); - for (index, arg) in argv.iter().enumerate() { - if !has_result_ref(arg) { - continue; - } - let role = analysis.role(index); - if role.allows_reference() { - continue; - } - let program = program_at(index); - return Some(match role { - Role::Program => { - format!("command[{index}] is the program to run and cannot use a {REF} reference") - } - Role::Code => format!( - "command[{index}] is code that {program} runs, so it cannot use a {REF} reference; pass the value as a separate argument or an environment variable the code reads" - ), - Role::Own => format!( - "command[{index}] is an option or operand that {program} reads itself, so it cannot use a {REF} reference; pass the value to the program {program} runs instead" - ), - Role::LoaderVariable => match analysis.assignment(index, arg).split_once('=') { - Some(("", _)) => format!( - "command[{index}] sets an environment variable with an empty name, so its value cannot use a {REF} reference" - ), - Some((name, _)) if !has_result_ref(name) => format!( - "command[{index}] sets {name}, which can make a program load code, so its value cannot use a {REF} reference; pass the value in another variable" - ), - _ => format!( - "command[{index}] takes the name of an environment variable from a {REF} reference" - ), - }, - _ => format!( - "rsigma cannot tell how {program} reads command[{index}], so it cannot use a {REF} reference; make the value a plain argument of the program that uses it, for example through a script that takes it as an argument" - ), - }); - } - - let mut names: Vec<(&String, &String)> = env.iter().collect(); - names.sort(); - if let Some((name, _)) = names - .iter() - .find(|(name, value)| has_result_ref(value) && loads_code(name)) - { - return Some(format!( - "env {name} uses a {REF} reference, and {name} can make a program load code; pass the value in another variable" - )); - } - - for (index, role) in analysis.roles.iter().enumerate() { - if *role != Role::Program || program_at(index) != "cmd" { - continue; - } - let line: String = argv - .iter() - .enumerate() - .filter(|(i, _)| analysis.owners[*i] == index && analysis.roles[*i] == Role::Code) - .map(|(_, arg)| arg.to_ascii_lowercase()) - .collect::>() - .join(" "); - if let Some((name, _)) = names.iter().find(|(name, value)| { - has_result_ref(value) && line.contains(&format!("%{}%", name.to_ascii_lowercase())) - }) { - return Some(format!( - "cmd expands %{name}% before it parses the command line, and {name} uses a {REF} reference; use delayed expansion (!{name}! with /V:ON) or pass the value as an argument" - )); - } - } - None -} - -/// Classify every argument of `argv`. -pub(crate) fn analyze(argv: &[String]) -> ArgvAnalysis { - let args: Vec = argv.iter().map(|a| resolve_env(a)).collect(); - let n = args.len(); - let mut analysis = ArgvAnalysis { - roles: vec![Role::Unknown; n], - owners: vec![0; n], - plus_options: vec![false; n], - option_values: vec![false; n], - assignment_starts: vec![0; n], - args_start: n, - }; - let mut at = 0; - while at < n { - analysis.set(at, Role::Program, at); - match parse_program(&args, at, &mut analysis) { - // A command starting with `-` means the wrapper's options were - // not read the way the wrapper reads them. - Next::Wrap(next) if args.get(next).is_some_and(|arg| arg.starts_with('-')) => { - analysis.rest(next, Role::Unknown, at); - break; - } - Next::Wrap(next) => at = next, - Next::Done(start) => { - // An option that takes a value can end the argv, pointing - // past it. - analysis.args_start = start.min(n); - break; - } - } - } - analysis -} - -/// What follows a program's own arguments. -enum Next { - /// The program receives the data; its argument list starts here. - Done(usize), - /// The program is a wrapper that runs the command starting here. - Wrap(usize), -} - -fn parse_program(args: &[String], at: usize, a: &mut ArgvAnalysis) -> Next { - let program = program_name(&args[at]); - let p = program.as_str(); - match p { - "bash" | "rbash" | "dash" => parse_shell(args, at, a, &[&SH]), - "ash" => parse_shell(args, at, a, &[&SH, &BUSYBOX_SH]), - "zsh" | "yash" => parse_shell(args, at, a, &[&ZSH]), - "ksh" | "ksh93" | "mksh" | "pdksh" | "lksh" => { - parse_shell(args, at, a, &[&KSH, &KSH_ATTACHED]) - } - "sh" => parse_shell(args, at, a, &[&SH, &BUSYBOX_SH, &ZSH, &KSH, &KSH_ATTACHED]), - "fish" => parse_interpreter(args, at, a, &FISH), - "csh" | "tcsh" => parse_csh(args, at, a), - "cmd" => parse_cmd(args, at, a), - "powershell" | "powershell_ise" => parse_powershell(args, at, a, false), - "pwsh" => parse_powershell(args, at, a, true), - "py" | "pythonw" => parse_interpreter(args, at, a, &PYTHON), - p if versioned(p, "python") || versioned(p, "pypy") => { - parse_interpreter(args, at, a, &PYTHON) - } - p if versioned(p, "perl") => parse_interpreter(args, at, a, &PERL), - p if versioned(p, "ruby") => parse_interpreter(args, at, a, &RUBY), - "luajit" => parse_interpreter(args, at, a, &LUA), - p if versioned(p, "lua") => parse_interpreter(args, at, a, &LUA), - p if versioned(p, "php") => parse_interpreter(args, at, a, &PHP), - "osascript" => parse_interpreter(args, at, a, &OSASCRIPT), - "rscript" => parse_interpreter(args, at, a, &RSCRIPT), - "node" | "nodejs" => parse_interpreter(args, at, a, &NODE), - "bun" => parse_bun(args, at, a), - "deno" => parse_deno(args, at, a), - p if versioned(p, "tclsh") => parse_tcl(args, at, a, TCLSH_OPTIONS), - p if versioned(p, "wish") => parse_tcl(args, at, a, WISH_OPTIONS), - "expect" => parse_interpreter(args, at, a, &EXPECT), - "awk" | "gawk" | "mawk" | "nawk" | "original-awk" | "bwk" => parse_awk(args, at, a), - "sed" | "gsed" => parse_sed(args, at, a), - "jq" | "jaq" | "gojq" => parse_jq(args, at, a), - "yq" => parse_yq(args, at, a), - "env" => parse_wrapper(args, at, a, &ENV), - "nice" => parse_wrapper(args, at, a, &NICE), - "nohup" => parse_wrapper(args, at, a, &NOHUP), - "setsid" => parse_wrapper(args, at, a, &SETSID), - "unbuffer" => parse_wrapper(args, at, a, &UNBUFFER), - "caffeinate" => parse_wrapper(args, at, a, &CAFFEINATE), - "timeout" | "gtimeout" => parse_wrapper(args, at, a, &TIMEOUT), - "stdbuf" => parse_wrapper(args, at, a, &STDBUF), - "time" => parse_wrapper(args, at, a, &TIME), - "ionice" => parse_wrapper(args, at, a, &IONICE), - "chrt" => parse_wrapper(args, at, a, &CHRT), - "taskset" => parse_wrapper(args, at, a, &TASKSET), - "chroot" => parse_wrapper(args, at, a, &CHROOT), - "sudo" => parse_wrapper(args, at, a, &SUDO), - "doas" => parse_wrapper(args, at, a, &DOAS), - "xargs" => parse_wrapper(args, at, a, &XARGS), - "pkexec" => parse_wrapper(args, at, a, &PKEXEC), - "watch" => parse_wrapper(args, at, a, &WATCH), - "flock" => parse_flock(args, at, a), - "su" | "runuser" => parse_su(args, at, a), - "wsl" => parse_wsl(args, at, a), - "docker" | "podman" | "nerdctl" => parse_container_cli(args, at, a), - "kubectl" | "oc" => parse_kubectl(args, at, a), - "busybox" => match args.get(at + 1) { - Some(applet) if !applet.starts_with('-') => Next::Wrap(at + 1), - _ => { - a.rest(at + 1, Role::Unknown, at); - Next::Done(args.len()) - } - }, - // These run a command from their arguments with a grammar of their - // own (a remote shell, a command string, a sandbox or namespace - // setup), so none of their arguments is known to be data. - "ssh" | "script" | "mshta" | "cscript" | "wscript" | "runas" | "parallel" - | "systemd-run" | "nsenter" | "unshare" | "firejail" | "bwrap" => { - a.rest(at + 1, Role::Unknown, at); - Next::Done(args.len()) - } - _ => { - a.rest(at + 1, Role::Data, at); - Next::Done(at + 1) - } - } -} - -/// Whether `name` is `base` with an optional version suffix (`python3.12`). -fn versioned(name: &str, base: &str) -> bool { - name.strip_prefix(base) - .is_some_and(|rest| rest.chars().all(|c| c.is_ascii_digit() || c == '.')) -} - -// --------------------------------------------------------------------------- -// Option parsing -// --------------------------------------------------------------------------- - -/// What an option takes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Arity { - Flag, - /// A value: attached, or the next argument. - Value(Role), - /// A value only when attached (`-i.bak`, `--lint=fatal`). - Optional(Role), - /// Two values as the next two arguments (`jq --arg NAME VALUE`). - Two(Role), - /// A number attached to the letter, after which the group goes on - /// (`perl -l0e`, `perl -0777n`): octal digits, or with `hex`, an `x` - /// and the rest of the group. - AttachedDigits { - hex: bool, - }, -} - -/// How one program spells its options. -struct Grammar { - short: fn(char) -> Option, - long: fn(&str) -> Option, - /// Short options may be grouped (`-xvf`), and a value may be attached - /// to a short option (`-ofile`). Without it, a single-dash argument - /// longer than one letter is looked up whole in `whole`. - cluster: bool, - /// Whole single-dash arguments with a meaning of their own (`node -pe`). - whole: fn(&str) -> Option, - /// Options may also start with `+` (`set +o`). - plus: bool, - /// Options may follow operands (GNU argument permutation). - permute: bool, - /// An unknown `--name=value` is one of the program's own settings. - attached_long_is_own: bool, - /// A value-taking short option inside a group reads its value from the - /// next argument, not from the rest of the group (POSIX sh `set` - /// style): `-euo pipefail`, `-oc errexit SCRIPT`. Several such letters - /// take the following arguments in order. - value_from_next_arg: bool, - /// A value-taking short option that ends its group does not take a next - /// argument that starts with `-` or `+`. - value_skips_options: bool, - /// A lone `-` ends the options like `--`. - dash_ends_options: bool, - /// With `plus`, a lone `+` ends the options like `--`; otherwise it is - /// an empty group of options. - plus_ends_options: bool, -} - -const NO_WHOLE: fn(&str) -> Option = |_| None; -const NO_LONG: fn(&str) -> Option = |_| None; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Name<'a> { - Short(char), - Long(&'a str), -} - -impl Name<'_> { - fn is(&self, short: &str, long: &[&str]) -> bool { - match self { - Name::Short(c) => short.contains(*c), - Name::Long(name) => long.contains(name), - } - } -} - -enum Event<'a> { - /// An option, with the index of its value when it has one. - Option { - name: Name<'a>, - value: Option, - }, - Operand(usize), - /// `--` at this index. - End(usize), - /// An option the grammar does not know; every argument from here on is - /// [`Role::Unknown`]. - Unknown, -} - -/// Walks a program's arguments, giving options and their values a role. -/// Operands are left to the caller. -struct Getopt<'a> { - args: &'a [String], - owner: usize, - grammar: &'a Grammar, - next: usize, - /// Byte offset of the next letter within `args[next]`, inside a group - /// of short options. - letter: Option, - done: bool, - /// Roles of the values the letters of the current group take from the - /// arguments after it, in order, with `value_from_next_arg`. - pending: Vec, - /// The value attached to the option just read (`-eNAME=VALUE`, - /// `--env=NAME=VALUE`). - attached: Option<&'a str>, - /// Whether the current group of short options starts with `+`. - plus_group: bool, -} - -impl<'a> Getopt<'a> { - fn new(args: &'a [String], owner: usize, start: usize, grammar: &'a Grammar) -> Self { - Self { - args, - owner, - grammar, - next: start, - letter: None, - done: false, - pending: Vec::new(), - attached: None, - plus_group: false, - } - } - - /// The value attached to the option just read, without the option. - fn attached(&self) -> Option<&'a str> { - self.attached - } - - /// Whether the short option just read was in a group starting with `+`. - fn in_plus_group(&self) -> bool { - self.plus_group - } - - /// Treat every remaining argument as an operand. - fn end_options(&mut self) { - self.done = true; - } - - /// The next whole argument as the value of the option just read, unless - /// that option sits inside a group of short options. - fn take_value(&mut self, a: &mut ArgvAnalysis, role: Role) -> Option { - if self.letter.is_some() || self.next >= self.args.len() { - return None; - } - let index = self.next; - a.set(index, value_role(role), self.owner); - a.mark_option_value(index); - self.next += 1; - Some(index) - } - - fn peek(&self) -> Option<&'a str> { - if self.letter.is_some() { - return None; - } - self.args.get(self.next).map(String::as_str) - } - - fn unknown(&mut self, a: &mut ArgvAnalysis, from: usize) -> Event<'a> { - a.rest(from, Role::Unknown, self.owner); - self.next = self.args.len(); - self.letter = None; - self.done = true; - self.pending.clear(); - Event::Unknown - } - - /// Move past the group of short options just read, then give the - /// letters that wait for a value the arguments after the group. - fn end_group(&mut self, a: &mut ArgvAnalysis) { - self.letter = None; - self.next += 1; - for role in std::mem::take(&mut self.pending) { - self.take_value(a, role); - } - } - - /// Go on to the letter at byte offset `at` of the current group, or - /// past the group when it ends there. - fn continue_group(&mut self, a: &mut ArgvAnalysis, at: usize) { - if at >= self.args[self.next].len() || !self.grammar.cluster { - self.end_group(a); - } else { - self.letter = Some(at); - } - } - - fn next(&mut self, a: &mut ArgvAnalysis) -> Option> { - self.attached = None; - if self.grammar.plus - && let Some(slot) = a.plus_options.get_mut(self.owner) - { - *slot = true; - } - if let Some(offset) = self.letter { - return Some(self.short(a, offset)); - } - if !self.done && self.grammar.plus && !self.grammar.plus_ends_options { - while self.args.get(self.next).is_some_and(|arg| arg == "+") { - a.set(self.next, Role::Own, self.owner); - self.next += 1; - } - } - let index = self.next; - let arg = self.args.get(index)?.as_str(); - if self.done { - self.next += 1; - return Some(Event::Operand(index)); - } - let lone_plus = self.grammar.plus && arg == "+"; - if arg == "--" || lone_plus || (self.grammar.dash_ends_options && arg == "-") { - a.set(index, Role::Own, self.owner); - self.next += 1; - self.done = true; - return Some(Event::End(index)); - } - if let Some(body) = arg.strip_prefix("--") { - return Some(self.long(a, index, body)); - } - let dash = arg.starts_with('-') || (self.grammar.plus && arg.starts_with('+')); - if dash && arg.len() > 1 { - a.set(index, Role::Own, self.owner); - self.plus_group = arg.starts_with('+'); - if !self.grammar.cluster && arg.len() > 2 { - return Some(self.whole(a, index, arg)); - } - return Some(self.short(a, 1)); - } - self.next += 1; - if !self.grammar.permute { - self.done = true; - } - Some(Event::Operand(index)) - } - - fn short(&mut self, a: &mut ArgvAnalysis, offset: usize) -> Event<'a> { - let index = self.next; - let arg = self.args[index].as_str(); - let Some(letter) = arg[offset..].chars().next() else { - self.end_group(a); - return match self.next(a) { - Some(event) => event, - None => Event::Operand(self.args.len()), - }; - }; - let after = offset + letter.len_utf8(); - let rest = &arg[after..]; - let name = Name::Short(letter); - match (self.grammar.short)(letter) { - None => self.unknown(a, index), - Some(Arity::Flag) => { - self.continue_group(a, after); - Event::Option { name, value: None } - } - Some(Arity::Value(role)) if self.grammar.value_from_next_arg => { - self.pending.push(role); - self.continue_group(a, after); - Event::Option { name, value: None } - } - Some(Arity::AttachedDigits { hex }) => { - let digits = if hex && rest.starts_with('x') { - rest.len() - } else { - rest.bytes() - .take_while(|b| (b'0'..=b'7').contains(b)) - .count() - }; - self.continue_group(a, after + digits); - Event::Option { name, value: None } - } - Some(Arity::Value(role) | Arity::Optional(role)) if !rest.is_empty() => { - a.set(index, value_role(role), self.owner); - self.end_group(a); - self.attached = Some(rest); - Event::Option { - name, - value: Some(index), - } - } - Some(Arity::Value(role)) => { - self.end_group(a); - let skip = self.grammar.value_skips_options - && self - .args - .get(self.next) - .is_some_and(|next| next.starts_with(['-', '+'])); - let value = if skip { None } else { self.take_value(a, role) }; - Event::Option { name, value } - } - Some(Arity::Optional(_)) => { - self.end_group(a); - Event::Option { name, value: None } - } - Some(Arity::Two(_)) if !rest.is_empty() => self.unknown(a, index), - Some(Arity::Two(role)) => { - self.end_group(a); - let value = self.take_value(a, role); - self.take_value(a, role); - Event::Option { name, value } - } - } - } - - fn whole(&mut self, a: &mut ArgvAnalysis, index: usize, arg: &'a str) -> Event<'a> { - let name = Name::Long(arg); - self.next += 1; - match (self.grammar.whole)(arg) { - Some(Arity::Flag) => Event::Option { name, value: None }, - Some(Arity::Value(role)) => { - let value = self.take_value(a, role); - Event::Option { name, value } - } - Some(Arity::Two(role)) => { - let value = self.take_value(a, role); - self.take_value(a, role); - Event::Option { name, value } - } - Some(Arity::Optional(_) | Arity::AttachedDigits { .. }) | None => { - self.unknown(a, index) - } - } - } - - fn long(&mut self, a: &mut ArgvAnalysis, index: usize, body: &'a str) -> Event<'a> { - let (name, attached) = match body.split_once('=') { - Some((name, value)) => (name, Some(value)), - None => (body, None), - }; - if name.is_empty() || name.contains("${") { - return self.unknown(a, index); - } - a.set(index, Role::Own, self.owner); - let event_name = Name::Long(name); - match ((self.grammar.long)(name), attached) { - (None, Some(_)) if self.grammar.attached_long_is_own => { - self.next += 1; - Event::Option { - name: event_name, - value: Some(index), - } - } - (None, _) - | (Some(Arity::Flag | Arity::Two(_)), Some(_)) - | (Some(Arity::AttachedDigits { .. }), _) => self.unknown(a, index), - (Some(Arity::Flag), None) | (Some(Arity::Optional(_)), None) => { - self.next += 1; - Event::Option { - name: event_name, - value: None, - } - } - (Some(Arity::Value(role) | Arity::Optional(role)), Some(value)) => { - a.set(index, value_role(role), self.owner); - self.next += 1; - self.attached = Some(value); - Event::Option { - name: event_name, - value: Some(index), - } - } - (Some(Arity::Value(role)), None) => { - self.next += 1; - let value = self.take_value(a, role); - Event::Option { - name: event_name, - value, - } - } - (Some(Arity::Two(role)), None) => { - self.next += 1; - let value = self.take_value(a, role); - self.take_value(a, role); - Event::Option { - name: event_name, - value, - } - } - } - } -} - -fn value_role(role: Role) -> Role { - match role { - Role::Data => Role::OptionValue, - other => other, - } -} - -fn flags(set: &str, c: char) -> Option { - set.contains(c).then_some(Arity::Flag) -} - -fn long_flags(set: &[&str], name: &str) -> Option { - set.contains(&name).then_some(Arity::Flag) -} - -// --------------------------------------------------------------------------- -// Shells -// --------------------------------------------------------------------------- - -/// bash, dash, and busybox ash: each `-o` or `-O` in a group takes the -/// next argument after the group, so `-euoc pipefail SCRIPT` runs SCRIPT. -const SH: Grammar = Grammar { - short: |c| match c { - 'o' | 'O' => Some(Arity::Value(Role::Own)), - c if c.is_ascii_alphanumeric() => Some(Arity::Flag), - _ => None, - }, - long: sh_long, - cluster: true, - whole: NO_WHOLE, - plus: true, - permute: false, - attached_long_is_own: false, - value_from_next_arg: true, - value_skips_options: false, - dash_ends_options: true, - plus_ends_options: false, -}; - -/// busybox ash ignores the long options it does not know, so none of them -/// takes a value. -const BUSYBOX_SH: Grammar = Grammar { - long: |_| Some(Arity::Flag), - ..SH -}; - -/// zsh and yash: `-o` takes the rest of its group (`-oerrexit`), or the -/// next argument when it ends the group, and a lone `+` ends the options. -const ZSH: Grammar = Grammar { - short: |c| match c { - 'o' => Some(Arity::Value(Role::Own)), - c if c.is_ascii_alphanumeric() => Some(Arity::Flag), - _ => None, - }, - value_from_next_arg: false, - plus_ends_options: true, - ..SH -}; - -/// The ksh family, which adds the `-R` and `-T` values and ends the -/// options at a lone `+`. -const KSH: Grammar = Grammar { - short: |c| match c { - 'o' | 'O' | 'R' | 'T' => Some(Arity::Value(Role::Own)), - c if c.is_ascii_alphanumeric() => Some(Arity::Flag), - _ => None, - }, - plus_ends_options: true, - ..SH -}; - -/// ksh93 and mksh read option values like zsh, but `-o` at the end of a -/// group does not take a next argument starting with `-` or `+` -/// (`ksh -o -c CMD` runs CMD). -const KSH_ATTACHED: Grammar = Grammar { - value_from_next_arg: false, - value_skips_options: true, - ..KSH -}; - -fn sh_long(name: &str) -> Option { - match name { - "rcfile" | "init-file" | "profile" | "emulate" => Some(Arity::Value(Role::Own)), - "login" | "noprofile" | "norc" | "posix" | "restricted" | "verbose" | "version" - | "help" | "debugger" | "dump-strings" | "dump-po-strings" | "noediting" - | "pretty-print" | "interactive" | "no-rcs" | "no-globalrcs" | "privileged" => { - Some(Arity::Flag) - } - _ => None, - } -} - -/// A POSIX-style shell: with `-c` the first operand is the script and the -/// second its `$0`; with `-s` the operands are positional parameters; -/// otherwise the first operand is the path of the script to run. -/// -/// Shells that share a name read option groups differently (`sh` may be -/// bash, dash, ash, mksh, or ksh), so the argv is read with each grammar -/// in `readings`, and every argument keeps the strictest role any of them -/// gives it. -fn parse_shell(args: &[String], at: usize, a: &mut ArgvAnalysis, readings: &[&Grammar]) -> Next { - let base = a.clone(); - let mut start = 0; - for (k, grammar) in readings.iter().enumerate() { - let mut reading = base.clone(); - start = start.max(read_shell(args, at, &mut reading, grammar)); - if k == 0 { - *a = reading; - } else { - a.merge(&reading, at + 1); - } - } - Next::Done(start) -} - -/// One reading of a shell's argv; returns where the arguments of the -/// script start. -fn read_shell(args: &[String], at: usize, a: &mut ArgvAnalysis, grammar: &Grammar) -> usize { - let mut g = Getopt::new(args, at, at + 1, grammar); - let (mut command, mut stdin) = (false, false); - let mut operands = Vec::new(); - while let Some(event) = g.next(a) { - match event { - Event::Option { - name: Name::Short('c'), - .. - } => command = true, - // `+s` turns reading the script from stdin off again in dash, - // zsh, and ksh. - Event::Option { - name: Name::Short('s'), - .. - } => stdin = !g.in_plus_group(), - Event::Option { .. } | Event::End(_) => {} - Event::Operand(i) if i < args.len() => operands.push(i), - Event::Operand(_) => {} - Event::Unknown => return args.len(), - } - } - for &i in &operands { - a.set(i, Role::Data, at); - } - let after = |k: usize| operands.get(k).map_or(args.len(), |&i| i + 1); - if command { - if let Some(&script) = operands.first() { - a.set(script, Role::Code, at); - } - after(1) - } else if stdin { - operands.first().copied().unwrap_or(args.len()) - } else { - if let Some(&script) = operands.first() { - a.set(script, Role::Code, at); - } - after(0) - } -} - -/// `cmd.exe`: everything after `/c`, `/k`, or `/r` is one command line it -/// parses itself. -fn parse_cmd(args: &[String], at: usize, a: &mut ArgvAnalysis) -> Next { - for i in at + 1..args.len() { - let arg = args[i].to_ascii_lowercase(); - let Some(switch) = arg.strip_prefix('/') else { - a.rest(i, Role::Unknown, at); - return Next::Done(args.len()); - }; - if matches!(switch, "c" | "k" | "r") { - a.set(i, Role::Own, at); - a.rest(i + 1, Role::Code, at); - return Next::Done(args.len()); - } - if switch.starts_with(['c', 'k', 'r']) { - a.rest(i, Role::Code, at); - return Next::Done(args.len()); - } - let known = matches!(switch, "s" | "q" | "d" | "a" | "u" | "x" | "y") - || ["e:", "f:", "v:", "t:"] - .iter() - .any(|prefix| switch.starts_with(prefix) && !has_result_ref(switch)); - if !known { - a.rest(i, Role::Unknown, at); - return Next::Done(args.len()); - } - a.set(i, Role::Own, at); - } - Next::Done(args.len()) -} - -/// The kinds of PowerShell parameters, ordered from least to most of what -/// follows them they turn into code. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum PsParam { - Flag, - Value, - File, - CommandWithArgs, - Command, -} - -const PS_PARAMS: &[(&str, &[&str], PsParam)] = &[ - ("command", &["c"], PsParam::Command), - ("encodedcommand", &["e", "ec", "enc"], PsParam::Command), - ("commandwithargs", &["cwa"], PsParam::CommandWithArgs), - ("file", &["f"], PsParam::File), - ("executionpolicy", &["ep", "ex"], PsParam::Value), - ("windowstyle", &["w"], PsParam::Value), - ("inputformat", &["inp", "if"], PsParam::Value), - ("outputformat", &["o", "of"], PsParam::Value), - ("version", &["v"], PsParam::Value), - ("configurationname", &["config"], PsParam::Value), - ("configurationfile", &[], PsParam::Value), - ("workingdirectory", &["wd"], PsParam::Value), - ("settingsfile", &["settings"], PsParam::Value), - ("custompipename", &[], PsParam::Value), - ("psconsolefile", &[], PsParam::Value), - ("encodedarguments", &["ea", "encodeda"], PsParam::Value), - ("noprofile", &["nop"], PsParam::Flag), - ("noninteractive", &["noni"], PsParam::Flag), - ("nologo", &["nol"], PsParam::Flag), - ("noexit", &["noe"], PsParam::Flag), - ("login", &["l"], PsParam::Flag), - ("interactive", &["i"], PsParam::Flag), - ("mta", &[], PsParam::Flag), - ("sta", &[], PsParam::Flag), - ("noprofileloadtime", &[], PsParam::Flag), - ("sshservermode", &["sshs"], PsParam::Flag), - ("namedpipeservermode", &["nps"], PsParam::Flag), - ("servermode", &["s"], PsParam::Flag), - ("help", &["h", "?"], PsParam::Flag), -]; - -/// The parameter `arg` names, with a `:value` attached to it, `Some(None)` -/// for a parameter PowerShell does not have, or `None` for an operand. -/// PowerShell trims the argument, reads any dash (doubled or not) or `/` as -/// the start of a name, and accepts any unambiguous prefix of a name; an -/// ambiguous one counts as the candidate that turns the most into code. -fn ps_param(arg: &str) -> Option> { - let mut chars = arg.trim().chars(); - let (body, slash) = match chars.next()? { - '/' => (chars.as_str(), true), - dash if is_dash(dash) => { - let body = chars.as_str(); - (body.strip_prefix(dash).unwrap_or(body), false) - } - _ => return None, - }; - if body.is_empty() { - return None; - } - let (name, attached) = match body.split_once(':') { - Some((name, _)) => (name, true), - None => (body, false), - }; - if name.contains("${") { - return (!slash).then_some(None); - } - let name = name.to_ascii_lowercase(); - let param = PS_PARAMS - .iter() - .filter(|(full, aliases, _)| { - *full == name || aliases.contains(&name.as_str()) || full.starts_with(&name) - }) - .map(|(_, _, kind)| *kind) - .max() - .map(|kind| (kind, attached)); - // On Unix a leading `/` starts a path rather than a parameter. - if slash && param.is_none() { - return None; - } - Some(param) -} - -/// Windows PowerShell joins its operands into a command; `pwsh` runs the -/// first operand as a script file and binds the rest as its parameters. -/// A script of `-` reads commands from stdin, and the parameters after it -/// are still PowerShell's own. -fn parse_powershell(args: &[String], at: usize, a: &mut ArgvAnalysis, pwsh: bool) -> Next { - let n = args.len(); - let mut i = at + 1; - while i < n { - match ps_param(&args[i]) { - None => { - if pwsh && args[i] == "-" { - a.set(i, Role::Own, at); - i += 1; - continue; - } - if pwsh { - a.set(i, Role::Code, at); - a.rest(i + 1, Role::Data, at); - return Next::Done(i + 1); - } - a.rest(i, Role::Code, at); - return Next::Done(n); - } - Some(None) => { - a.rest(i, Role::Unknown, at); - return Next::Done(n); - } - Some(Some((kind, attached))) => { - a.set(i, Role::Own, at); - let value = if attached { i } else { i + 1 }; - match kind { - PsParam::Flag => i += 1, - PsParam::Value => { - a.set(value, Role::Own, at); - if !attached { - a.mark_option_value(value); - } - i = value + 1; - } - PsParam::File if !attached && args.get(value).is_some_and(|v| v == "-") => { - a.set(value, Role::Own, at); - i = value + 1; - } - PsParam::File | PsParam::CommandWithArgs => { - a.set(value, Role::Code, at); - a.rest(value + 1, Role::Data, at); - return Next::Done(value + 1); - } - PsParam::Command => { - a.rest(value, Role::Code, at); - return Next::Done(n); - } - } - } - } - } - Next::Done(n) -} - -// --------------------------------------------------------------------------- -// Interpreters -// --------------------------------------------------------------------------- - -struct Interpreter { - grammar: Grammar, - /// Options whose value is the program to run, so no operand is a script - /// (`python -c`, `perl -e`). Options that load code besides the script - /// (`lua -e`, `node -r`) take [`Role::Code`] values in the grammar but - /// are not listed here. - code: fn(&Name) -> bool, - /// After the code, every argument is the code's own (`python -c`). - code_ends_options: bool, -} - -const PYTHON: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'c' | 'm' | 'W' => Some(Arity::Value(Role::Code)), - 'X' | 'Q' => Some(Arity::Value(Role::Own)), - c => flags("bBdEhiIOqsSuvVxPR", c), - }, - long: |name| match name { - "check-hash-based-pycs" => Some(Arity::Value(Role::Own)), - name => long_flags( - &["help", "version", "help-env", "help-xoptions", "help-all"], - name, - ), - }, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("cm", &[]), - code_ends_options: true, -}; - -const PERL: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'e' | 'E' | 'I' | 'm' | 'M' => Some(Arity::Value(Role::Code)), - 'd' | 'F' => Some(Arity::Optional(Role::Code)), - '0' => Some(Arity::AttachedDigits { hex: true }), - 'l' => Some(Arity::AttachedDigits { hex: false }), - 'C' | 'D' | 'i' | 'x' | 'V' => Some(Arity::Optional(Role::Own)), - c => flags("acfhnpsStTuUvwWX", c), - }, - long: NO_LONG, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("eE", &[]), - code_ends_options: false, -}; - -const RUBY: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'e' | 'r' | 'I' => Some(Arity::Value(Role::Code)), - 'C' | 'E' | 'F' | 'X' => Some(Arity::Value(Role::Own)), - '0' | 'i' | 'W' | 'x' | 'K' | 'T' => Some(Arity::Optional(Role::Own)), - c => flags("acdlnpsSvwyhU", c), - }, - long: |name| match name { - "enable" | "disable" | "encoding" | "external-encoding" | "internal-encoding" - | "dump" | "backtrace-limit" | "crash-report" | "parser" => { - Some(Arity::Value(Role::Own)) - } - name => long_flags( - &[ - "version", - "verbose", - "help", - "copyright", - "yydebug", - "jit", - "yjit", - "mjit", - ], - name, - ), - }, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: true, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("e", &[]), - code_ends_options: false, -}; - -const LUA: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'e' | 'l' | 'j' => Some(Arity::Value(Role::Code)), - 'O' => Some(Arity::Optional(Role::Own)), - c => flags("ivEW", c), - }, - long: NO_LONG, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |_| false, - code_ends_options: false, -}; - -const PHP: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'r' | 'f' | 'B' | 'R' | 'F' | 'E' | 'z' | 'd' | 'c' => Some(Arity::Value(Role::Code)), - 'b' | 'S' | 't' => Some(Arity::Value(Role::Own)), - c => flags("aCnehHilmsvw", c), - }, - long: |name| match name { - "php-ini" | "define" | "run" | "process-begin" | "process-code" | "process-file" - | "process-end" | "file" | "zend-extension" => Some(Arity::Value(Role::Code)), - "server" | "docroot" | "rfunction" | "rf" | "rclass" | "rc" | "rextension" | "re" - | "rzendextension" | "rz" | "rextinfo" | "ri" => Some(Arity::Value(Role::Own)), - name => long_flags( - &[ - "interactive", - "no-php-ini", - "profile-info", - "info", - "syntax-check", - "modules", - "hide-args", - "strip", - "version", - "help", - "ini", - ], - name, - ), - }, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| { - name.is( - "rfBRFE", - &[ - "run", - "process-begin", - "process-code", - "process-file", - "process-end", - "file", - ], - ) - }, - code_ends_options: false, -}; - -const OSASCRIPT: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'e' => Some(Arity::Value(Role::Code)), - 'l' | 's' => Some(Arity::Value(Role::Own)), - c => flags("i", c), - }, - long: NO_LONG, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("e", &[]), - code_ends_options: false, -}; - -const RSCRIPT: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'e' => Some(Arity::Value(Role::Code)), - _ => None, - }, - long: |name| match name { - "file" | "default-packages" => Some(Arity::Optional(Role::Code)), - name => long_flags( - &[ - "verbose", - "vanilla", - "no-environ", - "no-site-file", - "no-init-file", - "no-restore", - "no-restore-data", - "no-restore-history", - "no-save", - "save", - "no-echo", - "quiet", - "silent", - "slave", - "restore", - "version", - "help", - "interactive", - "no-readline", - ], - name, - ), - }, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: true, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("e", &["file"]), - code_ends_options: false, -}; - -const NODE: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'e' | 'p' | 'r' => Some(Arity::Value(Role::Code)), - 'C' => Some(Arity::Value(Role::Own)), - c => flags("civh", c), - }, - long: |name| match name { - "eval" | "print" | "require" | "import" | "loader" | "experimental-loader" => { - Some(Arity::Value(Role::Code)) - } - "env-file" - | "env-file-if-exists" - | "conditions" - | "input-type" - | "title" - | "inspect-port" - | "icu-data-dir" - | "openssl-config" - | "redirect-warnings" - | "secure-heap" - | "secure-heap-min" - | "test-reporter" - | "test-reporter-destination" - | "test-name-pattern" - | "test-concurrency" - | "watch-path" - | "disable-warning" - | "diagnostic-dir" - | "dns-result-order" - | "heapsnapshot-signal" - | "report-signal" - | "report-dir" - | "report-directory" - | "report-filename" - | "tls-cipher-list" - | "tls-keylog" - | "unhandled-rejections" - | "max-http-header-size" - | "localstorage-file" - | "experimental-default-type" - | "stack-trace-limit" => Some(Arity::Value(Role::Own)), - "inspect" | "inspect-brk" | "inspect-wait" | "debug-port" => { - Some(Arity::Optional(Role::Own)) - } - name => long_flags( - &[ - "no-warnings", - "no-deprecation", - "trace-warnings", - "trace-deprecation", - "trace-uncaught", - "enable-source-maps", - "preserve-symlinks", - "preserve-symlinks-main", - "pending-deprecation", - "throw-deprecation", - "abort-on-uncaught-exception", - "expose-gc", - "frozen-intrinsics", - "no-addons", - "no-global-search-paths", - "experimental-vm-modules", - "experimental-modules", - "experimental-strip-types", - "experimental-detect-module", - "experimental-require-module", - "experimental-wasm-modules", - "experimental-json-modules", - "experimental-import-meta-resolve", - "experimental-permission", - "permission", - "allow-child-process", - "allow-worker", - "allow-addons", - "allow-wasi", - "check", - "interactive", - "test", - "watch", - "watch-preserve-output", - "zero-fill-buffers", - "jitless", - "insecure-http-parser", - "use-openssl-ca", - "use-bundled-ca", - "force-fips", - "enable-fips", - "v8-options", - "version", - "help", - "completion-bash", - ], - name, - ), - }, - cluster: false, - whole: |arg| match arg { - "-pe" | "-ep" => Some(Arity::Value(Role::Code)), - _ => None, - }, - plus: false, - permute: false, - attached_long_is_own: true, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("ep", &["eval", "print", "-pe", "-ep"]), - code_ends_options: false, -}; - -const EXPECT: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'c' | 'f' | 'b' => Some(Arity::Value(Role::Code)), - 'D' => Some(Arity::Value(Role::Own)), - c => flags("dinNv", c), - }, - long: NO_LONG, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("fb", &[]), - code_ends_options: false, -}; - -const FISH: Interpreter = Interpreter { - grammar: Grammar { - short: |c| match c { - 'c' | 'C' => Some(Arity::Value(Role::Code)), - 'd' | 'o' | 'f' | 'p' => Some(Arity::Value(Role::Own)), - c => flags("ilnNPvh", c), - }, - long: |name| match name { - "command" | "init-command" => Some(Arity::Value(Role::Code)), - "debug" | "debug-output" | "features" | "profile" | "profile-startup" => { - Some(Arity::Value(Role::Own)) - } - name => long_flags( - &[ - "interactive", - "login", - "no-execute", - "no-config", - "private", - "print-rusage-self", - "print-debug-categories", - "version", - "help", - ], - name, - ), - }, - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, - }, - code: |name| name.is("c", &["command"]), - code_ends_options: false, -}; - -/// `csh` and `tcsh`: every `-c` in a group takes the next argument after -/// the group as the command, whatever it starts with (`-cf CMD`, `-fcb -/// CMD`, `-c -f`). -const CSH: Grammar = Grammar { - short: |c| match c { - 'c' => Some(Arity::Value(Role::Code)), - c => flags("bdefFilmnqstvVxX", c), - }, - long: |name| long_flags(&["help", "version"], name), - cluster: true, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: true, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, -}; - -/// `csh` and `tcsh`: after the options, the operands are the `argv` of the -/// `-c` command (the last `-c` wins), or the script and its `argv`. `-b` -/// ends the options after its group, and `--` does not end them: BSD `csh` -/// reads it as an empty group. -fn parse_csh(args: &[String], at: usize, a: &mut ArgvAnalysis) -> Next { - let n = args.len(); - let mut g = Getopt::new(args, at, at + 1, &CSH); - let mut command = false; - while let Some(event) = g.next(a) { - match event { - Event::Option { name, .. } => { - command |= name == Name::Short('c'); - if name == Name::Short('b') { - g.end_options(); - } - } - Event::End(i) => g = Getopt::new(args, at, i + 1, &CSH), - Event::Operand(i) if i < n => { - if command { - a.rest(i, Role::Data, at); - return Next::Done(i); - } - a.set(i, Role::Code, at); - a.rest(i + 1, Role::Data, at); - return Next::Done(i + 1); - } - Event::Operand(_) => break, - Event::Unknown => return Next::Done(n), - } - } - Next::Done(n) -} - -/// An interpreter: after its options comes the code (from an option or as -/// the path of a script operand), then the arguments the code receives. -fn parse_interpreter( - args: &[String], - at: usize, - a: &mut ArgvAnalysis, - interp: &Interpreter, -) -> Next { - let n = args.len(); - let mut g = Getopt::new(args, at, at + 1, &interp.grammar); - let mut code_seen = false; - while let Some(event) = g.next(a) { - match event { - Event::Option { name, value } => { - if (interp.code)(&name) { - code_seen = true; - if interp.code_ends_options { - let next = value.map_or(n, |v| v + 1); - a.rest(next, Role::Data, at); - return Next::Done(next); - } - } - } - Event::Operand(i) if i < n => { - if code_seen { - a.rest(i, Role::Data, at); - return Next::Done(i); - } - a.set( - i, - if args[i] == "-" { - Role::Data - } else { - Role::Code - }, - at, - ); - a.rest(i + 1, Role::Data, at); - return Next::Done(i + 1); - } - Event::Operand(_) => break, - Event::End(i) => { - if code_seen { - a.rest(i + 1, Role::Data, at); - return Next::Done(i); - } - if i + 1 < n { - a.set(i + 1, Role::Code, at); - a.rest(i + 2, Role::Data, at); - return Next::Done(i + 2); - } - return Next::Done(n); - } - Event::Unknown => return Next::Done(n), - } - } - Next::Done(n) -} - -const TCLSH_OPTIONS: &[(&str, bool)] = &[("-encoding", true)]; -const WISH_OPTIONS: &[(&str, bool)] = &[ - ("-encoding", true), - ("-colormap", true), - ("-display", true), - ("-geometry", true), - ("-name", true), - ("-use", true), - ("-visual", true), - ("-sync", false), -]; - -/// `tclsh` and `wish`: single-dash options, then the script and its -/// arguments. -fn parse_tcl(args: &[String], at: usize, a: &mut ArgvAnalysis, options: &[(&str, bool)]) -> Next { - let n = args.len(); - let mut i = at + 1; - while i < n { - let arg = args[i].as_str(); - if arg == "--" { - a.set(i, Role::Own, at); - i += 1; - break; - } - if let Some((_, takes_value)) = options.iter().find(|(name, _)| *name == arg) { - a.set(i, Role::Own, at); - if *takes_value { - a.set(i + 1, Role::Own, at); - i += 1; - } - i += 1; - continue; - } - if arg.starts_with('-') { - a.rest(i, Role::Unknown, at); - return Next::Done(n); - } - break; - } - if i < n { - a.set(i, Role::Code, at); - a.rest(i + 1, Role::Data, at); - return Next::Done(i + 1); - } - Next::Done(n) -} - -const BUN: Grammar = Grammar { - short: |c| match c { - 'e' | 'p' | 'r' => Some(Arity::Value(Role::Code)), - 'c' | 'd' | 'l' => Some(Arity::Value(Role::Own)), - c => flags("bvh", c), - }, - long: |name| match name { - "eval" | "print" | "preload" => Some(Arity::Value(Role::Code)), - "cwd" | "env-file" | "config" | "tsconfig-override" | "define" | "loader" | "port" - | "origin" | "conditions" | "main-fields" | "extension-order" | "install" => { - Some(Arity::Value(Role::Own)) - } - "inspect" | "inspect-brk" | "inspect-wait" => Some(Arity::Optional(Role::Own)), - name => long_flags( - &[ - "watch", - "hot", - "smol", - "bun", - "silent", - "no-clear-screen", - "if-present", - "no-install", - "prefer-offline", - "prefer-latest", - "revision", - "version", - "help", - "no-macros", - "no-deprecation", - "throw-deprecation", - ], - name, - ), - }, - cluster: false, - whole: NO_WHOLE, - plus: false, - permute: false, - attached_long_is_own: false, - value_from_next_arg: false, - value_skips_options: false, - dash_ends_options: false, - plus_ends_options: false, -}; - -const BUN_SUBCOMMANDS: &[&str] = &[ - "test", - "install", - "i", - "add", - "a", - "remove", - "rm", - "update", - "link", - "unlink", - "pm", - "build", - "init", - "create", - "c", - "upgrade", - "outdated", - "publish", - "patch", - "patch-commit", - "audit", - "info", - "repl", - "why", - "completions", - "discord", - "help", - "exec", -]; - -/// `bun`: a script, `bun run