yosh 0.1.5

A POSIX-compliant shell implemented in Rust
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
pub mod config;

use std::ffi::{CStr, CString, c_char, c_void};
use std::io::Write;
use std::path::Path;

use yosh_plugin_api::{HostApi, PluginDecl, YOSH_PLUGIN_API_VERSION};

use crate::env::ShellEnv;

use self::config::{PluginConfig, expand_tilde};

/// A loaded plugin and its metadata.
struct LoadedPlugin {
    name: String,
    #[allow(dead_code)]
    library: libloading::Library,
    commands: Vec<String>,
    capabilities: u32,
    has_pre_exec: bool,
    has_post_exec: bool,
    has_on_cd: bool,
    has_pre_prompt: bool,
}

/// Manages loaded plugins and dispatches commands/hooks.
pub struct PluginManager {
    plugins: Vec<LoadedPlugin>,
}

impl PluginManager {
    pub fn new() -> Self {
        PluginManager {
            plugins: Vec::new(),
        }
    }

    /// Load plugins listed in the config file. Errors are printed to stderr
    /// and the failing plugin is skipped.
    pub fn load_from_config(&mut self, config_path: &Path, env: &mut ShellEnv) {
        let config = match PluginConfig::load(config_path) {
            Ok(c) => c,
            Err(_) => return,
        };
        for entry in &config.plugin {
            if !entry.enabled {
                continue;
            }
            let path = expand_tilde(&entry.path);
            let config_caps = entry
                .capabilities
                .as_ref()
                .map(|strs| config::capabilities_from_strs(strs));
            if let Err(e) = self.load_plugin_with_capabilities(&path, env, config_caps) {
                eprintln!("yosh: plugin: {}", e);
            }
        }
    }

    /// Load a single plugin from a dynamic library path.
    /// Grants all requested capabilities.
    pub fn load_plugin(&mut self, path: &Path, env: &mut ShellEnv) -> Result<(), String> {
        self.load_plugin_with_capabilities(path, env, None)
    }

    /// Load a single plugin with optional capability restrictions.
    /// `config_capabilities`: None = grant all requested, Some(flags) = intersect with requested.
    pub fn load_plugin_with_capabilities(
        &mut self,
        path: &Path,
        env: &mut ShellEnv,
        config_capabilities: Option<u32>,
    ) -> Result<(), String> {
        // 1. Load library
        let library = unsafe { libloading::Library::new(path) }
            .map_err(|e| format!("{}: {}", path.display(), e))?;

        // 2. Get and validate declaration
        let (name, requested_capabilities) = unsafe {
            let decl_fn: libloading::Symbol<extern "C" fn() -> *const PluginDecl> = library
                .get(b"yosh_plugin_decl")
                .map_err(|_| format!("{}: not a valid yosh plugin", path.display()))?;
            let decl = &*decl_fn();

            if decl.api_version != YOSH_PLUGIN_API_VERSION {
                return Err(format!(
                    "{}: API version mismatch (expected {}, got {})",
                    path.display(),
                    YOSH_PLUGIN_API_VERSION,
                    decl.api_version
                ));
            }

            let name = CStr::from_ptr(decl.name).to_string_lossy().into_owned();
            (name, decl.required_capabilities)
        };

        // 3. Negotiate capabilities
        let effective_capabilities = match config_capabilities {
            None => requested_capabilities,
            Some(config_caps) => {
                let effective = requested_capabilities & config_caps;
                let denied = requested_capabilities & !effective;
                if denied != 0 {
                    Self::log_denied_capabilities(&name, denied);
                }
                effective
            }
        };

        // 4. Initialize plugin with sandboxed API
        {
            let mut ctx = HostContext::new(env, &name);
            let mut api = build_host_api(effective_capabilities);
            api.ctx = &mut ctx as *mut HostContext as *mut c_void;

            let init_fn: libloading::Symbol<unsafe extern "C" fn(*const HostApi) -> i32> = unsafe {
                library
                    .get(b"yosh_plugin_init")
                    .map_err(|_| format!("{}: missing yosh_plugin_init", path.display()))?
            };

            let status = unsafe { init_fn(&api) };
            if status != 0 {
                return Err(format!("{}: initialization failed", name));
            }
        }

        // 5. Get commands
        let commands: Vec<String> = unsafe {
            let cmd_fn: Result<
                libloading::Symbol<unsafe extern "C" fn(*mut u32) -> *const *const c_char>,
                _,
            > = library.get(b"yosh_plugin_commands");

            match cmd_fn {
                Ok(cmd_fn) => {
                    let mut count: u32 = 0;
                    let ptr = cmd_fn(&mut count);
                    (0..count)
                        .map(|i| {
                            CStr::from_ptr(*ptr.add(i as usize))
                                .to_string_lossy()
                                .into_owned()
                        })
                        .collect()
                }
                Err(_) => Vec::new(),
            }
        };

        // 6. Check for optional hook functions
        let has_pre_exec = unsafe {
            library
                .get::<*const ()>(b"yosh_plugin_hook_pre_exec")
                .is_ok()
        };
        let has_post_exec = unsafe {
            library
                .get::<*const ()>(b"yosh_plugin_hook_post_exec")
                .is_ok()
        };
        let has_on_cd = unsafe { library.get::<*const ()>(b"yosh_plugin_hook_on_cd").is_ok() };
        let has_pre_prompt = unsafe {
            library
                .get::<*const ()>(b"yosh_plugin_hook_pre_prompt")
                .is_ok()
        };

        self.plugins.push(LoadedPlugin {
            name,
            library,
            commands,
            capabilities: effective_capabilities,
            has_pre_exec,
            has_post_exec,
            has_on_cd,
            has_pre_prompt,
        });

        Ok(())
    }

