summaryrefslogtreecommitdiffstats
path: root/src/builtins.rs
blob: 638496bd8d496074a94e36e7303cecad5efcaeca (plain) (blame)
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
use async_std::io::{ReadExt as _, WriteExt as _};
use std::os::unix::io::{AsRawFd as _, FromRawFd as _, IntoRawFd as _};
use std::os::unix::process::ExitStatusExt as _;

struct Io {
    fds: std::collections::HashMap<
        std::os::unix::io::RawFd,
        std::os::unix::io::RawFd,
    >,
    pre_exec: Option<
        Box<dyn 'static + FnMut() -> std::io::Result<()> + Send + Sync>,
    >,
}

impl Io {
    fn new() -> Self {
        let mut fds = std::collections::HashMap::new();
        fds.insert(0.as_raw_fd(), 0.as_raw_fd());
        fds.insert(1.as_raw_fd(), 1.as_raw_fd());
        fds.insert(2.as_raw_fd(), 2.as_raw_fd());
        Self {
            fds,
            pre_exec: None,
        }
    }

    fn stdin(&self) -> Option<async_std::fs::File> {
        self.fds
            .get(&0.as_raw_fd())
            .copied()
            .map(|fd| unsafe { async_std::fs::File::from_raw_fd(fd) })
    }

    fn set_stdin<T: std::os::unix::io::IntoRawFd>(&mut self, stdin: T) {
        if let Some(fd) = self.fds.get(&0.as_raw_fd()) {
            if *fd > 2 {
                drop(unsafe { async_std::fs::File::from_raw_fd(*fd) });
            }
        }
        self.fds.insert(0.as_raw_fd(), stdin.into_raw_fd());
    }

    fn stdout(&self) -> Option<async_std::fs::File> {
        self.fds
            .get(&1.as_raw_fd())
            .copied()
            .map(|fd| unsafe { async_std::fs::File::from_raw_fd(fd) })
    }

    fn set_stdout<T: std::os::unix::io::IntoRawFd>(&mut self, stdout: T) {
        if let Some(fd) = self.fds.get(&1.as_raw_fd()) {
            if *fd > 2 {
                drop(unsafe { async_std::fs::File::from_raw_fd(*fd) });
            }
        }
        self.fds.insert(1.as_raw_fd(), stdout.into_raw_fd());
    }

    fn stderr(&self) -> Option<async_std::fs::File> {
        self.fds
            .get(&2.as_raw_fd())
            .copied()
            .map(|fd| unsafe { async_std::fs::File::from_raw_fd(fd) })
    }

    fn set_stderr<T: std::os::unix::io::IntoRawFd>(&mut self, stderr: T) {
        if let Some(fd) = self.fds.get(&2.as_raw_fd()) {
            if *fd > 2 {
                drop(unsafe { async_std::fs::File::from_raw_fd(*fd) });
            }
        }
        self.fds.insert(2.as_raw_fd(), stderr.into_raw_fd());
    }

    pub unsafe fn pre_exec<F>(&mut self, f: F)
    where
        F: 'static + FnMut() -> std::io::Result<()> + Send + Sync,
    {
        self.pre_exec = Some(Box::new(f));
    }

    async fn read_stdin(&self, buf: &mut [u8]) -> anyhow::Result<usize> {
        if let Some(mut fh) = self.stdin() {
            let res = fh.read(buf).await;
            let _ = fh.into_raw_fd();
            Ok(res?)
        } else {
            Ok(0)
        }
    }

    async fn write_stdout(&self, buf: &[u8]) -> anyhow::Result<()> {
        if let Some(mut fh) = self.stdout() {
            let res = fh.write_all(buf).await;
            let _ = fh.into_raw_fd();
            Ok(res.map(|_| ())?)
        } else {
            Ok(())
        }
    }

    async fn write_stderr(&self, buf: &[u8]) -> anyhow::Result<()> {
        if let Some(mut fh) = self.stderr() {
            let res = fh.write_all(buf).await;
            let _ = fh.into_raw_fd();
            Ok(res.map(|_| ())?)
        } else {
            Ok(())
        }
    }

