yash_cli/startup/
init_file.rs

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
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2024 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Running initialization files
//!
//! This module provides functions for running initialization files in the shell.
//! The initialization file is a script that is executed when the shell starts up.
//!
//! Currently, this module only supports running the POSIX-defined rcfile, whose
//! path is determined by the value of the `ENV` environment variable.
//! (TODO: Support for yash-specific initialization files will be added later.)
//!
//! The [`run_rcfile`] function is the main entry point for running the rcfile.
//! Helper functions that are used by `run_rcfile` are also provided in this
//! module.

use super::args::InitFile;
use std::cell::RefCell;
use std::ffi::CString;
use std::num::NonZeroU64;
use std::rc::Rc;
use thiserror::Error;
use yash_env::input::{Echo, FdReader};
use yash_env::io::Fd;
use yash_env::option::Option::Interactive;
use yash_env::option::State::Off;
use yash_env::stack::Frame;
use yash_env::system::{Errno, Mode, OfdAccess, OpenFlag, SystemEx};
use yash_env::variable::ENV;
use yash_env::Env;
use yash_env::System;
use yash_semantics::expansion::expand_text;
use yash_semantics::read_eval_loop;
use yash_semantics::Handle;
use yash_syntax::parser::lex::Lexer;
use yash_syntax::source::Source;