    /// Log which capabilities were requested but not granted.
    fn log_denied_capabilities(plugin_name: &str, denied: u32) {
        use yosh_plugin_api::*;
        let caps = [
            (CAP_VARIABLES_READ, "variables:read"),
            (CAP_VARIABLES_WRITE, "variables:write"),
            (CAP_FILESYSTEM, "filesystem"),
            (CAP_IO, "io"),
            (CAP_HOOK_PRE_EXEC, "hooks:pre_exec"),
            (CAP_HOOK_POST_EXEC, "hooks:post_exec"),
            (CAP_HOOK_ON_CD, "hooks:on_cd"),
            (CAP_HOOK_PRE_PROMPT, "hooks:pre_prompt"),
        ];
        for (flag, name) in caps {
            if denied & flag != 0 {
                eprintln!(
                    "yosh: plugin '{}': capability '{}' requested but not granted",
                    plugin_name, name
                );
            }
        }
    }

    /// Execute a plugin command. Returns Some(exit_status) if a plugin handled
    /// the command, or None if no plugin provides this command.
    pub fn exec_command(&self, env: &mut ShellEnv, name: &str, args: &[String]) -> Option<i32> {
        let plugin = self
            .plugins
            .iter()
            .find(|p| p.commands.iter().any(|c| c == name))?;

        let mut ctx = HostContext::new(env, &plugin.name);
        let mut api = build_host_api(plugin.capabilities);
        api.ctx = &mut ctx as *mut HostContext as *mut c_void;

        let c_name = CString::new(name).ok()?;
        let c_args: Vec<CString> = args
            .iter()
            .filter_map(|a| CString::new(a.as_str()).ok())
            .collect();
        let c_arg_ptrs: Vec<*const c_char> = c_args.iter().map(|s| s.as_ptr()).collect();

        let status = unsafe {
            let exec_fn: libloading::Symbol<
                unsafe extern "C" fn(
                    *const HostApi,
                    *const c_char,
                    i32,
                    *const *const c_char,
                ) -> i32,
            > = plugin.library.get(b"yosh_plugin_exec").ok()?;
            exec_fn(
                &api,
                c_name.as_ptr(),
                c_arg_ptrs.len() as i32,
                c_arg_ptrs.as_ptr(),
            )
        };

        Some(status)
    }

