zshrs 0.11.3

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
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
//! POSIX.1e capabilities — port of `Src/Modules/cap.c`.
//!
//! Implements `cap` / `getcap` / `setcap`. Linux-only (libcap);
//! macOS / BSD have no POSIX.1e capability sets — the stubs return
//! Unsupported.
//!
//! Structure mirrors the C source line-by-line:
//!   - `bin_cap` (cap.c:36)
//!   - `bin_getcap` (cap.c:68)
//!   - `bin_setcap` (cap.c:91)
//!   - `static struct builtin bintab[]` (cap.c:123)
//!   - module entries (cap.c:139-178)

#![allow(non_camel_case_types)]
#![allow(non_snake_case)]

use crate::ported::utils::zwarnnam;
use crate::ported::zsh_h::{module, options};
use std::ffi::{CStr, CString};

// =====================================================================
// libcap FFI — declared in `<sys/capability.h>` (libcap), not libc.
// =====================================================================

#[cfg(all(target_os = "linux", feature = "libcap"))]
mod ffi {
    use libc::{c_char, c_int, c_void, ssize_t};

    /// `cap_t` is an opaque pointer in libcap.
    pub type CapT = *mut c_void;

    #[link(name = "cap")]
    extern "C" {
        pub fn cap_get_proc() -> CapT;
        pub fn cap_set_proc(cap_p: CapT) -> c_int;
        pub fn cap_get_file(path: *const c_char) -> CapT;
        pub fn cap_set_file(path: *const c_char, cap_p: CapT) -> c_int;
        pub fn cap_from_text(buf: *const c_char) -> CapT;
        pub fn cap_to_text(caps: CapT, length: *mut ssize_t) -> *mut c_char;
        pub fn cap_free(obj: *mut c_void) -> c_int;
    }
}

// =====================================================================
// Port of `bin_cap(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))` from Src/Modules/cap.c:36.
// =====================================================================

/// Port of `bin_cap(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))` from `Src/Modules/cap.c:36`.
///
/// `cap [STRING]`: with `STRING`, parse via `cap_from_text` and
/// install via `cap_set_proc`; without args, print the current
/// process's capability set.
#[cfg(all(target_os = "linux", feature = "libcap"))]
/// WARNING: param names don't match C — Rust=(argv, _ops, _func) vs C=(nam, argv, ops, func)
pub(crate) fn bin_cap(nam: &str, argv: &[String], _ops: &options, _func: i32) -> i32 { // c:36

    let mut ret = 0;
    if let Some(arg0) = argv.first() {
        // C: caps = cap_from_text(*argv);
        let arg_c = match CString::new(arg0.as_str()) {
            Ok(c) => c,
            Err(_) => {
                zwarnnam(nam, "invalid capability string");
                return 1;
            }
        };
        unsafe {
            let caps = ffi::cap_from_text(arg_c.as_ptr());
            if caps.is_null() {
                zwarnnam(nam, "invalid capability string");
                return 1;
            }
            // C: if (cap_set_proc(caps)) { zwarnnam(...); ret = 1; }
            if ffi::cap_set_proc(caps) != 0 {
                zwarnnam(
                    nam,
                    &format!("can't change capabilities: {}", std::io::Error::last_os_error()),
                );
                ret = 1;
            }
            ffi::cap_free(caps);
        }
    } else {
        // C: caps = cap_get_proc(); if (caps) result = cap_to_text(caps, &length);
        unsafe {
            let caps = ffi::cap_get_proc();
            let result = if !caps.is_null() {
                ffi::cap_to_text(caps, std::ptr::null_mut())
            } else {
                std::ptr::null_mut()
            };
            if caps.is_null() || result.is_null() {
                zwarnnam(
                    nam,
                    &format!("can't get capabilities: {}", std::io::Error::last_os_error()),
                );
                ret = 1;
            } else {
                let s = CStr::from_ptr(result).to_string_lossy();
                println!("{}", s);
            }
            if !result.is_null() {
                ffi::cap_free(result as *mut libc::c_void);
            }
            if !caps.is_null() {
                ffi::cap_free(caps);
            }
        }
    }
    ret
}

/// Port of `bin_cap()` — non-Linux stub. C uses `bin_notavail`
/// (cap.c:115); we mirror the behaviour by emitting the same
/// "not available on this host" error.
#[cfg(not(all(target_os = "linux", feature = "libcap")))]
pub(crate) fn bin_cap(nam: &str, _argv: &[String], _ops: &options, _func: i32) -> i32 {
    zwarnnam(nam, "not available on this host");
    1
}

// =====================================================================
// Port of `bin_getcap(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))` from Src/Modules/cap.c:68.
// =====================================================================

