fcoreutils 0.22.0

High-performance GNU coreutils replacement with SIMD and parallelism
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
use std::fs;
use std::io;
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;

/// Configuration for chmod operations.
#[derive(Debug, Clone, Default)]
pub struct ChmodConfig {
    /// Report only when a change is made.
    pub changes: bool,
    /// Suppress most error messages.
    pub quiet: bool,
    /// Output a diagnostic for every file processed.
    pub verbose: bool,
    /// Fail to operate recursively on '/'.
    pub preserve_root: bool,
    /// Operate recursively.
    pub recursive: bool,
}

// Permission bit constants
const S_ISUID: u32 = 0o4000;
const S_ISGID: u32 = 0o2000;
const S_ISVTX: u32 = 0o1000;

const S_IRUSR: u32 = 0o0400;
const S_IWUSR: u32 = 0o0200;
const S_IXUSR: u32 = 0o0100;

const S_IRGRP: u32 = 0o0040;
const S_IWGRP: u32 = 0o0020;
const S_IXGRP: u32 = 0o0010;

const S_IROTH: u32 = 0o0004;
const S_IWOTH: u32 = 0o0002;
const S_IXOTH: u32 = 0o0001;

const USER_BITS: u32 = S_IRUSR | S_IWUSR | S_IXUSR;
const GROUP_BITS: u32 = S_IRGRP | S_IWGRP | S_IXGRP;
const OTHER_BITS: u32 = S_IROTH | S_IWOTH | S_IXOTH;
const ALL_BITS: u32 = USER_BITS | GROUP_BITS | OTHER_BITS | S_ISUID | S_ISGID | S_ISVTX;

/// Parse a mode string (octal or symbolic) and return the new mode.
///
/// `mode_str` can be:
/// - Octal: "755", "0644"
/// - Symbolic: "u+x", "g-w", "o=r", "a+rw", "u=rw,g=r,o=", "+t", "u+s"
/// - Combined: "u+rwx,g+rx,o+r"
///
/// `current_mode` is the existing file mode, needed for symbolic modes.
pub fn parse_mode(mode_str: &str, current_mode: u32) -> Result<u32, String> {
    // Try octal first: only if all characters are octal digits
    if !mode_str.is_empty() && mode_str.chars().all(|c| c.is_ascii_digit() && c < '8') {
        if let Ok(octal) = u32::from_str_radix(mode_str, 8) {
            return Ok(octal & 0o7777);
        }
    }
    parse_symbolic_mode(mode_str, current_mode)
}

/// Like `parse_mode` but ignores the process umask.
///
/// Used by `install -m` where the mode string is applied without umask
/// filtering (matching GNU coreutils behaviour).
pub fn parse_mode_no_umask(mode_str: &str, current_mode: u32) -> Result<u32, String> {
    // Try octal first
    if !mode_str.is_empty() && mode_str.chars().all(|c| c.is_ascii_digit() && c < '8') {
        if let Ok(octal) = u32::from_str_radix(mode_str, 8) {
            return Ok(octal & 0o7777);
        }
    }
    parse_symbolic_mode_with_umask(mode_str, current_mode, 0)
}

/// Parse a mode and also compute whether the umask blocked any requested bits.
/// Returns `(new_mode, umask_blocked)` where `umask_blocked` is true if the
/// umask prevented some requested bits from being changed.
///
/// This is needed for GNU compatibility: when no who is specified (e.g. `-rwx`
/// instead of `a-rwx`), umask filters the operation. If the resulting mode
/// differs from what would have been achieved without the umask, GNU warns
/// and exits 1 (but only when the mode was passed as an option-like arg).
pub fn parse_mode_check_umask(mode_str: &str, current_mode: u32) -> Result<(u32, bool), String> {
    // Octal modes are not affected by umask
    if !mode_str.is_empty() && mode_str.chars().all(|c| c.is_ascii_digit() && c < '8') {
        if let Ok(octal) = u32::from_str_radix(mode_str, 8) {
            return Ok((octal & 0o7777, false));
        }
    }

    let umask = get_umask();
    let with_umask = parse_symbolic_mode_with_umask(mode_str, current_mode, umask)?;
    let without_umask = parse_symbolic_mode_with_umask(mode_str, current_mode, 0)?;
    Ok((with_umask, with_umask != without_umask))
}