    /// Call pre_exec hook on all plugins that have it.
    pub fn call_pre_exec(&self, env: &mut ShellEnv, cmd: &str) {
        let c_cmd = match CString::new(cmd) {
            Ok(c) => c,
            Err(_) => return,
        };
        for plugin in &self.plugins {
            if !plugin.has_pre_exec {
                continue;
            }
            if plugin.capabilities & yosh_plugin_api::CAP_HOOK_PRE_EXEC == 0 {
                continue;
            }
            let mut ctx = HostContext::new(env, &plugin.name);
            let mut api = build_host_api(plugin.capabilities);
            api.ctx = &mut ctx as *mut HostContext as *mut c_void;
            unsafe {
                if let Ok(hook_fn) = plugin
                    .library
                    .get::<unsafe extern "C" fn(*const HostApi, *const c_char)>(
                        b"yosh_plugin_hook_pre_exec",
                    )
                {
                    hook_fn(&api, c_cmd.as_ptr());
                }
            }
        }
    }

    /// Call post_exec hook on all plugins that have it.
    pub fn call_post_exec(&self, env: &mut ShellEnv, cmd: &str, exit_code: i32) {
        let c_cmd = match CString::new(cmd) {
            Ok(c) => c,
            Err(_) => return,
        };
        for plugin in &self.plugins {
            if !plugin.has_post_exec {
                continue;
            }
            if plugin.capabilities & yosh_plugin_api::CAP_HOOK_POST_EXEC == 0 {
                continue;
            }
            let mut ctx = HostContext::new(env, &plugin.name);
            let mut api = build_host_api(plugin.capabilities);
            api.ctx = &mut ctx as *mut HostContext as *mut c_void;
            unsafe {
                if let Ok(hook_fn) =
                    plugin
                        .library
                        .get::<unsafe extern "C" fn(*const HostApi, *const c_char, i32)>(
                            b"yosh_plugin_hook_post_exec",
                        )
                {
                    hook_fn(&api, c_cmd.as_ptr(), exit_code);
                }
            }
        }
    }

    /// Call on_cd hook on all plugins that have it.
    pub fn call_on_cd(&self, env: &mut ShellEnv, old_dir: &str, new_dir: &str) {
        let c_old = match CString::new(old_dir) {
            Ok(c) => c,
            Err(_) => return,
        };
        let c_new = match CString::new(new_dir) {
            Ok(c) => c,
            Err(_) => return,
        };
        for plugin in &self.plugins {
            if !plugin.has_on_cd {
                continue;
            }
            if plugin.capabilities & yosh_plugin_api::CAP_HOOK_ON_CD == 0 {
                continue;
            }
            let mut ctx = HostContext::new(env, &plugin.name);
            let mut api = build_host_api(plugin.capabilities);
            api.ctx = &mut ctx as *mut HostContext as *mut c_void;
            unsafe {
                if let Ok(hook_fn) =
                    plugin
                        .library
                        .get::<unsafe extern "C" fn(*const HostApi, *const c_char, *const c_char)>(
                            b"yosh_plugin_hook_on_cd",
                        )
                {
                    hook_fn(&api, c_old.as_ptr(), c_new.as_ptr());
                }
            }
        }
    }

    /// Call pre_prompt hook on all plugins that have it.
    pub fn call_pre_prompt(&self, env: &mut ShellEnv) {
        for plugin in &self.plugins {
            if !plugin.has_pre_prompt {
                continue;
            }
            if plugin.capabilities & yosh_plugin_api::CAP_HOOK_PRE_PROMPT == 0 {
                continue;
            }
            let mut ctx = HostContext::new(env, &plugin.name);
            let mut api = build_host_api(plugin.capabilities);
            api.ctx = &mut ctx as *mut HostContext as *mut c_void;
            unsafe {
                if let Ok(hook_fn) = plugin
                    .library
                    .get::<unsafe extern "C" fn(*const HostApi)>(b"yosh_plugin_hook_pre_prompt")
                {
                    hook_fn(&api);
                }
            }
        }
    }