/// Port of `bin_getcap(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))` from `Src/Modules/cap.c:68`.
///
/// `getcap FILE...`: print each file's capability set as
/// `FILE CAPS`. C bails on the first error but iterates the rest;
/// the Rust port mirrors that exact loop.
#[cfg(all(target_os = "linux", feature = "libcap"))]
/// WARNING: param names don't match C — Rust=(argv, _ops, _func) vs C=(nam, argv, ops, func)
pub(crate) fn bin_getcap(nam: &str, argv: &[String], _ops: &options, _func: i32) -> i32 {

    let mut ret = 0;
    // C: do { ... } while(*++argv);
    for file in argv {
        let path_c = match CString::new(file.as_str()) {
            Ok(c) => c,
            Err(_) => {
                zwarnnam(nam, &format!("{}: invalid path", file));
                ret = 1;
                continue;
            }
        };
        unsafe {
            let caps = ffi::cap_get_file(path_c.as_ptr());
            let result = if !caps.is_null() {
                ffi::cap_to_text(caps, std::ptr::null_mut())
            } else {
                std::ptr::null_mut()
            };
            if caps.is_null() || result.is_null() {
                zwarnnam(nam, &format!("{}: {}", file, std::io::Error::last_os_error()));
                ret = 1;
            } else {
                let s = CStr::from_ptr(result).to_string_lossy();
                println!("{} {}", file, s);
            }
            if !result.is_null() {
                ffi::cap_free(result as *mut libc::c_void);
            }
            if !caps.is_null() {
                ffi::cap_free(caps);
            }
        }
    }
    ret
}

/// Port of `bin_getcap()` — non-Linux stub.
#[cfg(not(all(target_os = "linux", feature = "libcap")))]
pub(crate) fn bin_getcap(nam: &str, _argv: &[String], _ops: &options, _func: i32) -> i32 {
    zwarnnam(nam, "not available on this host");
    1
}

// =====================================================================
// Port of `bin_setcap(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))` from Src/Modules/cap.c:91.
// =====================================================================

/// Port of `bin_setcap(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))` from `Src/Modules/cap.c:91`.
///
/// `setcap STRING FILE...`: parse `STRING` via `cap_from_text`, then
/// apply via `cap_set_file` to each remaining file argument. Mirrors
/// C's loop: free `caps` once at end, advance `argv` per iteration.
#[cfg(all(target_os = "linux", feature = "libcap"))]
/// WARNING: param names don't match C — Rust=(argv, _ops, _func) vs C=(nam, argv, ops, func)
pub(crate) fn bin_setcap(nam: &str, argv: &[String], _ops: &options, _func: i32) -> i32 {

    let mut ret = 0;
    let cap_str = match argv.first() {
        Some(s) => s.as_str(),
        None => {
            zwarnnam(nam, "invalid capability string");
            return 1;
        }
    };
    let cap_c = match CString::new(cap_str) {
        Ok(c) => c,
        Err(_) => {
            zwarnnam(nam, "invalid capability string");
            return 1;
        }
    };
    unsafe {
        let caps = ffi::cap_from_text(cap_c.as_ptr());
        if caps.is_null() {
            zwarnnam(nam, "invalid capability string");
            return 1;
        }
        // C: do { if(cap_set_file(...)) { zwarnnam; ret = 1; } } while(*++argv);
        for file in &argv[1..] {
            let path_c = match CString::new(file.as_str()) {
                Ok(c) => c,
                Err(_) => {
                    zwarnnam(nam, &format!("{}: invalid path", file));
                    ret = 1;
                    continue;
                }
            };
            if ffi::cap_set_file(path_c.as_ptr(), caps) != 0 {
                zwarnnam(nam, &format!("{}: {}", file, std::io::Error::last_os_error()));
                ret = 1;
            }
        }
        ffi::cap_free(caps);
    }
    ret
}

/// Port of `bin_setcap()` — non-Linux stub.
#[cfg(not(all(target_os = "linux", feature = "libcap")))]
pub(crate) fn bin_setcap(nam: &str, _argv: &[String], _ops: &options, _func: i32) -> i32 {
    zwarnnam(nam, "not available on this host");
    1
}

// =====================================================================
// /* module paraphernalia */                                        c:121
// static struct builtin bintab[]                                    c:123
// static struct features module_features                            c:129
// =====================================================================


// `bintab` — port of `static struct builtin bintab[]` (cap.c:123).


// `module_features` — port of `static struct features module_features`
// from cap.c:129. Uses canonical slice-based `module::Features`.



// =====================================================================
// Module entry points (cap.c:138-178).
// =====================================================================

/// Port of `setup_(UNUSED(Module m))` from `Src/Modules/cap.c:139`.
#[allow(unused_variables)]
pub fn setup_(m: *const module) -> i32 {                                    // c:139
    0                                                                  // c:154
}