/// Errors that can occur when finding the default initialization file path
#[derive(Clone, Debug, Error, PartialEq)]
#[error(transparent)]
pub enum DefaultFilePathError {
    /// An error occurred while parsing the value of a variable specifying the
    /// initialization file path
    ParseError(#[from] yash_syntax::parser::Error),
    /// An error occurred while expanding the value of a variable specifying
    /// the initialization file path
    ExpansionError(#[from] yash_semantics::expansion::Error),
}

impl Handle for DefaultFilePathError {
    async fn handle(&self, env: &mut Env) -> yash_semantics::Result {
        match self {
            DefaultFilePathError::ParseError(e) => e.handle(env).await,
            DefaultFilePathError::ExpansionError(e) => e.handle(env).await,
        }
    }
}

/// Finds the path to the default rcfile.
///
/// The default path is determined by the value of the [`ENV`] environment
/// variable. The value is parsed as a [`Text`] and subjected to the
/// [initial expansion].
///
/// If the variable does not exist or is empty, the result will be an empty
/// string.
///
/// If the variable value cannot be parsed or expanded, an error message will
/// be printed to the standard error and an empty string will be returned.
///
/// TODO: If the POSIXly correct mode is off, the default path should be
/// `~/.yashrc` (or maybe some XDG-compliant path).
///
/// [`ENV`]: yash_env::variable::ENV
/// [`Text`]: yash_syntax::syntax::Text
/// [initial expansion]: yash_semantics::expansion::initial
pub async fn default_rcfile_path(env: &mut Env) -> Result<String, DefaultFilePathError> {
    let raw_value = env.variables.get_scalar(ENV).unwrap_or_default();

    let text = {
        let name = ENV.to_owned();
        let source = Source::VariableValue { name };
        let mut lexer = Lexer::from_memory(raw_value, source);
        lexer.text(|_| false, |_| false).await?
    };

    Ok(expand_text(env, &text).await?.0)
}

/// Resolves the path to the rcfile.
///
/// This function resolves the path to the rcfile specified by the `file`
/// argument. If the file is `InitFile::Default`, the default rcfile path is
/// determined by calling [`default_rcfile_path`].
///
/// This function returns an empty string in the following cases, in which
/// case the rcfile should not be executed:
///
/// - `file` is `InitFile::None`,
/// - the `Interactive` shell option is off,
/// - the real user ID of the process is not the same as the effective user ID, or
/// - the real group ID of the process is not the same as the effective group ID.
pub async fn resolve_rcfile_path(
    env: &mut Env,
    file: InitFile,
) -> Result<String, DefaultFilePathError> {
    if file == InitFile::None
        || env.options.get(Interactive) == Off
        || env.system.getuid() != env.system.geteuid()
        || env.system.getgid() != env.system.getegid()
    {
        return Ok(String::default());
    }

    match file {
        InitFile::None => unreachable!(),
        InitFile::Default => default_rcfile_path(env).await,
        InitFile::File { path } => Ok(path),
    }
}

/// Runs an initialization file, reading from the specified path.
///
/// This function reads the contents of the initialization file and executes
/// them in the current shell environment. The file is specified by the `path`
/// argument.
///
/// If `path` is an empty string, the function returns immediately.
pub async fn run_init_file(env: &mut Env, path: &str) {
    if path.is_empty() {
        return;
    }

    fn open_fd<S: System>(system: &mut S, path: String) -> Result<Fd, Errno> {
        let c_path = CString::new(path).map_err(|_| Errno::EILSEQ)?;
        let fd = system.open(
            &c_path,
            OfdAccess::ReadOnly,
            OpenFlag::CloseOnExec.into(),
            Mode::empty(),
        )?;
        system.move_fd_internal(fd)
    }

    let fd = match open_fd(&mut env.system, path.to_owned()) {
        Ok(fd) => fd,
        Err(errno) => {
            env.system
                .print_error(&format!(
                    "{}: cannot open initialization file {path:?}: {errno}\n",
                    &env.arg0
                ))
                .await;
            return;
        }
    };

    let env = &mut *env.push_frame(Frame::InitFile);
    let system = env.system.clone();
    let ref_env = RefCell::new(&mut *env);
    let input = Box::new(Echo::new(FdReader::new(fd, system), &ref_env));
    let start_line_number = NonZeroU64::MIN;
    let source = Rc::new(Source::InitFile {
        path: path.to_owned(),
    });
    let mut lexer = Lexer::new(input, start_line_number, source);
    read_eval_loop(&ref_env, &mut { lexer }).await;

    if let Err(errno) = env.system.close(fd) {
        env.system
            .print_error(&format!(
                "{}: cannot close initialization file {path:?}: {errno}\n",
                &env.arg0
            ))
            .await;
    }
}

/// Runs the rcfile specified by the `file` argument.
///
/// This function resolves the path to the rcfile using [`resolve_rcfile_path`]
/// and then runs the rcfile using [`run_init_file`]. Any errors resolving the
/// path are reported to the standard error.
pub async fn run_rcfile(env: &mut Env, file: InitFile) {
    match resolve_rcfile_path(env, file).await {
        Ok(path) => run_init_file(env, &path).await,
        Err(e) => drop(e.handle(env).await),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;
    use futures_util::FutureExt as _;
    use yash_env::option::State::On;
    use yash_env::system::{Gid, Uid};
    use yash_env::variable::Scope::Global;
    use yash_env::VirtualSystem;

    #[test]
    fn default_rcfile_path_with_unset_env() {
        let mut env = Env::new_virtual();
        let result = default_rcfile_path(&mut env).now_or_never().unwrap();
        assert_eq!(result.unwrap(), "");
    }

    #[test]
    fn default_rcfile_path_with_empty_env() {
        let mut env = Env::new_virtual();
        env.variables
            .get_or_new(ENV, Global)
            .assign("", None)
            .unwrap();
        let result = default_rcfile_path(&mut env).now_or_never().unwrap();
        assert_eq!(result.unwrap(), "");
    }

    #[test]
    fn default_rcfile_path_with_env_without_expansion() {
        let mut env = Env::new_virtual();
        env.variables
            .get_or_new(ENV, Global)
            .assign("foo", None)
            .unwrap();
        let result = default_rcfile_path(&mut env).now_or_never().unwrap();
        assert_eq!(result.unwrap(), "foo");
    }

    #[test]
    fn default_rcfile_path_with_env_with_unparsable_expansion() {
        let mut env = Env::new_virtual();
        env.variables
            .get_or_new(ENV, Global)
            .assign("foo${bar", None)
            .unwrap();
        let result = default_rcfile_path(&mut env).now_or_never().unwrap();
        assert_matches!(result, Err(DefaultFilePathError::ParseError(_)));
    }

    #[test]
    fn default_rcfile_path_with_env_with_failing_expansion() {
        let mut env = Env::new_virtual();
        env.variables
            .get_or_new(ENV, Global)
            .assign("${unset?}", None)
            .unwrap();
        let result = default_rcfile_path(&mut env).now_or_never().unwrap();
        assert_matches!(result, Err(DefaultFilePathError::ExpansionError(_)));
    }

    #[test]
    fn resolve_rcfile_path_none() {
        let mut env = Env::new_virtual();
        env.options.set(Interactive, On);
        let result = resolve_rcfile_path(&mut env, InitFile::None)
            .now_or_never()
            .unwrap();
        assert_eq!(result.unwrap(), "");
    }

    #[test]
    fn resolve_rcfile_path_default() {
        let mut env = Env::new_virtual();
        env.options.set(Interactive, On);
        env.variables
            .get_or_new(ENV, Global)
            .assign("foo/bar", None)
            .unwrap();
        let result = resolve_rcfile_path(&mut env, InitFile::Default)
            .now_or_never()
            .unwrap();
        assert_eq!(result.unwrap(), "foo/bar");
    }

    #[test]
    fn resolve_rcfile_path_exact() {
        let mut env = Env::new_virtual();
        env.options.set(Interactive, On);
        let path = "/path/to/rcfile".to_string();
        let file = InitFile::File { path };
        let result = resolve_rcfile_path(&mut env, file).now_or_never().unwrap();
        assert_eq!(result.unwrap(), "/path/to/rcfile");
    }

    #[test]
    fn resolve_rcfile_path_non_interactive() {
        let mut env = Env::new_virtual();
        env.options.set(Interactive, Off);
        let path = "/path/to/rcfile".to_string();
        let file = InitFile::File { path };
        let result = resolve_rcfile_path(&mut env, file).now_or_never().unwrap();
        assert_eq!(result.unwrap(), "");
    }

    #[test]
    fn resolve_rcfile_path_non_real_user() {
        let mut system = Box::new(VirtualSystem::new());
        system.current_process_mut().set_uid(Uid(0));
        system.current_process_mut().set_euid(Uid(10));
        let mut env = Env::with_system(system);
        env.options.set(Interactive, On);
        let path = "/path/to/rcfile".to_string();
        let file = InitFile::File { path };
        let result = resolve_rcfile_path(&mut env, file).now_or_never().unwrap();
        assert_eq!(result.unwrap(), "");
    }

    #[test]
    fn resolve_rcfile_path_non_real_group() {
        let mut system = Box::new(VirtualSystem::new());
        system.current_process_mut().set_gid(Gid(0));
        system.current_process_mut().set_egid(Gid(10));
        let mut env = Env::with_system(system);
        env.options.set(Interactive, On);
        let path = "/path/to/rcfile".to_string();
        let file = InitFile::File { path };
        let result = resolve_rcfile_path(&mut env, file).now_or_never().unwrap();
        assert_eq!(result.unwrap(), "");
    }
}