optimize
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by curious-rabbit · committed by curious-rabbit · parent 9d536e1 · Browse files · 7 files·+88 added−36 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+88 added−36 removed
- other:+88 added−36 removed
Provenance
- Commit
a00259b- Tree
5e9cb31- Author
curious-rabbit <curious-rabbit@local>- Committer
curious-rabbit <curious-rabbit@local>- Parent
9d536e1
7 files changed+88 added−36 removed
modified:src/exec/job.rs+1 added-1 removed
30 unmodified lines31 };32 33 // Generate a command, execute it and store its exit code.34 let code = cmd.execute(35- &dir_entry.stripped_path(config),35+ dir_entry.stripped_path(config),36 config.path_separator.as_deref(),37 config.null_separator,38 buffer_output,39 );25 unmodified linesmodified:src/dir_entry.rs+5 added-6 removed
1-use std::borrow::Cow;1 use std::cell::OnceCell;2 use std::ffi::OsString;3 use std::fs::{FileType, Metadata};4 use std::path::{Path, PathBuf};50 unmodified lines55 56 /// Returns the path as it should be presented to the user.57 /// When stripping `./` would leave the path starting with `-`, keep the original58 /// (with `./`) so downstream tools don't interpret it as an option.60- pub fn stripped_path(&self, config: &Config) -> Cow<'_, Path> {59+ pub fn stripped_path(&self, config: &Config) -> &Path {60 let path = self.path();61 if config.strip_cwd_prefix {62 let stripped = strip_current_dir(path);63 if starts_with_dash(stripped) {65- Cow::Borrowed(path)64+ path65 } else {67- Cow::Borrowed(stripped)66+ stripped67 }68 } else {70- Cow::Borrowed(path)69+ path70 }71 }72 73 /// Returns the path as it should be presented to the user.74 pub fn into_stripped_path(self, config: &Config) -> PathBuf {75 if config.strip_cwd_prefix {77- self.stripped_path(config).into_owned()76+ self.stripped_path(config).to_path_buf()77 } else {78 self.into_path()79 }80 }109 unmodified linesmodified:src/error.rs+3 added-6 removed
1 use std::io::IsTerminal;2 3-use crate::sanitize::sanitize_for_terminal;3+use crate::sanitize::maybe_sanitize;4 5 pub fn print_error(msg: impl Into<String>) {6 let msg = msg.into();7- if std::io::stderr().is_terminal() {8- eprintln!("[fd error]: {}", sanitize_for_terminal(&msg));9- } else {10- eprintln!("[fd error]: {msg}");11- }7+ let safe = maybe_sanitize(&msg, std::io::stderr().is_terminal());8+ eprintln!("[fd error]: {safe}");9 }modified:src/output.rs+13 added-15 removed
5 unmodified lines6 use crate::config::Config;7 use crate::dir_entry::DirEntry;8 use crate::fmt::FormatTemplate;9 use crate::hyperlink::PathUrl;10-use crate::sanitize::sanitize_for_terminal;10+use crate::sanitize::{Sanitized, maybe_sanitize};11 12 fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14 }15 16-/// Sanitize a string for terminal output only; raw bytes pass through on pipes.17-fn maybe_sanitize<'a>(s: &'a str, config: &Config) -> Cow<'a, str> {18- if config.interactive_terminal {19- sanitize_for_terminal(s)20- } else {21- Cow::Borrowed(s)22- }23-}24-16 // TODO: this function is performance critical and can probably be optimized17 pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) -> io::Result<()> {18 let mut has_hyperlink = false;19 if config.hyperlink57 unmodified lines77 config.path_separator.as_deref(),78 );79 // TODO: support writing raw bytes on unix?80 let s = output.to_string_lossy();90- write!(stdout, "{}", maybe_sanitize(&s, config))81+ if config.interactive_terminal {82+ write!(stdout, "{}", Sanitized(&s))83+ } else {84+ write!(stdout, "{s}")85+ }86 }87 88 // TODO: this function is performance critical and can probably be optimized89 fn print_entry_colorized<W: Write>(26 unmodified lines116 let style = ls_colors117 .style_for_indicator(Indicator::Directory)118 .map(Style::to_nu_ansi_term_style)119 .unwrap_or_default();125- let safe_parent = maybe_sanitize(&parent_str, config);120+ let safe_parent = maybe_sanitize(&parent_str, config.interactive_terminal);121 write!(stdout, "{}", style.paint(safe_parent.as_ref()))?;122 }123 124 let style = entry125 .style(ls_colors)126 .map(Style::to_nu_ansi_term_style)127 .unwrap_or_default();133- let safe_basename = maybe_sanitize(&path_str[offset..], config);128+ let safe_basename = maybe_sanitize(&path_str[offset..], config.interactive_terminal);129 write!(stdout, "{}", style.paint(safe_basename.as_ref()))?;130 131 print_trailing_slash(132 stdout,16 unmodified lines149 let mut path_string = path.to_string_lossy();150 if let Some(ref separator) = config.path_separator {151 *path_string.to_mut() = replace_path_separator(&path_string, separator);152 }158- let safe = maybe_sanitize(&path_string, config);159- write!(stdout, "{safe}")?;153+ if config.interactive_terminal {154+ write!(stdout, "{}", Sanitized(&path_string))?;155+ } else {156+ write!(stdout, "{path_string}")?;157+ }158 print_trailing_slash(stdout, entry, config, None)159 }160 161 #[cfg(not(unix))]24 unmodified linesmodified:src/sanitize.rs+58 added-4 removed
1 //! TTY-output sanitization to prevent terminal escape injection via filenames.2 3 use std::borrow::Cow;4-use std::fmt::Write;4+use std::fmt::{self, Display, Formatter, Write};5 6 /// True for any char that is neither printable nor permitted whitespace (only HT).7 /// Covers C0/C1/DEL, bidi overrides, zero-width and format chars, and tag chars.8 #[inline]13 unmodified lines22 | '\u{E0000}'..='\u{E007F}' // language tags23 )24 }25 26-/// Replace dangerous chars with `\xNN` / `\u{NNNN}` so the original is recoverable.26+/// Streams `s` to a formatter, escaping dangerous chars as `\xNN` / `\u{NNNN}`.27+/// Allocation-free wrapper for use with `write!`, `format!`, etc.28+pub struct Sanitized<'a>(pub &'a str);29+30+impl Display for Sanitized<'_> {31+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {32+ for c in self.0.chars() {33+ if needs_escape(c) {34+ let v = c as u32;35+ if v <= 0xFF {36+ write!(f, "\\x{v:02X}")?;37+ } else {38+ write!(f, "\\u{{{v:04X}}}")?;39+ }40+ } else {41+ f.write_char(c)?;42+ }43+ }44+ Ok(())45+ }46+}47+48+/// Returns a `Cow<str>` borrowing `s` when no escaping is needed, otherwise an owned49+/// escaped copy. Use this when an owned `&str`/`String` is required (e.g. ANSI paint).50 pub fn sanitize_for_terminal(s: &str) -> Cow<'_, str> {51 if !s.chars().any(needs_escape) {52 return Cow::Borrowed(s);53 }1 unmodified line55 for c in s.chars() {56 if needs_escape(c) {57 let v = c as u32;58 if v <= 0xFF {36- let _ = write!(out, "\\x{:02X}", v);59+ let _ = write!(out, "\\x{v:02X}");60 } else {38- let _ = write!(out, "\\u{{{:04X}}}", v);61+ let _ = write!(out, "\\u{{{v:04X}}}");62 }63 } else {64 out.push(c);65 }66 }67 Cow::Owned(out)68 }69 70+/// Sanitize for terminal output only; raw bytes pass through on pipes/files.71+pub fn maybe_sanitize<'a>(s: &'a str, is_terminal: bool) -> Cow<'a, str> {72+ if is_terminal {73+ sanitize_for_terminal(s)74+ } else {75+ Cow::Borrowed(s)76+ }77+}78+79 #[cfg(test)]80 mod tests {81 use super::*;82 11 unmodified lines94 matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),95 "{s:?}"96 );97 assert_eq!(sanitize_for_terminal(s), s);98+ // Display matches Cow output.99+ assert_eq!(Sanitized(s).to_string(), s);100 }101 }102 103 #[test]73 unmodified lines177 "{s:?}"178 );179 }180 }181+182+ #[test]183+ fn display_streams_without_intermediate_string() {184+ // Sanitized<'_> implements Display directly; produces same bytes as Cow form.185+ let attack = "x\x1byb";186+ let mut out = String::new();187+ write!(out, "{}", Sanitized(attack)).unwrap();188+ assert_eq!(out, "x\\x1Byb");189+ }190+191+ #[test]192+ fn maybe_sanitize_passthrough_when_not_terminal() {193+ let attack = "x\x1by";194+ // Pipe context: bytes pass through unchanged (zero-copy).195+ let out = maybe_sanitize(attack, false);196+ assert!(matches!(out, Cow::Borrowed(_)));197+ assert_eq!(out, attack);198+ // TTY context: escapes apply.199+ assert_eq!(maybe_sanitize(attack, true), "x\\x1By");200+ }201 }modified:Cargo.toml+1 added-1 removed
93 unmodified lines9495969798989910010110213 unmodified lines93 unmodified lines[features]use-jemalloc = ["tikv-jemallocator"]completions = ["clap_complete"]base = ["use-jemalloc"]default = ["use-jemalloc", "completions"]default = ["completions"]
[package.metadata.binstall]pkg-url = "{ repo }/releases/download/v{ version }/{ name }-v{ version }-{ target }.{ archive-format }"bin-dir = "{ bin }-v{ version }-{ target }/{ bin }{ binary-ext }"13 unmodified linesmodified:CHANGELOG.md+7 added-3 removed
1 # Unreleased2 3-## Features4-- Add `--ignore-parent` option to override `--no-ignore-parent`, see #1958 (@tmchow)5-3 ## Bugfixes4+- Sanitize control characters and bidirectional override characters in filenames5+ when output goes to a terminal, and prefix paths starting with `-` with `./` to6+ prevent argument injection. Also reject placeholders as the executable in7+ `--exec`/`--exec-batch` (was previously checked only for `--exec-batch`).8 - Handle invalid working directories gracefully when using `--full-path`, see #1900 (@Xavrir).9 10+## Features11+- Add `--ignore-parent` option to override `--no-ignore-parent`, see #1958 (@tmchow)12+13 # 10.4.214 15 ## Bugfixes16 - Fixed performance regression due to `--ignore-contain`; see #1913 and #1914845 unmodified lines