diff --git a/crates/bashkit/src/builtins/iconv.rs b/crates/bashkit/src/builtins/iconv.rs index d9b00dba3..492f1d8cd 100644 --- a/crates/bashkit/src/builtins/iconv.rs +++ b/crates/bashkit/src/builtins/iconv.rs @@ -1,11 +1,36 @@ //! iconv builtin - character encoding conversion (virtual) //! -//! Converts text between character encodings in a virtual environment. -//! Supports utf-8, ascii, latin1/iso-8859-1, utf-16. +//! Converts bytes between character encodings. Input and output are raw +//! bytes end to end: `-t latin1` writes Latin-1 bytes, `-t utf-16` writes +//! real UTF-16 code units. iconv is the step that turns non-UTF-8 files into +//! text the other builtins can read (L-STREAM-001), so it must never go +//! through a lossy UTF-8 string. +//! +//! Decisions: +//! - Conversion runs char by char (decode one char, encode it), so error +//! positions are byte offsets in the input, like GNU iconv. +//! - On a hard error the converted prefix is still written to stdout and the +//! exit status is 1 (GNU). With `-o FILE` nothing is written when +//! conversion stops on an error, so a wrong `-f` guess never damages FILE, +//! even when FILE is also the input. `-c` is the exception by request: it +//! asks to drop what does not convert, so `-c -o FILE` writes the rest +//! (that is how a damaged export is saved) and exits 1. +//! - `-s` suppresses nothing: glibc's `-s` keeps conversion errors on +//! stderr, and bashkit iconv prints no other warnings. +//! - Empty suffixes (`UTF-8//`, `ASCII//,,`) are accepted, as glibc does. +//! - `-c` / `//IGNORE` drop invalid input and characters the target cannot +//! hold, write the rest, and exit 1 (POSIX, GNU libiconv). glibc 2.39 exits +//! 0 when only unconvertible characters were dropped; we follow POSIX. +//! - `UTF-16` output starts with a BOM and is little-endian; `UTF-16LE` and +//! `UTF-16BE` write no BOM. `UTF-16` input honours a BOM and defaults to +//! little-endian without one (glibc on little-endian hosts). +//! - Output growth (up to 2x for UTF-16) is charged to the shared execution +//! budget (TM-DOS-103 pattern used by `od`). //! //! Usage: //! iconv -f UTF-8 -t LATIN1 file.txt -//! echo "hello" | iconv -f UTF-8 -t ASCII +//! iconv -f LATIN1 -t UTF-8 -o file.txt file.txt +//! echo "hello" | iconv -f UTF-8 -t ASCII//TRANSLIT //! iconv -l use async_trait::async_trait; @@ -13,6 +38,7 @@ use async_trait::async_trait; use super::{Builtin, BuiltinHelper, Context, resolve_path}; use crate::error::Result; use crate::interpreter::ExecResult; +use crate::limits::{BudgetedBytes, ExecutionBudget}; /// iconv builtin - character encoding conversion. pub struct Iconv; @@ -21,78 +47,119 @@ impl BuiltinHelper for Iconv { const NAME: &'static str = "iconv"; } -/// Parse an encoding spec like "ascii//translit" into (encoding, translit). -fn parse_encoding_spec(spec: &str) -> (Option<&'static str>, bool) { - if let Some(pos) = spec.find("//") { - let suffix = &spec[pos + 2..]; - if suffix.eq_ignore_ascii_case("translit") { - (normalize_encoding(&spec[..pos]), true) - } else { - (None, false) - } - } else { - (normalize_encoding(spec), false) - } +#[derive(Clone, Copy, PartialEq, Eq)] +enum Charset { + Utf8, + Ascii, + Latin1, + /// UTF-16 with BOM: BOM-detected on input, BOM + little-endian on output. + Utf16, + Utf16Le, + Utf16Be, } -/// Normalize encoding name to canonical form. -fn normalize_encoding(name: &str) -> Option<&'static str> { - match name.to_ascii_lowercase().replace('-', "").as_str() { - "utf8" => Some("utf-8"), - "ascii" | "usascii" => Some("ascii"), - "latin1" | "iso88591" | "iso_88591" => Some("latin1"), - "utf16" | "utf16le" => Some("utf-16"), - "utf16be" => Some("utf-16be"), - _ => None, - } +/// Look up a charset name, ignoring case, `-` and `_`. +fn lookup_charset(name: &str) -> Option { + let key: String = name + .chars() + .filter(|c| !matches!(c, '-' | '_')) + .collect::() + .to_ascii_lowercase(); + Some(match key.as_str() { + "utf8" => Charset::Utf8, + "ascii" | "usascii" | "ansix3.41968" | "646" => Charset::Ascii, + "latin1" | "iso88591" | "iso885911987" | "l1" | "cp819" | "ibm819" => Charset::Latin1, + "utf16" => Charset::Utf16, + "utf16le" => Charset::Utf16Le, + "utf16be" => Charset::Utf16Be, + _ => return None, + }) } -/// Transliterate non-ASCII characters to their closest ASCII equivalents. -fn transliterate_to_ascii(input: &str) -> String { - let mut result = String::with_capacity(input.len()); - for ch in input.chars() { - if ch.is_ascii() { - result.push(ch); - } else { - result.push(match ch { - 'á' | 'à' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => 'a', - 'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e', - 'í' | 'ì' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' => 'i', - 'ó' | 'ò' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o', - 'ú' | 'ù' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u', - 'ý' | 'ÿ' | 'ŷ' => 'y', - 'ñ' | 'ń' | 'ņ' | 'ň' => 'n', - 'ç' | 'ć' | 'č' | 'ĉ' | 'ċ' => 'c', - 'ß' => 's', - 'æ' => 'a', - 'œ' => 'o', - 'ð' => 'd', - 'þ' => 't', - 'ł' => 'l', - 'đ' => 'd', - 'ğ' => 'g', - 'ş' | 'š' | 'ś' | 'ŝ' => 's', - 'ž' | 'ź' | 'ż' => 'z', - 'ř' => 'r', - 'ť' | 'ţ' => 't', - 'Á' | 'À' | 'Â' | 'Ã' | 'Ä' | 'Å' => 'A', - 'É' | 'È' | 'Ê' | 'Ë' => 'E', - 'Í' | 'Ì' | 'Î' | 'Ï' => 'I', - 'Ó' | 'Ò' | 'Ô' | 'Õ' | 'Ö' | 'Ø' => 'O', - 'Ú' | 'Ù' | 'Û' | 'Ü' => 'U', - 'Ý' => 'Y', - 'Ñ' => 'N', - 'Ç' => 'C', - 'Š' => 'S', - 'Ž' => 'Z', - 'Ř' => 'R', - 'Ť' => 'T', - 'Ď' => 'D', - _ => '?', - }); +/// A parsed encoding argument like `ASCII//TRANSLIT//IGNORE`. +struct EncodingSpec { + charset: Charset, + translit: bool, + ignore: bool, +} + +/// Parse `NAME[//SUFFIX...]`. Suffixes may also be comma-separated +/// (`//TRANSLIT,IGNORE`), as glibc accepts. +fn parse_encoding_spec(spec: &str) -> Option { + let mut parts = spec.split("//"); + let charset = lookup_charset(parts.next()?)?; + let mut out = EncodingSpec { + charset, + translit: false, + ignore: false, + }; + for part in parts { + for suffix in part.split(',') { + if suffix.eq_ignore_ascii_case("translit") { + out.translit = true; + } else if suffix.eq_ignore_ascii_case("ignore") { + out.ignore = true; + } else if !suffix.is_empty() { + return None; + } } } - result + Some(out) +} + +/// Closest ASCII spelling for a character, used by `//TRANSLIT`. +fn transliterate(ch: char) -> Option<&'static str> { + Some(match ch { + 'á' | 'à' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => "a", + 'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e", + 'í' | 'ì' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' => "i", + 'ó' | 'ò' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => "o", + 'ú' | 'ù' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => "u", + 'ý' | 'ÿ' | 'ŷ' => "y", + 'ñ' | 'ń' | 'ņ' | 'ň' => "n", + 'ç' | 'ć' | 'č' | 'ĉ' | 'ċ' => "c", + 'ß' => "ss", + 'æ' => "ae", + 'œ' => "oe", + 'ð' | 'đ' | 'ď' => "d", + 'þ' => "th", + 'ł' | 'ľ' | 'ĺ' => "l", + 'ğ' => "g", + 'ş' | 'š' | 'ś' | 'ŝ' => "s", + 'ž' | 'ź' | 'ż' => "z", + 'ř' | 'ŕ' => "r", + 'ť' | 'ţ' => "t", + 'Á' | 'À' | 'Â' | 'Ã' | 'Ä' | 'Å' | 'Ā' | 'Ă' | 'Ą' => "A", + 'É' | 'È' | 'Ê' | 'Ë' | 'Ē' | 'Ė' | 'Ę' | 'Ě' => "E", + 'Í' | 'Ì' | 'Î' | 'Ï' | 'Ī' | 'Į' => "I", + 'Ó' | 'Ò' | 'Ô' | 'Õ' | 'Ö' | 'Ø' | 'Ō' | 'Ő' => "O", + 'Ú' | 'Ù' | 'Û' | 'Ü' | 'Ū' | 'Ů' | 'Ű' | 'Ų' => "U", + 'Ý' | 'Ÿ' => "Y", + 'Ñ' | 'Ń' | 'Ň' => "N", + 'Ç' | 'Ć' | 'Č' => "C", + 'Æ' => "AE", + 'Œ' => "OE", + 'Ð' | 'Đ' | 'Ď' => "D", + 'Þ' => "TH", + 'Ł' | 'Ľ' | 'Ĺ' => "L", + 'Ğ' => "G", + 'Ş' | 'Š' | 'Ś' => "S", + 'Ž' | 'Ź' | 'Ż' => "Z", + 'Ř' | 'Ŕ' => "R", + 'Ť' | 'Ţ' => "T", + '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{2032}' => "'", + '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{2033}' => "\"", + '\u{2013}' | '\u{2014}' | '\u{2212}' => "-", + '\u{2026}' => "...", + '\u{00A0}' => " ", + '\u{20AC}' => "EUR", + '\u{00A9}' => "(C)", + '\u{00AE}' => "(R)", + '\u{2122}' => "(TM)", + '\u{00AB}' => "<<", + '\u{00BB}' => ">>", + _ => return None, + }) } const SUPPORTED_ENCODINGS: &[&str] = &[ @@ -101,182 +168,305 @@ const SUPPORTED_ENCODINGS: &[&str] = &[ "LATIN1", "UTF-16", "UTF-16BE", + "UTF-16LE", "UTF-8", ]; -/// Encode bytes from UTF-8 string into target encoding. -/// When `transliterate` is true, non-ASCII characters are replaced with -/// ASCII equivalents before encoding (supports `//translit` mode). -fn encode_to( - input: &str, - encoding: &str, - transliterate: bool, -) -> std::result::Result, String> { - let text = if transliterate { - transliterate_to_ascii(input) - } else { - input.to_string() - }; - match encoding { - "utf-8" => Ok(text.as_bytes().to_vec()), - "ascii" => { - for (i, b) in text.bytes().enumerate() { - if b > 127 { - return Err(format!( - "iconv: cannot convert character at byte {i} to ASCII\n" - )); +/// One step of decoding. +enum Decoded { + Char(char), + /// Invalid sequence; the returned length says how many bytes to skip. + Invalid, + /// Truncated sequence at the end of input. + Incomplete, +} + +/// Decode the char at `input[pos..]`, returning it and the bytes consumed. +fn decode_one(input: &[u8], pos: usize, charset: Charset, big_endian: bool) -> (Decoded, usize) { + let rest = &input[pos..]; + match charset { + Charset::Utf8 => { + let b = rest[0]; + if b < 0x80 { + return (Decoded::Char(b as char), 1); + } + let chunk = &rest[..rest.len().min(4)]; + match std::str::from_utf8(chunk) { + Ok(s) => first_char(s), + Err(e) if e.valid_up_to() > 0 => { + // valid_up_to() is a char boundary, so this cannot fail. + first_char(std::str::from_utf8(&chunk[..e.valid_up_to()]).unwrap_or("\0")) } + Err(e) => match e.error_len() { + Some(n) => (Decoded::Invalid, n), + None => (Decoded::Incomplete, rest.len()), + }, } - Ok(text.as_bytes().to_vec()) } - "latin1" => { - let mut out = Vec::with_capacity(text.len()); - for ch in text.chars() { - let cp = ch as u32; - if cp > 255 { - return Err(format!("iconv: cannot convert U+{cp:04X} to LATIN1\n")); - } - out.push(cp as u8); + Charset::Ascii => { + let b = rest[0]; + if b < 0x80 { + (Decoded::Char(b as char), 1) + } else { + (Decoded::Invalid, 1) } - Ok(out) } - "utf-16" => { - let mut out = Vec::new(); - // BOM little-endian - out.extend_from_slice(&[0xFF, 0xFE]); - for ch in text.chars() { - let mut buf = [0u16; 2]; - let encoded = ch.encode_utf16(&mut buf); - for u in encoded { - out.extend_from_slice(&u.to_le_bytes()); - } + Charset::Latin1 => (Decoded::Char(rest[0] as char), 1), + Charset::Utf16 | Charset::Utf16Le | Charset::Utf16Be => { + let unit = |i: usize| -> Option { + let b = rest.get(i..i + 2)?; + Some(if big_endian { + u16::from_be_bytes([b[0], b[1]]) + } else { + u16::from_le_bytes([b[0], b[1]]) + }) + }; + let Some(first) = unit(0) else { + return (Decoded::Incomplete, rest.len()); + }; + match first { + 0xD800..=0xDBFF => match unit(2) { + None => (Decoded::Incomplete, rest.len()), + Some(second @ 0xDC00..=0xDFFF) => { + let cp = 0x10000 + + ((u32::from(first) - 0xD800) << 10) + + (u32::from(second) - 0xDC00); + match char::from_u32(cp) { + Some(c) => (Decoded::Char(c), 4), + None => (Decoded::Invalid, 2), + } + } + Some(_) => (Decoded::Invalid, 2), + }, + 0xDC00..=0xDFFF => (Decoded::Invalid, 2), + _ => match char::from_u32(u32::from(first)) { + Some(c) => (Decoded::Char(c), 2), + None => (Decoded::Invalid, 2), + }, } - Ok(out) } - "utf-16be" => { - let mut out = Vec::new(); - for ch in text.chars() { - let mut buf = [0u16; 2]; - let encoded = ch.encode_utf16(&mut buf); - for u in encoded { - out.extend_from_slice(&u.to_be_bytes()); - } + } +} + +fn first_char(s: &str) -> (Decoded, usize) { + match s.chars().next() { + Some(c) => (Decoded::Char(c), c.len_utf8()), + None => (Decoded::Invalid, 1), + } +} + +/// Encode one char. Returns false when the target cannot hold it. +fn encode_one( + ch: char, + charset: Charset, + out: &mut BudgetedBytes, +) -> std::result::Result { + let mut buf = [0u8; 4]; + match charset { + Charset::Utf8 => out.try_extend_from_slice(ch.encode_utf8(&mut buf).as_bytes())?, + Charset::Ascii if ch.is_ascii() => out.try_push(ch as u8)?, + Charset::Latin1 if (ch as u32) < 0x100 => out.try_push(ch as u32 as u8)?, + Charset::Ascii | Charset::Latin1 => return Ok(false), + Charset::Utf16 | Charset::Utf16Le | Charset::Utf16Be => { + let mut units = [0u16; 2]; + for u in ch.encode_utf16(&mut units) { + let bytes = if charset == Charset::Utf16Be { + u.to_be_bytes() + } else { + u.to_le_bytes() + }; + out.try_extend_from_slice(&bytes)?; } - Ok(out) } - _ => Err(format!("iconv: unsupported target encoding '{encoding}'\n")), } + Ok(true) } -/// Decode bytes from source encoding into UTF-8 string. -fn decode_from(input: &[u8], encoding: &str) -> std::result::Result { - match encoding { - "utf-8" => String::from_utf8(input.to_vec()) - .map_err(|e| format!("iconv: invalid UTF-8 input: {e}\n")), - "ascii" => { - for (i, &b) in input.iter().enumerate() { - if b > 127 { - return Err(format!( - "iconv: invalid ASCII byte 0x{b:02X} at position {i}\n" - )); - } +/// Why a conversion stopped early. +enum ConvertError { + Illegal(usize), + Incomplete, +} + +impl ConvertError { + fn message(&self) -> String { + match self { + Self::Illegal(pos) => format!("iconv: illegal input sequence at position {pos}\n"), + Self::Incomplete => { + "iconv: incomplete character or shift sequence at end of buffer\n".to_string() } - // ASCII is a subset of UTF-8 - Ok(String::from_utf8(input.to_vec()).unwrap_or_default()) } - "latin1" => { - // Each byte maps directly to a Unicode codepoint - Ok(input.iter().map(|&b| b as char).collect()) + } +} + +struct Converter { + from: Charset, + to: Charset, + translit: bool, + /// `-c` or `//IGNORE`: drop what cannot be converted. + skip: bool, + /// Set when `skip` dropped anything (exit status 1). + skipped: bool, + bom_written: bool, +} + +impl Converter { + /// Convert one input file, appending to `out`. + fn convert( + &mut self, + input: &[u8], + out: &mut BudgetedBytes, + budget: Option<&ExecutionBudget>, + ) -> Result> { + if self.to == Charset::Utf16 && !self.bom_written { + out.try_extend_from_slice(&[0xFF, 0xFE])?; + self.bom_written = true; } - "utf-16" => { - if input.len() < 2 { - return Err("iconv: UTF-16 input too short\n".to_string()); - } - // Check BOM - let (data, big_endian) = if input[0] == 0xFF && input[1] == 0xFE { - (&input[2..], false) - } else if input[0] == 0xFE && input[1] == 0xFF { - (&input[2..], true) - } else { - // Default to little-endian (no BOM) - (input, false) - }; - if data.len() % 2 != 0 { - return Err("iconv: UTF-16 input has odd byte count\n".to_string()); + let mut pos = 0; + let mut big_endian = self.from == Charset::Utf16Be; + if self.from == Charset::Utf16 && input.len() >= 2 { + match (input[0], input[1]) { + (0xFF, 0xFE) => pos = 2, + (0xFE, 0xFF) => { + pos = 2; + big_endian = true; + } + _ => {} } - let units: Vec = data - .as_chunks::<2>() - .0 - .iter() - .map(|c| { - if big_endian { - u16::from_be_bytes([c[0], c[1]]) - } else { - u16::from_le_bytes([c[0], c[1]]) + } + if let Some(budget) = budget { + budget.consume_work(input.len() as u64)?; + } + while pos < input.len() { + let (decoded, len) = decode_one(input, pos, self.from, big_endian); + match decoded { + Decoded::Char(ch) => { + if !self.emit(ch, out)? { + if self.skip { + self.skipped = true; + } else { + return Ok(Err(ConvertError::Illegal(pos))); + } } - }) - .collect(); - String::from_utf16(&units).map_err(|e| format!("iconv: invalid UTF-16 input: {e}\n")) + } + Decoded::Invalid if self.skip => self.skipped = true, + Decoded::Invalid => return Ok(Err(ConvertError::Illegal(pos))), + // `-c` keeps what converted from a file cut mid-character. + Decoded::Incomplete if self.skip => self.skipped = true, + Decoded::Incomplete => return Ok(Err(ConvertError::Incomplete)), + } + pos += len; + } + Ok(Ok(())) + } + + /// Encode `ch`, transliterating when asked. False when it cannot be written. + fn emit( + &self, + ch: char, + out: &mut BudgetedBytes, + ) -> std::result::Result { + if encode_one(ch, self.to, out)? { + return Ok(true); } - "utf-16be" => { - if !input.len().is_multiple_of(2) { - return Err("iconv: UTF-16BE input has odd byte count\n".to_string()); + if !self.translit { + return Ok(false); + } + let mark = out.len(); + if let Some(rep) = transliterate(ch) { + let mut ok = true; + for c in rep.chars() { + ok &= encode_one(c, self.to, out)?; + } + if ok { + return Ok(true); } - let units: Vec = input - .as_chunks::<2>() - .0 - .iter() - .map(|c| u16::from_be_bytes([c[0], c[1]])) - .collect(); - String::from_utf16(&units).map_err(|e| format!("iconv: invalid UTF-16BE input: {e}\n")) + out.truncate(mark); } - _ => Err(format!("iconv: unsupported source encoding '{encoding}'\n")), + encode_one('?', self.to, out) } } +const USAGE: &str = "Usage: iconv [OPTION...] [FILE...]\nConvert encoding of given files from one encoding to another.\n\n -f, --from-code=NAME\tencoding of original text\n -t, --to-code=NAME\tencoding for output (suffixes //TRANSLIT, //IGNORE)\n -c\t\t\tomit invalid characters from output\n -o, --output=FILE\toutput file, not written if conversion stops on an error\n -s, --silent\t\tsuppress warnings\n -l, --list\t\tlist all known coded character sets\n --help\t\tdisplay this help and exit\n --version\t\toutput version information and exit\n"; + #[async_trait] impl Builtin for Iconv { async fn execute(&self, ctx: Context<'_>) -> Result { - if let Some(r) = Self::check_help( - ctx.args, - "Usage: iconv [OPTION]... [FILE]\nConvert text from one character encoding to another.\n\n -f ENCODING\tconvert characters from ENCODING\n -t ENCODING\tconvert characters to ENCODING (supports //TRANSLIT)\n -l, --list\tlist known coded character sets\n --help\t\tdisplay this help and exit\n --version\toutput version information and exit\n", - Some("iconv (bashkit) 0.1"), - ) { + if let Some(r) = Self::check_help(ctx.args, USAGE, Some("iconv (bashkit) 0.2")) { return Ok(r); } let mut from_enc: Option = None; let mut to_enc: Option = None; - let mut file_arg: Option = None; + let mut output: Option = None; + let mut files: Vec = Vec::new(); let mut list = false; + let mut omit_invalid = false; + let args = ctx.args; let mut i = 0; - while i < ctx.args.len() { - match ctx.args[i].as_str() { - "-l" | "--list" => { - list = true; - } - "-f" => { - i += 1; - if i >= ctx.args.len() { - return Ok(Self::err("option '-f' requires an argument", 1)); - } - from_enc = Some(ctx.args[i].clone()); - } - "-t" => { - i += 1; - if i >= ctx.args.len() { - return Ok(Self::err("option '-t' requires an argument", 1)); + let mut options_done = false; + while i < args.len() { + let arg = args[i].as_str(); + i += 1; + if options_done || arg == "-" || !arg.starts_with('-') { + files.push(arg.to_string()); + continue; + } + // Options that take a value: -f X, -fX, --from-code=X, --from-code X. + let valued = [ + ("-f", "--from-code"), + ("-t", "--to-code"), + ("-o", "--output"), + ]; + let mut matched = None; + for (idx, (short, long)) in valued.iter().enumerate() { + let value = if arg == *short || arg == *long { + match args.get(i) { + Some(v) => { + i += 1; + Some(v.clone()) + } + None => { + return Ok(Self::err( + format!("option '{arg}' requires an argument"), + 1, + )); + } } - to_enc = Some(ctx.args[i].clone()); + } else if let Some(v) = arg.strip_prefix(&format!("{long}=")) { + Some(v.to_string()) + } else if arg.len() > 2 && arg.starts_with(short) && !arg.starts_with("--") { + Some(arg[2..].to_string()) + } else { + None + }; + if let Some(v) = value { + matched = Some((idx, v)); + break; } - arg if arg.starts_with('-') => { - return Ok(Self::err(format!("unknown option '{arg}'"), 1)); + } + if let Some((idx, v)) = matched { + match idx { + 0 => from_enc = Some(v), + 1 => to_enc = Some(v), + _ => output = Some(v), } - _ => { - file_arg = Some(ctx.args[i].clone()); + continue; + } + match arg { + "--" => options_done = true, + "-l" | "--list" => list = true, + "-c" => omit_invalid = true, + "-s" | "--silent" => {} + _ if arg.len() > 1 + && !arg.starts_with("--") + && arg[1..].chars().all(|c| matches!(c, 'c' | 's' | 'l')) => + { + omit_invalid |= arg.contains('c'); + list |= arg.contains('l'); } + _ => return Ok(Self::err(format!("unknown option '{arg}'"), 1)), } - i += 1; } if list { @@ -289,63 +479,97 @@ impl Builtin for Iconv { } let from = match &from_enc { - Some(f) => match normalize_encoding(f) { - Some(e) => e, - None => return Ok(Self::err(format!("unsupported encoding '{}'", f), 1)), + Some(f) => match parse_encoding_spec(f) { + Some(spec) => spec.charset, + None => return Ok(Self::err(format!("unsupported encoding '{f}'"), 1)), }, None => return Ok(Self::err("missing source encoding (-f)", 1)), }; - - let (to, to_translit) = match &to_enc { + let to = match &to_enc { Some(t) => match parse_encoding_spec(t) { - (Some(e), translit) => (e, translit), - (None, _) => return Ok(Self::err(format!("unsupported encoding '{}'", t), 1)), + Some(spec) => spec, + None => return Ok(Self::err(format!("unsupported encoding '{t}'"), 1)), }, None => return Ok(Self::err("missing target encoding (-t)", 1)), }; - // Read input from file or stdin - let input_bytes: Vec = if let Some(ref file) = file_arg { - let path = resolve_path(ctx.cwd, file); - match ctx.fs.read_file(&path).await { - Ok(bytes) => bytes, - Err(e) => return Ok(Self::err_path(file, e.to_string(), 1)), + if files.is_empty() { + if ctx.stdin.is_none() { + return Ok(Self::err( + "no input (provide file argument or pipe stdin)", + 1, + )); } - } else if let Some(stdin) = ctx.stdin { - stdin.as_bytes().to_vec() - } else { - return Ok(Self::err( - "no input (provide file argument or pipe stdin)", - 1, - )); - }; + files.push("-".to_string()); + } - // Decode from source encoding to UTF-8 string - let text = match decode_from(&input_bytes, from) { - Ok(t) => t, - Err(e) => return Ok(ExecResult::err(e, 1)), + let budget = ctx + .execution_budget() + .map(|budget| { + budget + .try_with(Clone::clone) + .map_err(|_| crate::Error::Cancelled) + }) + .transpose()?; + let mut out = BudgetedBytes::new(budget.as_ref())?; + let mut converter = Converter { + from, + to: to.charset, + translit: to.translit, + skip: omit_invalid || to.ignore, + skipped: false, + bom_written: false, }; - // Encode from UTF-8 string to target encoding - let output_bytes = match encode_to(&text, to, to_translit) { - Ok(b) => b, - Err(e) => return Ok(ExecResult::err(e, 1)), - }; + let mut failure: Option = None; + for file in &files { + let input: Vec = if file == "-" { + ctx.stdin_bytes().unwrap_or_default().to_vec() + } else { + let path = resolve_path(ctx.cwd, file); + match ctx.fs.read_file(&path).await { + Ok(bytes) => bytes, + Err(e) => { + failure = Some(format!( + "iconv: {file}: {}\n", + crate::error::io_error_reason(&e) + )); + break; + } + } + }; + if let Err(e) = converter.convert(&input, &mut out, budget.as_ref())? { + failure = Some(e.message()); + break; + } + } - // For text-compatible encodings, output as string; otherwise raw bytes as lossy UTF-8 - let output = match to { - "utf-8" | "ascii" => String::from_utf8_lossy(&output_bytes).to_string(), - "latin1" => { - // Each Latin1 byte maps directly to a Unicode codepoint - output_bytes.iter().map(|&b| b as char).collect() + let (bytes, _lease) = out.into_parts(); + let exit_code = i32::from(failure.is_some() || converter.skipped); + + if let Some(target) = output { + // A conversion that stopped never replaces the file; `-c` drops + // were requested and still write. + if let Some(msg) = failure { + return Ok(ExecResult::err(msg, 1)); } - _ => { - // Binary output - present as lossy string (VFS limitation) - String::from_utf8_lossy(&output_bytes).to_string() + let path = resolve_path(ctx.cwd, &target); + if let Err(e) = ctx.fs.write_file(&path, &bytes).await { + return Ok(Self::err_path( + &target, + crate::error::io_error_reason(&e), + 1, + )); } - }; + return Ok(ExecResult::with_code(String::new(), exit_code)); + } - Ok(ExecResult::ok(output)) + let mut result = ExecResult::ok_bytes(bytes); + result.exit_code = exit_code; + if let Some(msg) = failure { + result.stderr = msg.into(); + } + Ok(result) } } @@ -353,25 +577,26 @@ impl Builtin for Iconv { mod tests { use super::*; use std::collections::HashMap; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; use std::sync::Arc; - use crate::fs::InMemoryFs; + use crate::fs::{FileSystem, InMemoryFs}; - async fn run(args: &[&str], stdin: Option<&str>, fs: Option>) -> ExecResult { + async fn run_bytes(args: &[&str], stdin: Option<&[u8]>, fs: Arc) -> ExecResult { let args: Vec = args.iter().map(|s| s.to_string()).collect(); let env = HashMap::new(); let mut variables = HashMap::new(); let mut cwd = PathBuf::from("/"); - let fs = fs.unwrap_or_else(|| Arc::new(InMemoryFs::new())); - let fs_dyn = fs as Arc; + let fs_dyn = fs as Arc; + let stdin: Option<&'static crate::StreamData> = + stdin.map(|b| &*Box::leak(Box::new(crate::StreamData::from(b.to_vec())))); let ctx = Context { args: &args, env: &env, variables: &mut variables, cwd: &mut cwd, fs: fs_dyn, - stdin: crate::builtins::test_stream_opt(stdin), + stdin, #[cfg(feature = "http_client")] http_client: None, #[cfg(feature = "git")] @@ -383,140 +608,435 @@ mod tests { Iconv.execute(ctx).await.unwrap() } + async fn run(args: &[&str], stdin: Option<&str>) -> ExecResult { + run_bytes(args, stdin.map(str::as_bytes), Arc::new(InMemoryFs::new())).await + } + + async fn fs_with(path: &str, bytes: &[u8]) -> Arc { + let fs = Arc::new(InMemoryFs::new()); + fs.write_file(Path::new(path), bytes).await.unwrap(); + fs + } + + // --- positive --- + #[tokio::test] - async fn test_list_encodings() { - let r = run(&["-l"], None, None).await; + async fn list_encodings() { + let r = run(&["-l"], None).await; assert_eq!(r.exit_code, 0); - assert!(r.stdout.contains("UTF-8")); - assert!(r.stdout.contains("ASCII")); - assert!(r.stdout.contains("LATIN1")); + for name in ["UTF-8", "ASCII", "LATIN1", "UTF-16LE", "UTF-16BE"] { + assert!(r.stdout.contains(name), "{name}"); + } } #[tokio::test] - async fn test_utf8_to_ascii() { - let r = run(&["-f", "UTF-8", "-t", "ASCII"], Some("hello"), None).await; + async fn utf8_to_ascii() { + let r = run(&["-f", "UTF-8", "-t", "ASCII"], Some("hello")).await; assert_eq!(r.exit_code, 0); assert_eq!(r.stdout, "hello"); } #[tokio::test] - async fn test_utf8_to_ascii_fails_on_nonascii() { - let r = run(&["-f", "UTF-8", "-t", "ASCII"], Some("caf\u{00e9}"), None).await; - assert_eq!(r.exit_code, 1); - assert!(r.stderr.contains("cannot convert")); + async fn utf8_to_latin1_writes_latin1_bytes() { + let r = run(&["-f", "UTF-8", "-t", "LATIN1"], Some("caf\u{e9}")).await; + assert_eq!(r.exit_code, 0); + assert_eq!(r.stdout.as_bytes(), b"caf\xe9"); } #[tokio::test] - async fn test_utf8_to_latin1() { - let r = run(&["-f", "UTF-8", "-t", "LATIN1"], Some("caf\u{00e9}"), None).await; + async fn repairs_double_encoded_utf8() { + // "Köln" encoded as UTF-8, then read as Latin-1 and encoded again. + let r = run(&["-f", "utf-8", "-t", "latin1"], Some("K\u{c3}\u{b6}ln")).await; assert_eq!(r.exit_code, 0); - // Latin1 byte 0xe9 maps to Unicode U+00E9 (é), so output is valid UTF-8 "café" - assert_eq!(r.stdout, "caf\u{00e9}"); + assert_eq!(r.stdout.as_bytes(), "Köln".as_bytes()); } #[tokio::test] - async fn test_latin1_to_utf8() { - let fs = Arc::new(InMemoryFs::new()); - // Write Latin1 bytes: "caf" + 0xe9 (e-acute) - let latin1_bytes = vec![b'c', b'a', b'f', 0xe9]; - let path = std::path::Path::new("/test.txt"); - let fs_dyn = fs.clone() as Arc; - fs_dyn.write_file(path, &latin1_bytes).await.unwrap(); - - let r = run( - &["-f", "LATIN1", "-t", "UTF-8", "/test.txt"], - None, - Some(fs), - ) - .await; + async fn latin1_file_to_utf8() { + let fs = fs_with("/test.txt", b"caf\xe9").await; + let r = run_bytes(&["-f", "LATIN1", "-t", "UTF-8", "/test.txt"], None, fs).await; assert_eq!(r.exit_code, 0); - assert_eq!(r.stdout, "caf\u{00e9}"); + assert_eq!(r.stdout, "caf\u{e9}"); } #[tokio::test] - async fn test_missing_from_encoding() { - let r = run(&["-t", "ASCII"], Some("hi"), None).await; - assert_eq!(r.exit_code, 1); - assert!(r.stderr.contains("missing source encoding")); + async fn latin1_stdin_bytes_to_utf8() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes(&["-f", "latin1", "-t", "utf-8"], Some(b"K\xf6ln"), fs).await; + assert_eq!(r.exit_code, 0); + assert_eq!(r.stdout, "Köln"); } #[tokio::test] - async fn test_missing_to_encoding() { - let r = run(&["-f", "ASCII"], Some("hi"), None).await; - assert_eq!(r.exit_code, 1); - assert!(r.stderr.contains("missing target encoding")); + async fn utf16_output_has_bom_and_le_units() { + let r = run(&["-f", "utf-8", "-t", "utf-16"], Some("aé€")).await; + assert_eq!(r.exit_code, 0); + assert_eq!( + r.stdout.as_bytes(), + &[0xFF, 0xFE, b'a', 0, 0xE9, 0, 0xAC, 0x20] + ); } #[tokio::test] - async fn test_unsupported_encoding() { - let r = run(&["-f", "EBCDIC", "-t", "UTF-8"], Some("hi"), None).await; - assert_eq!(r.exit_code, 1); - assert!(r.stderr.contains("unsupported encoding")); + async fn utf16le_and_be_output_have_no_bom() { + let r = run(&["-f", "utf-8", "-t", "UTF-16LE"], Some("ab")).await; + assert_eq!(r.stdout.as_bytes(), b"a\0b\0"); + let r = run(&["-f", "utf-8", "-t", "UTF-16BE"], Some("ab")).await; + assert_eq!(r.stdout.as_bytes(), b"\0a\0b"); } #[tokio::test] - async fn test_unsupported_target_encoding_suffix() { - for target in ["ASCII//BAD", "UTF-8//IGNORE", "ASCII//TRANSLIT//IGNORE"] { - let r = run(&["-f", "UTF-8", "-t", target], Some("hi"), None).await; - assert_eq!(r.exit_code, 1, "target should be rejected: {target}"); - assert!(r.stderr.contains("unsupported encoding")); - } + async fn utf16_surrogate_pair_round_trip() { + let r = run(&["-f", "utf-8", "-t", "utf-16be"], Some("😀")).await; + assert_eq!(r.stdout.as_bytes(), &[0xD8, 0x3D, 0xDE, 0x00]); + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes( + &["-f", "utf-16be", "-t", "utf-8"], + Some(&[0xD8, 0x3D, 0xDE, 0x00]), + fs, + ) + .await; + assert_eq!(r.exit_code, 0); + assert_eq!(r.stdout, "😀"); } #[tokio::test] - async fn test_no_input() { - let r = run(&["-f", "UTF-8", "-t", "ASCII"], None, None).await; - assert_eq!(r.exit_code, 1); - assert!(r.stderr.contains("no input")); + async fn utf16_input_honours_bom() { + let fs = Arc::new(InMemoryFs::new()); + let be = run_bytes( + &["-f", "utf-16", "-t", "utf-8"], + Some(b"\xFE\xFF\0h\0i"), + fs.clone(), + ) + .await; + assert_eq!(be.stdout, "hi"); + let le = run_bytes( + &["-f", "utf-16", "-t", "utf-8"], + Some(b"\xFF\xFEh\0i\0"), + fs.clone(), + ) + .await; + assert_eq!(le.stdout, "hi"); + let none = run_bytes(&["-f", "utf-16", "-t", "utf-8"], Some(b"h\0i\0"), fs).await; + assert_eq!(none.stdout, "hi"); } #[tokio::test] - async fn test_file_not_found() { - let r = run(&["-f", "UTF-8", "-t", "ASCII", "/nope.txt"], None, None).await; - assert_eq!(r.exit_code, 1); - assert!(r.stderr.contains("/nope.txt")); + async fn utf16le_input_keeps_bom_as_character() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes(&["-f", "utf-16le", "-t", "utf-8"], Some(b"\xFF\xFEa\0"), fs).await; + assert_eq!(r.stdout, "\u{FEFF}a"); } #[tokio::test] - async fn test_identity_conversion() { - let r = run(&["-f", "UTF-8", "-t", "UTF-8"], Some("hello world\n"), None).await; + async fn identity_conversion() { + let r = run(&["-f", "UTF-8", "-t", "UTF-8"], Some("hello world\n")).await; assert_eq!(r.exit_code, 0); assert_eq!(r.stdout, "hello world\n"); } #[tokio::test] - async fn test_translit_to_ascii() { + async fn attached_and_long_option_forms() { + for args in [ + &["-futf-8", "-tlatin1"][..], + &["--from-code=utf-8", "--to-code=latin1"][..], + &["--from-code", "utf-8", "--to-code", "latin1"][..], + ] { + let r = run(args, Some("é")).await; + assert_eq!(r.exit_code, 0, "{}", args.join(" ")); + assert_eq!(r.stdout.as_bytes(), b"\xe9", "{}", args.join(" ")); + } + } + + #[tokio::test] + async fn multiple_files_are_concatenated() { + let fs = fs_with("/a", b"\xe9").await; + fs.write_file(Path::new("/b"), b"\xf6").await.unwrap(); + let r = run_bytes(&["-f", "latin1", "-t", "utf-8", "/a", "/b"], None, fs).await; + assert_eq!(r.stdout, "éö"); + } + + #[tokio::test] + async fn translit_to_ascii() { let r = run( &["-f", "UTF-8", "-t", "ascii//translit"], - Some("caf\u{00e9}"), - None, + Some("café naïve"), ) .await; assert_eq!(r.exit_code, 0); - assert_eq!(r.stdout, "cafe"); + assert_eq!(r.stdout, "cafe naive"); } #[tokio::test] - async fn test_translit_multiple_diacritics() { + async fn translit_multi_char_and_unknown() { let r = run( &["-f", "UTF-8", "-t", "ASCII//TRANSLIT"], - Some("na\u{00ef}ve"), - None, + Some("Straße 5€ Ж"), ) .await; assert_eq!(r.exit_code, 0); - assert_eq!(r.stdout, "naive"); + assert_eq!(r.stdout, "Strasse 5EUR ?"); } #[tokio::test] - async fn test_translit_german() { - let r = run( - &["-f", "utf-8", "-t", "ascii//translit"], - Some("H\u{00e9}llo W\u{00f6}rld"), + async fn translit_keeps_chars_the_target_holds() { + let r = run(&["-f", "UTF-8", "-t", "latin1//TRANSLIT"], Some("é€")).await; + assert_eq!(r.exit_code, 0); + assert_eq!(r.stdout.as_bytes(), b"\xe9EUR"); + } + + // --- -o --- + + #[tokio::test] + async fn output_file_in_place() { + let fs = fs_with("/data.csv", b"K\xf6ln\n").await; + let r = run_bytes( + &["-f", "cp819", "-t", "utf-8", "-o", "/data.csv", "/data.csv"], None, + fs.clone(), ) .await; assert_eq!(r.exit_code, 0); - assert_eq!(r.stdout, "Hello World"); + assert!(r.stdout.is_empty()); + assert_eq!( + fs.read_file(Path::new("/data.csv")).await.unwrap(), + "Köln\n".as_bytes() + ); + } + + #[tokio::test] + async fn output_file_untouched_on_failure() { + let original = b"K\xf6ln\n"; + let fs = fs_with("/data.csv", original).await; + let r = run_bytes( + &[ + "-f", + "utf-8", + "-t", + "latin1", + "-o", + "/data.csv", + "/data.csv", + ], + None, + fs.clone(), + ) + .await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("illegal input sequence at position 1")); + assert_eq!( + fs.read_file(Path::new("/data.csv")).await.unwrap(), + original + ); + } + + // --- -c / //IGNORE --- + + #[tokio::test] + async fn omit_invalid_input_bytes() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes(&["-c", "-f", "utf-8", "-t", "utf-8"], Some(b"a\xffb\n"), fs).await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "ab\n"); + assert!(r.stderr.is_empty()); + } + + #[tokio::test] + async fn omit_truncated_trailing_char() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes(&["-c", "-f", "utf-8", "-t", "latin1"], Some(b"a\xc3"), fs).await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "a"); + } + + #[tokio::test] + async fn omit_unencodable_chars() { + for args in [ + &["-c", "-f", "utf-8", "-t", "latin1"][..], + &["-f", "utf-8", "-t", "latin1//IGNORE"][..], + ] { + let r = run(args, Some("aЖé\n")).await; + assert_eq!(r.exit_code, 1, "{}", args.join(" ")); + assert_eq!(r.stdout.as_bytes(), b"a\xe9\n", "{}", args.join(" ")); + } + } + + #[tokio::test] + async fn omit_with_output_file_still_writes() { + let fs = fs_with("/in", b"a\xffb").await; + let r = run_bytes( + &["-c", "-f", "utf-8", "-t", "utf-8", "-o", "/out", "/in"], + None, + fs.clone(), + ) + .await; + assert_eq!(r.exit_code, 1); + assert_eq!(fs.read_file(Path::new("/out")).await.unwrap(), b"ab"); + } + + #[tokio::test] + async fn omit_in_place_rewrites_with_dropped_bytes() { + let fs = fs_with("/data", b"a\xffb\n").await; + let r = run_bytes( + &["-c", "-f", "utf-8", "-t", "utf-8", "-o", "/data", "/data"], + None, + fs.clone(), + ) + .await; + assert_eq!(r.exit_code, 1); + assert_eq!(fs.read_file(Path::new("/data")).await.unwrap(), b"ab\n"); + } + + #[tokio::test] + async fn empty_suffixes_are_accepted_like_glibc() { + for target in ["UTF-8//", "ASCII//,,", "ASCII//TRANSLIT//"] { + let r = run(&["-f", "utf-8", "-t", target], Some("ab")).await; + assert_eq!(r.exit_code, 0, "{target}"); + assert_eq!(r.stdout, "ab", "{target}"); + } + } + + #[tokio::test] + async fn silent_keeps_error_messages_like_glibc() { + let r = run(&["-s", "-f", "utf-8", "-t", "ascii"], Some("aé")).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("illegal input sequence")); + } + + #[tokio::test] + async fn omit_broken_utf16() { + let fs = Arc::new(InMemoryFs::new()); + // lone high surrogate, then 'a', then odd trailing byte + let r = run_bytes( + &["-c", "-f", "utf-16le", "-t", "utf-8"], + Some(b"\x00\xD8a\0x"), + fs, + ) + .await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "a"); + } + + // --- negative --- + + #[tokio::test] + async fn unencodable_char_stops_with_prefix() { + let r = run(&["-f", "UTF-8", "-t", "ASCII"], Some("caf\u{e9}!")).await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "caf"); + assert_eq!(r.stderr, "iconv: illegal input sequence at position 3\n"); + } + + #[tokio::test] + async fn invalid_utf8_input_reports_position() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes(&["-f", "utf-8", "-t", "utf-16le"], Some(b"ab\xffc"), fs).await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout.as_bytes(), b"a\0b\0"); + assert!(r.stderr.contains("position 2")); + } + + #[tokio::test] + async fn truncated_input_is_incomplete() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes( + &["-f", "utf-8", "-t", "utf-8"], + Some(b"a\xe2\x82"), + fs.clone(), + ) + .await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "a"); + assert!(r.stderr.contains("incomplete character")); + let r = run_bytes(&["-f", "utf-16le", "-t", "utf-8"], Some(b"a\0b"), fs).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("incomplete character")); + } + + #[tokio::test] + async fn invalid_ascii_input() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes(&["-f", "ascii", "-t", "utf-8"], Some(b"a\x80"), fs).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("position 1")); + } + + #[tokio::test] + async fn missing_from_encoding() { + let r = run(&["-t", "ASCII"], Some("hi")).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("missing source encoding")); + } + + #[tokio::test] + async fn missing_to_encoding() { + let r = run(&["-f", "ASCII"], Some("hi")).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("missing target encoding")); + } + + #[tokio::test] + async fn missing_option_argument() { + for flag in ["-f", "-t", "-o", "--output"] { + let r = run(&["-f", "utf-8", "-t", "ascii", flag], Some("hi")).await; + assert_eq!(r.exit_code, 1, "{flag}"); + assert!(r.stderr.contains("requires an argument"), "{flag}"); + } + } + + #[tokio::test] + async fn unsupported_encoding() { + let r = run(&["-f", "EBCDIC", "-t", "UTF-8"], Some("hi")).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("unsupported encoding")); + } + + #[tokio::test] + async fn unsupported_target_suffix() { + for target in ["ASCII//BAD", "UTF-8//TRANSLIT//NOPE"] { + let r = run(&["-f", "UTF-8", "-t", target], Some("hi")).await; + assert_eq!(r.exit_code, 1, "target should be rejected: {target}"); + assert!(r.stderr.contains("unsupported encoding")); + } + } + + #[tokio::test] + async fn unknown_option() { + let r = run(&["-f", "utf-8", "-t", "ascii", "-x"], Some("hi")).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("unknown option '-x'")); + } + + #[tokio::test] + async fn no_input() { + let r = run(&["-f", "UTF-8", "-t", "ASCII"], None).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("no input")); + } + + #[tokio::test] + async fn file_not_found() { + let r = run(&["-f", "UTF-8", "-t", "ASCII", "/nope.txt"], None).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("/nope.txt")); + } + + #[tokio::test] + async fn arbitrary_bytes_never_panic() { + // Every single byte and byte pair, through every source charset. + let fs = Arc::new(InMemoryFs::new()); + let mut inputs: Vec> = (0u8..=255).map(|b| vec![b]).collect(); + inputs.push((0u8..=255).collect()); + inputs.push(vec![0xF4, 0x90, 0x80, 0x80]); + inputs.push(vec![0xED, 0xA0, 0x80]); + for from in ["utf-8", "ascii", "latin1", "utf-16", "utf-16le", "utf-16be"] { + for input in &inputs { + for flags in [&["-c"][..], &[][..]] { + let mut args = flags.to_vec(); + args.extend(["-f", from, "-t", "utf-16"]); + let _ = run_bytes(&args, Some(input), fs.clone()).await; + } + } + } } } diff --git a/crates/bashkit/tests/integration/byte_stream_tests.rs b/crates/bashkit/tests/integration/byte_stream_tests.rs index 8c74cbddc..adda69fc8 100644 --- a/crates/bashkit/tests/integration/byte_stream_tests.rs +++ b/crates/bashkit/tests/integration/byte_stream_tests.rs @@ -161,3 +161,57 @@ async fn select_consumes_binary_pipeline_lines_by_raw_byte_offset() { ); assert_eq!(result.exit_code, 0); } + +#[tokio::test] +async fn iconv_repairs_cp_export_and_writes_real_bytes() { + // Latin-1 export in, UTF-8 for text tools, then Latin-1 / UTF-16 bytes out. + let mut bash = Bash::new(); + let result = bash + .exec( + "printf 'K\\366ln;1\\n' > /e.csv + iconv -f latin1 -t utf-8 -o /e.csv /e.csv + cut -d';' -f1 /e.csv | iconv -f utf-8 -t latin1 | od -An -tx1 + printf 'K\\303\\203\\302\\266ln' | iconv -f utf-8 -t latin1 | iconv -f utf-8 -t utf-16le | od -An -tx1", + ) + .await + .unwrap(); + assert_eq!( + result.stdout.text().unwrap(), + " 4b f6 6c 6e 0a\n 4b 00 f6 00 6c 00 6e 00\n" + ); + assert_eq!( + bash.fs() + .read_file(std::path::Path::new("/e.csv")) + .await + .unwrap(), + "Köln;1\n".as_bytes() + ); +} + +#[tokio::test] +async fn iconv_matches_real_iconv_byte_for_byte() { + // Skip where the host has no iconv; CI runners ship glibc's. + if Command::new("iconv").arg("-l").output().is_err() { + return; + } + for script in [ + "printf 'K\\303\\266ln \\342\\202\\254\\n' | iconv -f utf-8 -t utf-16", + "printf 'K\\303\\266ln\\n' | iconv -f utf-8 -t utf-16be", + "printf 'K\\303\\266ln\\n' | iconv -f utf-8 -t latin1", + "printf 'K\\366ln\\n' | iconv -f iso-8859-1 -t utf-8", + "printf '\\377\\376a\\000\\330\\075\\336\\000' | iconv -f utf-16 -t utf-8", + // -c exit status differs on purpose (L-ICONV-001); bytes must match. + "printf 'a\\377b\\n' | iconv -c -f utf-8 -t utf-8; true", + "printf 'ab\\303' | iconv -f utf-8 -t latin1", + ] { + let expected = Command::new("bash").args(["-c", script]).output().unwrap(); + let mut bash = Bash::new(); + let actual = bash.exec(script).await.unwrap(); + assert_eq!(actual.stdout.as_bytes(), expected.stdout, "{script}"); + assert_eq!( + actual.exit_code, + expected.status.code().unwrap(), + "{script}" + ); + } +} diff --git a/knowledge/log.md b/knowledge/log.md index 5df2d827b..e2ae0153d 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,7 @@ ## 2026-11-18 +* **iconv writes real bytes; `-o`, `-c`, `//IGNORE`** (issue #2935): `iconv` built its output as a `String`, so `-t latin1` wrote UTF-8 again (double-encoded `Köln` could not be repaired) and `-t utf-16` went through a lossy decode. Conversion now runs char by char from input bytes to output bytes, with GNU positions in errors and the converted prefix on stdout when it stops. `UTF-16LE`/`UTF-16BE` write no BOM (`utf-16le` was an alias of the BOM form). `-o FILE` writes only after a full conversion, so `-o in.csv in.csv` with a wrong `-f` leaves the file intact. `-c`/`//IGNORE` drop bad input and unconvertible characters and exit 1. Output growth is charged to the execution budget. See [Limitations](operations/limitations.md) L-ICONV-001. * **Windows `/dev/stderr` redirects hit the VFS (#2933), and four more host-separator joins**: `dev_fd_alias` re-normalized the already-clean redirect target with `PathBuf::push`, which joins with `\` on Windows, so `/dev\stderr` missed the string match and `echo x > /dev/stderr` wrote a VFS file. It now uses the shared `normalize_path`. A clippy trial run with the join methods banned found the rest of the class: `PosixFs::mkdir -p` parent checks (backend saw `/a\b`), `cd x/..`, `readlink -f`/`realpath` prefix probes, and `OverlayFs` upper-dir counting, all now `vfs_join`. Second sweep after #2425, so the fix is a guard, not a sweep: `crates/bashkit/clippy.toml` bans `Path::join`/`PathBuf::push`/`set_file_name`/`with_file_name` with scoped allows for host-path code; `testing::CheckedFs` records paths a filesystem receives; the Windows CI job now runs the device-path and separator integration tests. Fuzzing could not have found it: Linux's separator is `/`. See [Virtual Filesystem](foundations/vfs.md). * **picomatch ReDoS suppressed: no patched release exists**: the nightly `Advisory Audit` went red on 2026-11-18 with GHSA-fc5q-39xc-vjpf (CVE-2026-112366, high) against `picomatch` in three of the five pnpm lockfiles (crates/bashkit-js, examples/browser, site). Nothing in the tree moved: picomatch 4.0.7 has been the resolution in all three since 2026-11-07 and every push scan was green, including main at 1bea26a eighteen hours earlier; the advisory was widened to cover `<= 4.0.7` on 2026-11-17. `<= 4.0.7` is picomatch's entire release history and the advisory lists no patched version, so the usual npm answer -- bump to the fix -- does not exist, and `pnpm audit` keys on the resolved version, so a `pnpm patch` would not clear it either. Suppressed by id in `IGNORED_NPM_ADVISORIES` with a rationale and a removal condition, the first npm entry since the `braces` exception was retired on 2026-10-23. The exposure is build tooling only: `ava` and `@napi-rs/cli` in crates/bashkit-js, `vite`/`tinyglobby` in examples/browser, `astro` and `vite` in site, plus `micromatch`/`anymatch` on picomatch 2.3.2. Every glob those compile comes from repo config or a build tool's own defaults, no tenant input reaches them, and no published crate, wheel or npm package resolves picomatch -- the published `@everruns/bashkit` ships only its JS wrappers and native binaries, with `@napi-rs/wasm-runtime` as its single optional dependency. A suppressed finding is still printed by the wrapper, so the entry stays visible until picomatch ships a release above 4.0.7. See [Threat Model](security/threat-model.md#suppressed-advisories). diff --git a/knowledge/operations/limitations.md b/knowledge/operations/limitations.md index 7a90c3377..9a7e5c373 100644 --- a/knowledge/operations/limitations.md +++ b/knowledge/operations/limitations.md @@ -227,6 +227,7 @@ pass in CI); only divergences and boundaries are recorded here. | L-OD-001 | od | Floating-point types (`-t f`, `-e`, `-f`, `-F`) are refused with an error; `-S`/`--strings` and `--traditional` are accepted but ignored | `test_od_float_rejected` | | L-FOLD-001 | fold | Every character counts one column (no East Asian wide-char widths); `-b` counts UTF-8 bytes | `fold.rs` | | L-STR-001 | strings | Accepts dash-prefixed filenames (e.g. `-data.bin`), so only a lone unknown short option (`-Q`) is rejected as invalid; GNU rejects `-data.bin` too | `strings.rs` | +| L-ICONV-001 | iconv | Charsets: UTF-8, ASCII, Latin-1, UTF-16 (BOM, LE default), UTF-16LE, UTF-16BE. `-c`/`//IGNORE` exit 1 when anything was dropped (POSIX, GNU libiconv); glibc 2.39 exits 0 when only unconvertible characters were dropped. `-c` also drops a sequence truncated at end of input, where glibc still errors. `-c -o FILE` writes the converted rest (dropping was requested); without `-c`, `-o` never writes after an error. `-s` is accepted and, like glibc, keeps error messages. `//TRANSLIT` uses a built-in Latin/punctuation table, unknown characters become `?` | `iconv.rs` tests | | L-MAKE-001 | make | `$(eval)` and `$(file)` stop make with `function '...' is not supported (L-MAKE-001)` | Both write makefile state or files mid-expansion; expansion restarts on a `$(shell)`/`$(wildcard)` miss, so side-effecting functions would run more than once | `l_make_001_eval_and_file_unsupported` | | L-MAKE-002 | make | No built-in implicit rules (as `make -r`), pattern rules do not chain through intermediate files, and `vpath`/`VPATH` are not searched | The sandbox has no compiler for built-in rules to call; chaining and directory search are the next steps if real makefiles need them | `l_make_002_no_builtin_or_chained_rules` | | L-MAKE-003 | make | Recipes always run in the sandbox shell one at a time: `SHELL` is ignored, `-j` is accepted but sequential, and `$(MAKE)` fails at MAKELEVEL 4 (`recursive make depth exceeds 4`; GNU has no cap) | Recipes must stay inside the interpreter; each nested make runs on the caller's stack (TM-DOS-126) | `l_make_003_sequential_sandbox_shell` | diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 6910f6cc6..7befb21bf 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -1309,7 +1309,7 @@ command count, timeout, `catch_unwind`). | `base64` | Encode/decode base64 | Pure byte transformation; output bounded by input size | | `md5sum`, `sha1sum`, `sha256sum` | Compute checksums | Hash computation on VFS file data; O(n) CPU, bounded by `max_file_size` | | `verify` | Compute/verify file hashes | Same as checksum builtins; reads VFS files only | -| `iconv` | Encoding conversion | Pure byte transformation between UTF-8/ASCII/Latin1/UTF-16 | +| `iconv` | Encoding conversion | Pure byte transformation; output growth (up to 2x for UTF-16) charged to the shared execution budget; `-o` writes through the VFS only after the whole input converted | | `hextools` (`od`, `xxd`, `hexdump`) | Byte-level inspection | Format VFS file bytes as hex/octal; output bounded by input size | | `semver` | Version string parsing | Pure string comparison; no recursion or resource access | | `strings` | Extract printable strings | Linear scan of byte data; output bounded by input |