/// Parse a symbolic mode string and compute the resulting mode.
///
/// Format: `[ugoa]*[+-=][rwxXstugo]+` (comma-separated clauses)
fn parse_symbolic_mode(mode_str: &str, current_mode: u32) -> Result<u32, String> {
    parse_symbolic_mode_with_umask(mode_str, current_mode, get_umask())
}

/// Inner implementation that accepts an explicit umask value.
fn parse_symbolic_mode_with_umask(
    mode_str: &str,
    current_mode: u32,
    umask: u32,
) -> Result<u32, String> {
    let mut mode = current_mode & 0o7777;

    // Preserve the file type bits from the original mode so that
    // apply_symbolic_clause can detect directories for capital-X handling.
    let file_type_bits = current_mode & 0o170000;

    for clause in mode_str.split(',') {
        if clause.is_empty() {
            return Err(format!("invalid mode: '{}'", mode_str));
        }
        mode = apply_symbolic_clause(clause, mode | file_type_bits, umask)? & 0o7777;
    }

    Ok(mode)
}

/// Get the current umask value.
pub fn get_umask() -> u32 {
    // Set umask to 0, read the old value, then restore it.
    // SAFETY: umask is always safe to call.
    let old = unsafe { libc::umask(0) };
    unsafe {
        libc::umask(old);
    }
    old as u32
}