    fn setup_command(mut self, cmd: &mut crate::command::Command) {
        if let Some(stdin) = self.stdin() {
            let stdin = stdin.into_raw_fd();
            if stdin != 0 {
                cmd.stdin(unsafe { std::fs::File::from_raw_fd(stdin) });
                self.fds.remove(&0.as_raw_fd());
            }
        }
        if let Some(stdout) = self.stdout() {
            let stdout = stdout.into_raw_fd();
            if stdout != 1 {
                cmd.stdout(unsafe { std::fs::File::from_raw_fd(stdout) });
                self.fds.remove(&1.as_raw_fd());
            }
        }
        if let Some(stderr) = self.stderr() {
            let stderr = stderr.into_raw_fd();
            if stderr != 2 {
                cmd.stderr(unsafe { std::fs::File::from_raw_fd(stderr) });
                self.fds.remove(&2.as_raw_fd());
            }
        }
        if let Some(pre_exec) = self.pre_exec.take() {
            unsafe { cmd.pre_exec(pre_exec) };
        }
    }
}

impl Drop for Io {
    fn drop(&mut self) {
        for fd in self.fds.values() {
            if *fd > 2 {
                drop(unsafe { std::fs::File::from_raw_fd(*fd) });
            }
        }
    }
}

type Builtin = &'static (dyn Fn(
    &crate::parse::Exe,
    &crate::command::Env,
    Io,
) -> anyhow::Result<Child>
              + Sync
              + Send);

#[allow(clippy::as_conversions)]
static BUILTINS: once_cell::sync::Lazy<
    std::collections::HashMap<&'static str, Builtin>,
> = once_cell::sync::Lazy::new(|| {
    let mut builtins = std::collections::HashMap::new();
    builtins.insert("cd", &cd as Builtin);
    builtins.insert("echo", &echo);
    builtins.insert("and", &and);
    builtins.insert("or", &or);
    builtins.insert("command", &command);
    builtins.insert("builtin", &builtin);
    builtins
});

pub struct Command {
    exe: crate::parse::Exe,
    f: Builtin,
    io: Io,
}

impl Command {
    pub fn new(exe: &crate::parse::Exe) -> Option<Self> {
        BUILTINS.get(exe.exe()).map(|f| Self {
            exe: exe.clone(),
            f,
            io: Io::new(),
        })
    }

    pub fn stdin(&mut self, fh: std::fs::File) {
        self.io.set_stdin(fh);
    }

    pub fn stdout(&mut self, fh: std::fs::File) {
        self.io.set_stdout(fh);
    }

    pub fn stderr(&mut self, fh: std::fs::File) {
        self.io.set_stderr(fh);
    }

    pub unsafe fn pre_exec<F>(&mut self, f: F)
    where
        F: 'static + FnMut() -> std::io::Result<()> + Send + Sync,
    {
        self.io.pre_exec(f);
    }

    pub fn spawn(self, env: &crate::command::Env) -> anyhow::Result<Child> {
        let Self { f, exe, io } = self;
        (f)(&exe, env, io)
    }
}

pub struct Child {
    fut: std::pin::Pin<
        Box<
            dyn std::future::Future<Output = std::process::ExitStatus>
                + Sync
                + Send,
        >,
    >,
    wrapped_child: Option<Box<crate::command::Child>>,
}

impl Child {
    pub fn id(&self) -> Option<u32> {
        self.wrapped_child.as_ref().and_then(|cmd| cmd.id())
    }

    #[async_recursion::async_recursion]
    pub async fn status(
        self,
    ) -> anyhow::Result<async_std::process::ExitStatus> {
        if let Some(child) = self.wrapped_child {
            child.status().await
        } else {
            Ok(self.fut.await)
        }
    }
}

// clippy can't tell that the type is necessary
#[allow(clippy::unnecessary_wraps)]
fn cd(
    exe: &crate::parse::Exe,
    env: &crate::command::Env,
    io: Io,
) -> anyhow::Result<Child> {
    async fn async_cd(
        exe: &crate::parse::Exe,
        _env: &crate::command::Env,
        io: Io,
    ) -> std::process::ExitStatus {
        let dir = exe
            .args()
            .into_iter()
            .map(std::convert::AsRef::as_ref)
            .next()
            .unwrap_or("");

        let dir = if dir.is_empty() {
            home()
        } else if dir.starts_with('~') {
            let path: std::path::PathBuf = dir.into();
            if let std::path::Component::Normal(prefix) =
                path.components().next().unwrap()
            {
                if prefix.to_str() == Some("~") {
                    home().join(path.strip_prefix(prefix).unwrap())
                } else {
                    // TODO
                    io.write_stderr(b"unimplemented\n").await.unwrap();
                    return async_std::process::ExitStatus::from_raw(1 << 8);
                }
            } else {
                unreachable!()
            }
        } else {
            dir.into()
        };
        let code = match std::env::set_current_dir(&dir) {
            Ok(()) => 0,
            Err(e) => {
                io.write_stderr(
                    format!(
                        "{}: {}: {}\n",
                        exe.exe(),
                        crate::format::io_error(&e),
                        dir.display()
                    )
                    .as_bytes(),
                )
                .await
                .unwrap();
                1
            }
        };
        async_std::process::ExitStatus::from_raw(code << 8)
    }

    let exe = exe.clone();
    let env = env.clone();
    Ok(Child {
        fut: Box::pin(async move { async_cd(&exe, &env, io).await }),
        wrapped_child: None,
    })
}

