Skip to main content

tilo_process/
login_shell.rs

1/// The shell this account's terminal starts: **`$SHELL`** when it names a
2/// program this account can run (the person's preference, and how fish starts
3/// here when it is the login shell), then the login shell the passwd database
4/// records when that runs, then **`/bin/sh`** — a shell a person has since
5/// uninstalled never leaves them without a terminal. Windows uses `COMSPEC`,
6/// falling back to `cmd.exe`.
7#[must_use]
8pub fn login_shell() -> String {
9    #[cfg(windows)]
10    {
11        std::env::var("COMSPEC")
12            .ok()
13            .filter(|shell| !shell.trim().is_empty())
14            .unwrap_or_else(|| "cmd.exe".into())
15    }
16    #[cfg(unix)]
17    {
18        login_shell_with(
19            std::env::var("SHELL").ok(),
20            login_shell_from_passwd(),
21            crate::tools::runs,
22        )
23    }
24    #[cfg(not(any(unix, windows)))]
25    {
26        "/bin/sh".into()
27    }
28}
29
30/// [`login_shell`] with its sources and the program check injected, testable
31/// without mutating process-global state (which would race parallel tests).
32#[cfg(unix)]
33#[must_use]
34pub fn login_shell_with(
35    shell_env: Option<String>,
36    passwd_shell: Option<String>,
37    runs: impl Fn(&str) -> bool,
38) -> String {
39    let named = |shell: Option<String>| shell.filter(|shell| !shell.is_empty() && runs(shell));
40    named(shell_env)
41        .or_else(|| named(passwd_shell))
42        .unwrap_or_else(|| "/bin/sh".into())
43}
44
45#[cfg(unix)]
46#[must_use]
47pub fn login_shell_from_passwd() -> Option<String> {
48    use std::ffi::CStr;
49    // SAFETY: `getpwuid` returns a pointer into a static buffer owned by libc
50    // (valid until the next passwd call, of which we make none before copying
51    // out); both pointers are null-checked and the shell is copied out while
52    // live.
53    unsafe {
54        let pw = libc::getpwuid(crate::uid());
55        if pw.is_null() || (*pw).pw_shell.is_null() {
56            return None;
57        }
58        Some(
59            CStr::from_ptr((*pw).pw_shell)
60                .to_string_lossy()
61                .into_owned(),
62        )
63    }
64}
65
66#[cfg(all(test, unix))]
67mod tests {
68    use super::*;
69
70    fn has(shells: &'static [&'static str]) -> impl Fn(&str) -> bool {
71        move |shell| shells.contains(&shell)
72    }
73
74    #[test]
75    fn the_shell_env_wins_then_the_passwd_shell_then_sh() {
76        let fish = || Some("/usr/bin/fish".to_owned());
77        let zsh = || Some("/usr/bin/zsh".to_owned());
78        let bash = || Some("/bin/bash".to_owned());
79        assert_eq!(
80            login_shell_with(fish(), bash(), has(&["/usr/bin/fish"])),
81            "/usr/bin/fish",
82            "$SHELL wins when it is set and can run"
83        );
84        assert_eq!(
85            login_shell_with(None, zsh(), has(&["/usr/bin/zsh"])),
86            "/usr/bin/zsh",
87            "with $SHELL unset the recorded login shell starts, not /bin/sh"
88        );
89        assert_eq!(
90            login_shell_with(Some(String::new()), zsh(), has(&["/usr/bin/zsh"])),
91            "/usr/bin/zsh"
92        );
93        assert_eq!(
94            login_shell_with(fish(), bash(), has(&["/bin/bash"])),
95            "/bin/bash"
96        );
97        assert_eq!(login_shell_with(fish(), None, has(&[])), "/bin/sh");
98        let passwd = login_shell_from_passwd().expect("this account has a login shell recorded");
99        assert!(
100            passwd.starts_with('/'),
101            "the passwd login shell is absolute: {passwd:?}"
102        );
103        assert!(crate::tools::runs("/bin/sh"));
104        assert!(crate::tools::runs("sh"), "a bare name is looked up in PATH");
105        assert!(!crate::tools::runs("/nonexistent/uninstalled-shell"));
106        assert!(!crate::tools::runs("tilo-no-such-program"));
107    }
108}