    /// Call destroy on all plugins and drop them.
    pub fn unload_all(&mut self) {
        for plugin in &self.plugins {
            unsafe {
                if let Ok(destroy_fn) = plugin
                    .library
                    .get::<unsafe extern "C" fn()>(b"yosh_plugin_destroy")
                {
                    destroy_fn();
                }
            }
        }
        self.plugins.clear();
    }

    /// Check if any plugin provides the given command.
    pub fn has_command(&self, name: &str) -> bool {
        self.plugins
            .iter()
            .any(|p| p.commands.iter().any(|c| c == name))
    }
}

impl Default for PluginManager {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for PluginManager {
    fn drop(&mut self) {
        self.unload_all();
    }
}

// ── Host context and callbacks ─────────────────────────────────────────

/// Context passed to plugin callbacks via the opaque `ctx` pointer.
struct HostContext<'a> {
    env: &'a mut ShellEnv,
    plugin_name: String,
    /// Buffer for returning C strings from get_var/get_cwd.
    /// Valid until the next callback invocation.
    return_buf: CString,
}

impl<'a> HostContext<'a> {
    fn new(env: &'a mut ShellEnv, plugin_name: &str) -> Self {
        HostContext {
            env,
            plugin_name: plugin_name.to_string(),
            return_buf: CString::default(),
        }
    }
}

unsafe extern "C" fn host_get_var(ctx: *mut c_void, name: *const c_char) -> *const c_char {
    unsafe {
        let host = &mut *(ctx as *mut HostContext);
        let name = match CStr::from_ptr(name).to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null(),
        };
        match host.env.vars.get(name) {
            Some(val) => {
                host.return_buf = CString::new(val).unwrap_or_default();
                host.return_buf.as_ptr()
            }
            None => std::ptr::null(),
        }
    }
}

unsafe extern "C" fn host_set_var(
    ctx: *mut c_void,
    name: *const c_char,
    value: *const c_char,
) -> i32 {
    unsafe {
        let host = &mut *(ctx as *mut HostContext);
        let name = match CStr::from_ptr(name).to_str() {
            Ok(s) => s,
            Err(_) => return 1,
        };
        let value = match CStr::from_ptr(value).to_str() {
            Ok(s) => s,
            Err(_) => return 1,
        };
        match host.env.vars.set(name, value) {
            Ok(()) => 0,
            Err(_) => 1,
        }
    }
}

unsafe extern "C" fn host_export_var(
    ctx: *mut c_void,
    name: *const c_char,
    value: *const c_char,
) -> i32 {
    unsafe {
        let host = &mut *(ctx as *mut HostContext);
        let name = match CStr::from_ptr(name).to_str() {
            Ok(s) => s,
            Err(_) => return 1,
        };
        let value = match CStr::from_ptr(value).to_str() {
            Ok(s) => s,
            Err(_) => return 1,
        };
        match host.env.vars.set(name, value) {
            Ok(()) => {
                host.env.vars.export(name);
                0
            }
            Err(_) => 1,
        }
    }
}

unsafe extern "C" fn host_get_cwd(ctx: *mut c_void) -> *const c_char {
    unsafe {
        let host = &mut *(ctx as *mut HostContext);
        match std::env::current_dir() {
            Ok(cwd) => {
                host.return_buf = CString::new(cwd.to_string_lossy().as_ref()).unwrap_or_default();
                host.return_buf.as_ptr()
            }
            Err(_) => std::ptr::null(),
        }
    }
}

unsafe extern "C" fn host_set_cwd(_ctx: *mut c_void, path: *const c_char) -> i32 {
    unsafe {
        let path = match CStr::from_ptr(path).to_str() {
            Ok(s) => s,
            Err(_) => return 1,
        };
        match std::env::set_current_dir(path) {
            Ok(()) => 0,
            Err(_) => 1,
        }
    }
}

unsafe extern "C" fn host_write_stdout(_ctx: *mut c_void, data: *const c_char, len: usize) -> i32 {
    unsafe {
        let slice = std::slice::from_raw_parts(data as *const u8, len);
        match std::io::stdout().write_all(slice) {
            Ok(()) => 0,
            Err(_) => 1,
        }
    }
}