// clippy can't tell that the type is necessary
#[allow(clippy::unnecessary_wraps)]
// mostly just for testing and ensuring that builtins work, i'll likely remove
// this later, since the binary seems totally fine
fn echo(
    exe: &crate::parse::Exe,
    env: &crate::command::Env,
    io: Io,
) -> anyhow::Result<Child> {
    async fn async_echo(
        exe: &crate::parse::Exe,
        _env: &crate::command::Env,
        io: Io,
    ) -> std::process::ExitStatus {
        macro_rules! write_stdout {
            ($bytes:expr) => {
                if let Err(e) = io.write_stdout($bytes).await {
                    io.write_stderr(format!("echo: {}", e).as_bytes())
                        .await
                        .unwrap();
                    return async_std::process::ExitStatus::from_raw(1 << 8);
                }
            };
        }
        let count = exe.args().count();
        for (i, arg) in exe.args().enumerate() {
            write_stdout!(arg.as_bytes());
            if i == count - 1 {
                write_stdout!(b"\n");
            } else {
                write_stdout!(b" ");
            }
        }

        async_std::process::ExitStatus::from_raw(0)
    }

    let exe = exe.clone();
    let env = env.clone();
    Ok(Child {
        fut: Box::pin(async move { async_echo(&exe, &env, io).await }),
        wrapped_child: None,
    })
}

fn and(
    exe: &crate::parse::Exe,
    env: &crate::command::Env,
    io: Io,
) -> anyhow::Result<Child> {
    let exe = exe.shift();
    if env.latest_status().success() {
        let mut cmd = crate::command::Command::new(&exe);
        io.setup_command(&mut cmd);
        Ok(Child {
            fut: Box::pin(async move { unreachable!() }),
            wrapped_child: Some(Box::new(cmd.spawn(env)?)),
        })
    } else {
        let env = env.clone();
        Ok(Child {
            fut: Box::pin(async move { *env.latest_status() }),
            wrapped_child: None,
        })
    }
}

fn or(
    exe: &crate::parse::Exe,
    env: &crate::command::Env,
    io: Io,
) -> anyhow::Result<Child> {
    let exe = exe.shift();
    if env.latest_status().success() {
        let env = env.clone();
        Ok(Child {
            fut: Box::pin(async move { *env.latest_status() }),
            wrapped_child: None,
        })
    } else {
        let mut cmd = crate::command::Command::new(&exe);
        io.setup_command(&mut cmd);
        Ok(Child {
            fut: Box::pin(async move { unreachable!() }),
            wrapped_child: Some(Box::new(cmd.spawn(env)?)),
        })
    }
}

fn command(
    exe: &crate::parse::Exe,
    env: &crate::command::Env,
    io: Io,
) -> anyhow::Result<Child> {
    let exe = exe.shift();
    let mut cmd = crate::command::Command::new_binary(&exe);
    io.setup_command(&mut cmd);
    Ok(Child {
        fut: Box::pin(async move { unreachable!() }),
        wrapped_child: Some(Box::new(cmd.spawn(env)?)),
    })
}

fn builtin(
    exe: &crate::parse::Exe,
    env: &crate::command::Env,
    io: Io,
) -> anyhow::Result<Child> {
    let exe = exe.shift();
    let mut cmd = crate::command::Command::new_builtin(&exe);
    io.setup_command(&mut cmd);
    Ok(Child {
        fut: Box::pin(async move { unreachable!() }),
        wrapped_child: Some(Box::new(cmd.spawn(env)?)),
    })
}

fn home() -> std::path::PathBuf {
    std::env::var_os("HOME").unwrap().into()
}