expression
Trusted directory traversal: skip symlinks and limit depth
Walk only a newly created, trusted tree. Bound depth and number of entries, skip non-regular files and symlinks, propagate errors and sort output. A hostile tree requires stronger handle-relative platform controls; type checks can race. Use a fresh disposable working directory exclusively controlled by this program. Expected stdout (not executed): 2 Common mistake: Calling a pathname-based recursive walk secure against concurrent malicious edits.
Formal Syntax & Structure
rust syntaxrust
read_dir(root); entry.file_type()?; bounded recursionWorking Example
Example Snippetrust
fn main() { use std::fs::{self, File}; use std::io::{Read, Write}; fs::create_dir("bm-fixture").expect("fresh working directory required"); let p = std::path::Path::new("bm-fixture").join("note.txt"); fn walk(dir: &std::path::Path, depth: usize, budget: &mut usize) -> std::io::Result<usize> { if depth == 0 { return Ok(0); } let mut count = 0; for e in fs::read_dir(dir)? { if *budget == 0 { return Err(std::io::Error::other("entry limit")); } *budget -= 1; let e = e?; let t = e.file_type()?; if t.is_dir() { count += walk(&e.path(), depth - 1, budget)?; } else if t.is_file() { count += 1; } } Ok(count) } File::create_new(&p).unwrap(); let d = p.with_file_name("child"); fs::create_dir(&d).unwrap(); File::create_new(d.join("a")).unwrap(); println!("{}", walk(std::path::Path::new("bm-fixture"), 3, &mut 10).unwrap());}