/// Port of `features_(UNUSED(Module m), UNUSED(char ***features))` from `Src/Modules/cap.c:146`.
/// C body: `*features = featuresarray(m, &module_features); return 0;`
pub fn features_(m: *const module, features: &mut Vec<String>) -> i32 {     // c:146
    *features = featuresarray(m, module_features());
    0                                                                  // c:161
}

/// Port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from `Src/Modules/cap.c:154`.
/// C body: `return handlefeatures(m, &module_features, enables);`
pub fn enables_(m: *const module, enables: &mut Option<Vec<i32>>) -> i32 {  // c:154
    handlefeatures(m, module_features(), enables) // c:168
}

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/cap.c:161`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {                                     // c:161
    0                                                                  // c:175
}

/// Port of `cleanup_(UNUSED(Module m))` from `Src/Modules/cap.c:168`.
/// C body: `return setfeatureenables(m, &module_features, NULL);`
pub fn cleanup_(m: *const module) -> i32 {                                  // c:168
    setfeatureenables(m, module_features(), None) // c:175
}

/// Port of `finish_(UNUSED(Module m))` from `Src/Modules/cap.c:175`.
#[allow(unused_variables)]
pub fn finish_(m: *const module) -> i32 {                                   // c:175
    0                                                                  // c:175
}

// =====================================================================
// ShellExecutor bridge — sanctioned PORT.md exception. Wires the
// internal builtin dispatcher to the canonical free fns above.
// =====================================================================

// (impl ShellExecutor block moved to src/exec_shims.rs — see file marker)


// =====================================================================
// Tests
// =====================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn empty_ops() -> options {
        options { ind: [0u8; crate::ported::zsh_h::MAX_OPS], args: Vec::new(), argscount: 0, argsalloc: 0 }
    }

    #[test]
    fn test_features_returns_bintab_names() {
        let m: *const module = std::ptr::null();
        let mut features: Vec<String> = Vec::new();
        let rc = features_(m, &mut features);
        assert_eq!(rc, 0);
        assert_eq!(features, vec!["b:cap", "b:getcap", "b:setcap"]);
    }

    #[test]
    fn test_enables_get_then_set() {
        let m: *const module = std::ptr::null();
        let mut enables: Option<Vec<i32>> = None;
        let rc = enables_(m, &mut enables);
        assert_eq!(rc, 0);
        let v = enables.as_ref().unwrap();
        assert_eq!(v.len(), 3);
        let rc = enables_(m, &mut enables);
        assert_eq!(rc, 0);
    }

    #[test]
    fn test_cleanup_returns_zero() {
        let m: *const module = std::ptr::null();
        assert_eq!(cleanup_(m), 0);
    }

    #[test]
    #[cfg(not(all(target_os = "linux", feature = "libcap")))]
    fn test_bin_cap_unsupported_on_macos() {
        let ops = empty_ops();
        // Without libcap, all three bin_* return 1 (notavail).
        assert_eq!(bin_cap("cap", &[], &ops, 0), 1);
        assert_eq!(bin_getcap("getcap", &["/etc/passwd".into()], &ops, 0), 1);
        assert_eq!(
            bin_setcap("setcap", &["cap_net_admin+ep".into(), "/tmp/x".into()], &ops, 0),
            1
        );
    }
}

use crate::ported::zsh_h::features as features_t;
use std::sync::{Mutex, OnceLock};

static MODULE_FEATURES: OnceLock<Mutex<features_t>> = OnceLock::new();

// WARNING: NOT IN CAP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn module_features() -> &'static Mutex<features_t> {
    MODULE_FEATURES.get_or_init(|| Mutex::new(features_t {
        bn_list: None,
        bn_size: 3,
        cd_list: None,
        cd_size: 0,
        mf_list: None,
        mf_size: 0,
        pd_list: None,
        pd_size: 0,
        n_abstract: 0,
    }))
}

// Local stubs for the per-module entry points. C uses generic
// `featuresarray`/`handlefeatures`/`setfeatureenables` (module.c:
// 3275/3370/3445) but those take `Builtin` + `Features` pointer
// fields the Rust port doesn't carry. The hardcoded descriptor
// list mirrors the C bintab/conddefs/mathfuncs/paramdefs.
// WARNING: NOT IN CAP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn featuresarray(_m: *const module, _f: &Mutex<features_t>) -> Vec<String> {
    vec!["b:cap".to_string(), "b:getcap".to_string(), "b:setcap".to_string()]
}

// WARNING: NOT IN CAP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn handlefeatures(
    _m: *const module,
    _f: &Mutex<features_t>,
    enables: &mut Option<Vec<i32>>,
) -> i32 {
    if enables.is_none() {
        *enables = Some(vec![1; 3]);
    }
    0
}

// WARNING: NOT IN CAP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn setfeatureenables(
    _m: *const module,
    _f: &Mutex<features_t>,
    _e: Option<&[i32]>,
) -> i32 {
    0
}