unsafe extern "C" fn host_write_stderr(_ctx: *mut c_void, data: *const c_char, len: usize) -> i32 {
    unsafe {
        let slice = std::slice::from_raw_parts(data as *const u8, len);
        match std::io::stderr().write_all(slice) {
            Ok(()) => 0,
            Err(_) => 1,
        }
    }
}

// ── Deny functions for sandboxed capabilities ─────────────────────────

unsafe extern "C" fn deny_get_var(ctx: *mut c_void, _name: *const c_char) -> *const c_char {
    unsafe {
        let host = &*(ctx as *mut HostContext);
        eprintln!(
            "yosh: plugin '{}': get_var denied (missing 'variables:read' capability)",
            host.plugin_name
        );
    }
    std::ptr::null()
}

unsafe extern "C" fn deny_set_var(
    ctx: *mut c_void,
    _name: *const c_char,
    _value: *const c_char,
) -> i32 {
    unsafe {
        let host = &*(ctx as *mut HostContext);
        eprintln!(
            "yosh: plugin '{}': set_var denied (missing 'variables:write' capability)",
            host.plugin_name
        );
    }
    -1
}

unsafe extern "C" fn deny_export_var(
    ctx: *mut c_void,
    _name: *const c_char,
    _value: *const c_char,
) -> i32 {
    unsafe {
        let host = &*(ctx as *mut HostContext);
        eprintln!(
            "yosh: plugin '{}': export_var denied (missing 'variables:write' capability)",
            host.plugin_name
        );
    }
    -1
}

unsafe extern "C" fn deny_get_cwd(ctx: *mut c_void) -> *const c_char {
    unsafe {
        let host = &*(ctx as *mut HostContext);
        eprintln!(
            "yosh: plugin '{}': get_cwd denied (missing 'filesystem' capability)",
            host.plugin_name
        );
    }
    std::ptr::null()
}

unsafe extern "C" fn deny_set_cwd(ctx: *mut c_void, _path: *const c_char) -> i32 {
    unsafe {
        let host = &*(ctx as *mut HostContext);
        eprintln!(
            "yosh: plugin '{}': set_cwd denied (missing 'filesystem' capability)",
            host.plugin_name
        );
    }
    -1
}

unsafe extern "C" fn deny_write_stdout(ctx: *mut c_void, _data: *const c_char, _len: usize) -> i32 {
    unsafe {
        let host = &*(ctx as *mut HostContext);
        eprintln!(
            "yosh: plugin '{}': write_stdout denied (missing 'io' capability)",
            host.plugin_name
        );
    }
    -1
}

unsafe extern "C" fn deny_write_stderr(ctx: *mut c_void, _data: *const c_char, _len: usize) -> i32 {
    unsafe {
        let host = &*(ctx as *mut HostContext);
        eprintln!(
            "yosh: plugin '{}': write_stderr denied (missing 'io' capability)",
            host.plugin_name
        );
    }
    -1
}

/// Build a HostApi table for a plugin based on its effective capabilities.
/// Denied functions are replaced with stubs that log and return errors.
fn build_host_api(capabilities: u32) -> HostApi {
    use yosh_plugin_api::*;

    let has = |cap: u32| capabilities & cap != 0;

    HostApi {
        ctx: std::ptr::null_mut(),
        get_var: if has(CAP_VARIABLES_READ) {
            host_get_var
        } else {
            deny_get_var
        },
        set_var: if has(CAP_VARIABLES_WRITE) {
            host_set_var
        } else {
            deny_set_var
        },
        export_var: if has(CAP_VARIABLES_WRITE) {
            host_export_var
        } else {
            deny_export_var
        },
        get_cwd: if has(CAP_FILESYSTEM) {
            host_get_cwd
        } else {
            deny_get_cwd
        },
        set_cwd: if has(CAP_FILESYSTEM) {
            host_set_cwd
        } else {
            deny_set_cwd
        },
        write_stdout: if has(CAP_IO) {
            host_write_stdout
        } else {
            deny_write_stdout
        },
        write_stderr: if has(CAP_IO) {
            host_write_stderr
        } else {
            deny_write_stderr
        },
    }
}