/// Apply a single symbolic mode clause (e.g. "u+x", "go-w", "a=r").
fn apply_symbolic_clause(clause: &str, current_mode: u32, umask: u32) -> Result<u32, String> {
    let bytes = clause.as_bytes();
    let len = bytes.len();
    let mut pos = 0;

    // Parse the "who" part: [ugoa]*
    let mut who_mask: u32 = 0;
    let mut who_specified = false;
    while pos < len {
        match bytes[pos] {
            b'u' => {
                who_mask |= USER_BITS | S_ISUID;
                who_specified = true;
            }
            b'g' => {
                who_mask |= GROUP_BITS | S_ISGID;
                who_specified = true;
            }
            b'o' => {
                who_mask |= OTHER_BITS | S_ISVTX;
                who_specified = true;
            }
            b'a' => {
                who_mask |= ALL_BITS;
                who_specified = true;
            }
            _ => break,
        }
        pos += 1;
    }

    // If no who specified, default to 'a' but filtered by umask
    if !who_specified {
        who_mask = ALL_BITS;
    }

    if pos >= len {
        return Err(format!("invalid mode: '{}'", clause));
    }

    let mut mode = current_mode;

    // Process one or more operator+perm sequences: [+-=][rwxXstugo]*
    while pos < len {
        // Parse operator
        let op = match bytes[pos] {
            b'+' => '+',
            b'-' => '-',
            b'=' => '=',
            _ => return Err(format!("invalid mode: '{}'", clause)),
        };
        pos += 1;

        // Parse permission bits
        let mut perm_bits: u32 = 0;
        let mut has_x_cap = false;
        // Track whether we've seen regular perm chars (rwxXst) vs copy-from (ugo).
        // GNU chmod does not allow mixing these in the same clause after the operator.
        let mut has_perm_chars = false;
        let mut has_copy_from = false;

        while pos < len && bytes[pos] != b'+' && bytes[pos] != b'-' && bytes[pos] != b'=' {
            match bytes[pos] {
                b'r' => {
                    if has_copy_from {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_perm_chars = true;
                    perm_bits |= S_IRUSR | S_IRGRP | S_IROTH;
                }
                b'w' => {
                    if has_copy_from {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_perm_chars = true;
                    perm_bits |= S_IWUSR | S_IWGRP | S_IWOTH;
                }
                b'x' => {
                    if has_copy_from {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_perm_chars = true;
                    perm_bits |= S_IXUSR | S_IXGRP | S_IXOTH;
                }
                b'X' => {
                    if has_copy_from {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_perm_chars = true;
                    has_x_cap = true;
                }
                b's' => {
                    if has_copy_from {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_perm_chars = true;
                    perm_bits |= S_ISUID | S_ISGID;
                }
                b't' => {
                    if has_copy_from {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_perm_chars = true;
                    perm_bits |= S_ISVTX;
                }
                b'u' => {
                    if has_perm_chars {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_copy_from = true;
                    // Copy user bits
                    let u = current_mode & USER_BITS;
                    perm_bits |= u | (u >> 3) | (u >> 6);
                }
                b'g' => {
                    if has_perm_chars {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_copy_from = true;
                    // Copy group bits
                    let g = current_mode & GROUP_BITS;
                    perm_bits |= (g << 3) | g | (g >> 3);
                }
                b'o' => {
                    if has_perm_chars {
                        return Err(format!("invalid mode: '{}'", clause));
                    }
                    has_copy_from = true;
                    // Copy other bits
                    let o = current_mode & OTHER_BITS;
                    perm_bits |= (o << 6) | (o << 3) | o;
                }
                b',' => break,
                _ => return Err(format!("invalid mode: '{}'", clause)),
            }
            pos += 1;
        }

        // Handle capital X: add execute only if directory or already has execute
        if has_x_cap {
            // Check if current mode has any execute bit set, or if we're going
            // to set any execute bit. The caller's is_dir check happens at
            // chmod_file level. For parse_mode, we check the current_mode.
            let is_executable = (current_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0;
            // Note: directory check is indicated by the S_IFDIR bit (0o40000)
            let is_dir = (current_mode & 0o170000) == 0o040000;
            if is_executable || is_dir {
                perm_bits |= S_IXUSR | S_IXGRP | S_IXOTH;
            }
        }

        // Apply the operation, masked by who_mask
        let effective = perm_bits & who_mask;

        // When who is not specified, apply umask filtering for + and -
        let effective = if !who_specified {
            // For +/-, umask filters which bits can be changed
            // For =, umask also applies
            let umask_filter = !(umask) & (USER_BITS | GROUP_BITS | OTHER_BITS);
            // Keep setuid/setgid/sticky that are in effective
            let special = effective & (S_ISUID | S_ISGID | S_ISVTX);
            (effective & umask_filter) | special
        } else {
            effective
        };

        match op {
            '+' => {
                mode |= effective;
            }
            '-' => {
                mode &= !effective;
            }
            '=' => {
                // Clear the who bits, then set the specified ones
                let clear_mask = who_mask & (USER_BITS | GROUP_BITS | OTHER_BITS);
                // For '=', also clear setuid/setgid/sticky if who includes them
                let clear_special = who_mask & (S_ISUID | S_ISGID | S_ISVTX);
                mode &= !(clear_mask | clear_special);

                let effective_eq = if !who_specified {
                    let umask_filter = !(umask) & (USER_BITS | GROUP_BITS | OTHER_BITS);
                    let special = (perm_bits & who_mask) & (S_ISUID | S_ISGID | S_ISVTX);
                    ((perm_bits & who_mask) & umask_filter) | special
                } else {
                    perm_bits & who_mask
                };
                mode |= effective_eq;
            }
            _ => unreachable!(),
        }
    }

    Ok(mode)
}

/// Format a mode as an octal string (4 digits).
fn format_mode(mode: u32) -> String {
    format!("{:04o}", mode & 0o7777)
}

/// Format a mode as a symbolic permission string like `rwxr-xr-x`.
/// Includes setuid/setgid/sticky representation matching GNU coreutils.
fn format_symbolic(mode: u32) -> String {
    let m = mode & 0o7777;
    let mut s = [b'-'; 9];

    // User
    if m & S_IRUSR != 0 {
        s[0] = b'r';
    }
    if m & S_IWUSR != 0 {
        s[1] = b'w';
    }
    if m & S_IXUSR != 0 {
        s[2] = if m & S_ISUID != 0 { b's' } else { b'x' };
    } else if m & S_ISUID != 0 {
        s[2] = b'S';
    }

    // Group
    if m & S_IRGRP != 0 {
        s[3] = b'r';
    }
    if m & S_IWGRP != 0 {
        s[4] = b'w';
    }
    if m & S_IXGRP != 0 {
        s[5] = if m & S_ISGID != 0 { b's' } else { b'x' };
    } else if m & S_ISGID != 0 {
        s[5] = b'S';
    }

    // Other
    if m & S_IROTH != 0 {
        s[6] = b'r';
    }
    if m & S_IWOTH != 0 {
        s[7] = b'w';
    }
    if m & S_IXOTH != 0 {
        s[8] = if m & S_ISVTX != 0 { b't' } else { b'x' };
    } else if m & S_ISVTX != 0 {
        s[8] = b'T';
    }

    String::from_utf8(s.to_vec()).unwrap()
}

/// Format the symbolic mode string for umask-blocked warning messages.
/// Produces output like `rwxr-xr-x`.
pub fn format_symbolic_for_warning(mode: u32) -> String {
    format_symbolic(mode)
}

/// Apply a mode to a file and return whether a change was made.
///
/// If `config.verbose` is true, prints a message for every file.
/// If `config.changes` is true, prints only when the mode changes.
///
/// GNU chmod sends verbose/changes output to stdout.
pub fn chmod_file(path: &Path, mode: u32, config: &ChmodConfig) -> Result<bool, io::Error> {
    let metadata = fs::symlink_metadata(path)?;

    // Skip symlinks
    if metadata.file_type().is_symlink() {
        return Ok(false);
    }

    let old_mode = metadata.mode() & 0o7777;
    let changed = old_mode != mode;

    if changed {
        let perms = fs::Permissions::from_mode(mode);
        fs::set_permissions(path, perms)?;
    }

    let path_display = path.display();
    if config.verbose {
        if changed {
            println!(
                "mode of '{}' changed from {} ({}) to {} ({})",
                path_display,
                format_mode(old_mode),
                format_symbolic(old_mode),
                format_mode(mode),
                format_symbolic(mode)
            );
        } else {
            println!(
                "mode of '{}' retained as {} ({})",
                path_display,
                format_mode(old_mode),
                format_symbolic(old_mode)
            );
        }
    } else if config.changes && changed {
        println!(
            "mode of '{}' changed from {} ({}) to {} ({})",
            path_display,
            format_mode(old_mode),
            format_symbolic(old_mode),
            format_mode(mode),
            format_symbolic(mode)
        );
    }

    Ok(changed)
}

/// Recursively apply a mode string to a directory tree.
///
/// The mode is re-parsed for each file using its current mode, which matters
/// for symbolic modes (e.g. `a+X` behaves differently for files vs directories).
pub fn chmod_recursive(
    path: &Path,
    mode_str: &str,
    config: &ChmodConfig,
) -> Result<bool, io::Error> {
    if config.preserve_root && path == Path::new("/") {
        return Err(io::Error::other(
            "it is dangerous to operate recursively on '/'",
        ));
    }

    let mut had_error = false;

    // Process the path itself first
    match process_entry(path, mode_str, config) {
        Ok(()) => {}
        Err(e) => {
            if !config.quiet {
                eprintln!("chmod: cannot access '{}': {}", path.display(), e);
            }
            had_error = true;
        }
    }

    // Walk the directory tree
    if path.is_dir() {
        walk_dir(path, mode_str, config, &mut had_error);
    }

    if had_error {
        Err(io::Error::other("some operations failed"))
    } else {
        Ok(true)
    }
}

/// Process a single entry: read its mode, parse the mode string, and apply.
fn process_entry(path: &Path, mode_str: &str, config: &ChmodConfig) -> Result<(), io::Error> {
    let metadata = fs::symlink_metadata(path)?;

    // Skip symlinks
    if metadata.file_type().is_symlink() {
        return Ok(());
    }

    let current_mode = metadata.mode();
    let mut new_mode = parse_mode(mode_str, current_mode).map_err(|e| io::Error::other(e))?;

    // GNU chmod: for directories, preserve setuid/setgid bits when the octal
    // mode doesn't explicitly specify them (i.e., <= 4 octal digits).
    if metadata.is_dir()
        && !mode_str.is_empty()
        && mode_str.bytes().all(|b| b.is_ascii_digit() && b < b'8')
        && mode_str.len() <= 4
    {
        let existing_special = current_mode & 0o7000;
        new_mode |= existing_special;
    }

    chmod_file(path, new_mode, config)?;
    Ok(())
}

/// Walk a directory recursively, applying the mode to each entry.
/// Uses rayon for parallel processing when verbose/changes output is not needed.
fn walk_dir(dir: &Path, mode_str: &str, config: &ChmodConfig, had_error: &mut bool) {
    // For non-verbose mode, use parallel traversal with rayon
    if !config.verbose && !config.changes {
        let error_flag = std::sync::atomic::AtomicBool::new(false);
        walk_dir_parallel(dir, mode_str, config, &error_flag);
        if error_flag.load(std::sync::atomic::Ordering::Relaxed) {
            *had_error = true;
        }
        return;
    }

    // Sequential path for verbose/changes mode (output ordering matters)
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) => {
            if !config.quiet {
                eprintln!("chmod: cannot open directory '{}': {}", dir.display(), e);
            }
            *had_error = true;
            return;
        }
    };

    for entry in entries {
        let entry = match entry {
            Ok(e) => e,
            Err(e) => {
                if !config.quiet {
                    eprintln!("chmod: error reading directory entry: {}", e);
                }
                *had_error = true;
                continue;
            }
        };

        let entry_path = entry.path();

        let file_type = match entry.file_type() {
            Ok(ft) => ft,
            Err(e) => {
                if !config.quiet {
                    eprintln!(
                        "chmod: cannot read file type of '{}': {}",
                        entry_path.display(),
                        e
                    );
                }
                *had_error = true;
                continue;
            }
        };

        if file_type.is_symlink() {
            continue;
        }

        match process_entry(&entry_path, mode_str, config) {
            Ok(()) => {}
            Err(e) => {
                if !config.quiet {
                    eprintln!(
                        "chmod: changing permissions of '{}': {}",
                        entry_path.display(),
                        e
                    );
                }
                *had_error = true;
            }
        }

        if file_type.is_dir() {
            walk_dir(&entry_path, mode_str, config, had_error);
        }
    }
}

/// Parallel directory walk using rayon for non-verbose chmod operations.
fn walk_dir_parallel(
    dir: &Path,
    mode_str: &str,
    config: &ChmodConfig,
    had_error: &std::sync::atomic::AtomicBool,
) {
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) => {
            if !config.quiet {
                eprintln!("chmod: cannot open directory '{}': {}", dir.display(), e);
            }
            had_error.store(true, std::sync::atomic::Ordering::Relaxed);
            return;
        }
    };

    let entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();

    use rayon::prelude::*;
    entries.par_iter().for_each(|entry| {
        let entry_path = entry.path();
        let file_type = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => {
                had_error.store(true, std::sync::atomic::Ordering::Relaxed);
                return;
            }
        };

        if file_type.is_symlink() {
            return;
        }

        if process_entry(&entry_path, mode_str, config).is_err() {
            had_error.store(true, std::sync::atomic::Ordering::Relaxed);
        }

        if file_type.is_dir() {
            walk_dir_parallel(&entry_path, mode_str, config, had_error);
        }
    });
}