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
#![cfg_attr(feature = "strict", deny(warnings))]
#![cfg_attr(feature = "strict", deny(missing_docs))]

//! bigbro is a crate that enables running external commands and
//! tracking their use of the filesystem.  It currently only works
//! under linux.
//!
//! # Example
//!
//! ```
//! let status = bigbro::Command::new("cargo")
//!                             .args(&["--version"])
//!                             .status().unwrap();
//! for f in status.read_from_files() {
//!    println!("read file: {}", f.to_string_lossy());
//! }
//! ```
extern crate libc;

use std;

use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
use std::io;
use std::io::Write;

pub const WORKS: bool = false;

#[derive(Debug)]
pub struct Child {
    inner: Option<std::process::Child>,
    want_stdouterr: bool,
    log_stdouterr: Option<PathBuf>,
}

impl Child {
    pub fn kill(&mut self) -> std::io::Result<()> {
        if let Some(mut c) = self.inner.take() {
            c.kill()
        } else {
            Ok(())
        }
    }
    /// Ask the child process to exit
    pub fn terminate(&mut self) -> std::io::Result<()> {
        self.kill()
    }
    /// Wait for child to finish
    pub fn wait(&mut self) -> std::io::Result<Status> {
        if let Some(mut child) = self.inner.take() {
            if self.want_stdouterr {
                let s = child.wait_with_output()?;
                if let Some(ref p) = self.log_stdouterr {
                    let mut f = std::fs::File::create(p)?;
                    f.write(&s.stdout)?;
                }
                Ok(Status {
                    status: s.status,
                    read_from_directories: std::collections::HashSet::new(),
                    read_from_files: std::collections::HashSet::new(),
                    written_to_files: std::collections::HashSet::new(),
                    mkdir_directories: std::collections::HashSet::new(),
                    stdout_fd: Some(s.stdout),
                })
            } else {
                let s = child.wait()?;
                Ok(Status {
                    status: s,
                    read_from_directories: std::collections::HashSet::new(),
                    read_from_files: std::collections::HashSet::new(),
                    written_to_files: std::collections::HashSet::new(),
                    mkdir_directories: std::collections::HashSet::new(),
                    stdout_fd: None,
                })
            }
        } else {
            Err(io::Error::new(io::ErrorKind::Other,"already used up child"))
        }
    }
    /// Check if the child has finished
    pub fn try_wait(&mut self) -> std::io::Result<Option<Status>> {
        unimplemented!()
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Killer {
}

impl Killer {
    pub fn kill(&mut self) -> std::io::Result<()> {
        Err(io::Error::new(io::ErrorKind::Other,"Killer not implemented generically"))
    }
    /// Ask the child process to exit
    pub fn terminate(&mut self) -> std::io::Result<()> {
        self.kill()
    }
}

/// The result of running a command using bigbro.
///
/// It contains the
/// ExitStatus as well as the information about files and directories
/// accessed by the command.
#[derive(Debug)]
pub struct Status {
    status: std::process::ExitStatus,
    read_from_directories: std::collections::HashSet<PathBuf>,
    read_from_files: std::collections::HashSet<PathBuf>,
    written_to_files: std::collections::HashSet<PathBuf>,
    mkdir_directories: std::collections::HashSet<PathBuf>,
    stdout_fd: Option<Vec<u8>>,
}

impl Status {
    pub fn status(&self) -> std::process::ExitStatus {
        self.status
    }
    pub fn read_from_directories(&self) -> std::collections::HashSet<PathBuf> {
       self.read_from_directories.clone()
    }
    pub fn read_from_files(&self) -> std::collections::HashSet<PathBuf> {
        self.read_from_files.clone()
    }
    pub fn written_to_files(&self) -> std::collections::HashSet<PathBuf> {
        self.written_to_files.clone()
    }
    pub fn mkdir_directories(&self) -> std::collections::HashSet<PathBuf> {
        self.mkdir_directories.clone()
    }
    pub fn stdout(&mut self) -> std::io::Result<Option<Box<std::io::Read>>> {
        if let Some(f) = self.stdout_fd.take() {
            return Ok(Some(Box::new(std::io::Cursor::new(f))));
        }
        Ok(None)
    }
}

pub struct Command {
    cmd: std::process::Command,
    want_stdouterr: bool,
    log_stdouterr: Option<std::path::PathBuf>,
}

impl Command {
    pub fn new<S: AsRef<std::ffi::OsStr>>(program: S) -> Command {
        Command {
            cmd: std::process::Command::new(program),
            want_stdouterr: false,
            log_stdouterr: None,
        }
    }

    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) {
        self.cmd.arg(arg);
    }
    pub fn current_dir<P: AsRef<std::path::Path>>(&mut self, dir: P) {
        self.cmd.current_dir(dir);
    }

    pub fn stdin(&mut self, cfg: Stdio) {
        self.cmd.stdin(to_io(cfg));
    }
    pub fn stdout(&mut self, cfg: Stdio) {
        self.cmd.stdout(to_io(cfg));
    }
    pub fn stderr(&mut self, cfg: Stdio) {
        self.cmd.stderr(to_io(cfg));
    }

    pub fn save_stdouterr(&mut self) {
        self.stdout(Stdio::piped());
        self.want_stdouterr = true;
    }

    pub fn log_stdouterr(&mut self, path: &std::path::Path) {
        self.stdout(Stdio::piped());
        self.want_stdouterr = true;
        self.log_stdouterr = Some(PathBuf::from(path));
    }

    /// Run the Command blind, wait for it to complete, and return its results.
    pub fn blind(&mut self, envs_cleared: bool,
                 envs_removed: &std::collections::HashSet<OsString>,
                 envs_set: &std::collections::HashMap<OsString,OsString>) -> io::Result<Status> {
        self.status(envs_cleared, &envs_removed, &envs_set)
    }
    pub fn status(&mut self, envs_cleared: bool,
                  envs_removed: &std::collections::HashSet<OsString>,
                  envs_set: &std::collections::HashMap<OsString,OsString>)
                  -> io::Result<Status>
    {
        if envs_cleared {
            self.cmd.env_clear();
        }
        for e in envs_removed {
            self.cmd.env_remove(e);
        }
        for (k,v) in envs_set {
            self.cmd.env(k,v);
        }
        if self.want_stdouterr {
            let s = self.cmd.output()?;
            if let Some(ref p) = self.log_stdouterr {
                let mut f = std::fs::File::create(p)?;
                f.write(&s.stdout)?;
            }
            Ok(Status {
                status: s.status,
                read_from_directories: std::collections::HashSet::new(),
                read_from_files: std::collections::HashSet::new(),
                written_to_files: std::collections::HashSet::new(),
                mkdir_directories: std::collections::HashSet::new(),
                stdout_fd: Some(s.stdout),
            })
        } else {
            let s = self.cmd.status()?;
            Ok(Status {
                status: s,
                read_from_directories: std::collections::HashSet::new(),
                read_from_files: std::collections::HashSet::new(),
                written_to_files: std::collections::HashSet::new(),
                mkdir_directories: std::collections::HashSet::new(),
                stdout_fd: None,
            })
        }
    }
    pub fn spawn(mut self, envs_cleared: bool,
                 envs_removed: std::collections::HashSet<OsString>,
                 envs_set: std::collections::HashMap<OsString,OsString>)
                 -> io::Result<Child>
    {
        if envs_cleared {
            self.cmd.env_clear();
        }
        for e in envs_removed {
            self.cmd.env_remove(e);
        }
        for (k,v) in envs_set {
            self.cmd.env(k,v);
        }
        self.cmd.spawn().map(|c| {
            Child {
                inner: Some(c),
                want_stdouterr: self.want_stdouterr,
                log_stdouterr: self.log_stdouterr.clone(),
            }
        })
    }
    pub fn spawn_hook_blind<F>(self, envs_cleared: bool,
                               envs_removed: std::collections::HashSet<OsString>,
                               envs_set: std::collections::HashMap<OsString,OsString>,
                               status_hook: F,)
                               -> io::Result<::Killer>
        where F: FnOnce(std::io::Result<::Status>) + Send + 'static
    {
        self.spawn_hook(envs_cleared, envs_removed, envs_set, status_hook)
    }
    pub fn spawn_hook<F>(mut self, envs_cleared: bool,
                         envs_removed: std::collections::HashSet<OsString>,
                         envs_set: std::collections::HashMap<OsString,OsString>,
                         status_hook: F,)
                         -> io::Result<::Killer>
        where F: FnOnce(std::io::Result<::Status>) + Send + 'static
    {
        if envs_cleared {
            self.cmd.env_clear();
        }
        for e in envs_removed {
            self.cmd.env_remove(e);
        }
        for (k,v) in envs_set {
            self.cmd.env(k,v);
        }
        let c = self.cmd.spawn()?;
        let mut myc = Child {
            inner: Some(c),
            want_stdouterr: self.want_stdouterr,
            log_stdouterr: self.log_stdouterr.clone(),
        };
        std::thread::spawn(move || {
            status_hook(myc.wait().map(|c| ::Status { inner: c }));
        });
        Ok(::Killer { inner: Killer {}})
    }
}

enum Std {
    Inherit,
    MakePipe,
    Null,
}

fn to_io(i: Stdio) -> std::process::Stdio {
    match i.0 {
        Std::Inherit => std::process::Stdio::inherit(),
        Std::MakePipe => std::process::Stdio::piped(),
        Std::Null => std::process::Stdio::null(),
    }
}

/// A description of what you want done with one of the standard streams.
pub struct Stdio(Std);

impl Stdio {
    /// A new pipe should be arranged to connect the parent and child processes.
    pub fn piped() -> Stdio { Stdio(Std::MakePipe) }

    /// The child inherits from the corresponding parent descriptor.
    pub fn inherit() -> Stdio { Stdio(Std::Inherit) }

    /// This stream will be ignored. This is the equivalent of attaching the
    /// stream to `/dev/null`
    pub fn null() -> Stdio { Stdio(Std::Null) }
}