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
#![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;

#[cfg(feature="noprofile")]
extern crate cpuprofiler;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(not(target_os = "linux"))]
mod generic;

#[cfg(target_os = "linux")]
use linux as imp;

#[cfg(not(target_os = "linux"))]
use generic as imp;

pub use imp::{Stdio};

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

/// A process builder, providing fine-grained control over how a new
/// process should be spawned.
///
/// Strongly modelled after `std::process::Command`.  A default
/// configuration is generated using `Command::new(program)`, where
/// `program` gives a path to the program to be executed. Additional
/// builder methods allow the configuration to be changed (for
/// example, by adding arguments) prior to running:
///
/// ```
/// use bigbro::Command;
///
/// let status = if cfg!(target_os = "windows") {
///     Command::new("cmd")
///             .args(&["/C", "echo hello"])
///             .status()
///             .expect("failed to execute process")
/// } else {
///     Command::new("sh")
///             .arg("-c")
///             .arg("echo hello")
///             .status()
///             .expect("failed to execute process")
/// };
///
/// assert!(status.status().success());
/// ```
pub struct Command {
    envs_set: std::collections::HashMap<OsString,OsString>,
    envs_removed: std::collections::HashSet<OsString>,
    envs_cleared: bool,
    am_blind: bool,
    inner: imp::Command,
}

impl Command {
    /// Constructs a new `Command` for launching the program at
    /// path `program`, with the following default configuration:
    ///
    /// * No arguments to the program
    /// * Inherit the current process's environment
    /// * Inherit the current process's working directory
    /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
    ///
    /// Builder methods are provided to change these defaults and
    /// otherwise configure the process.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```no_run
    /// use bigbro::Command;
    ///
    /// Command::new("sh")
    ///         .status()
    ///         .expect("sh command failed to run");
    /// ```
    pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
        Command {
            envs_set: std::collections::HashMap::new(),
            envs_removed: std::collections::HashSet::new(),
            envs_cleared: false,
            am_blind: false,
            inner: imp::Command::new(program),
        }
    }

    /// Add a single argument to the command.
    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
        self.inner.arg(arg);
        self
    }

    /// Add arguments to the command.
    pub fn args<I, S>(&mut self, args: I) -> &mut Command
        where I: IntoIterator<Item=S>, S: AsRef<OsStr>
    {
        for arg in args {
            self.inner.arg(arg.as_ref());
        }
        self
    }

    /// Set the working directory for the command.
    pub fn current_dir<P: AsRef<std::path::Path>>(&mut self, dir: P) -> &mut Command {
        self.inner.current_dir(dir);
        self
    }

    /// Update an environment variable mapping
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let mut status = Command::new("sh")
    ///                          .arg("-c")
    ///                          .arg("echo -n $CFLAGS")
    ///                          .env("CFLAGS", "--coverage")
    ///                          .save_stdouterr()
    ///                          .status()
    ///                          .expect("failed to execute sh");
    ///
    /// println!("status: {:?}", status.status());
    /// assert!(status.status().success() );
    /// let f = status.stdout().unwrap();
    /// assert!(f.is_some());
    /// let mut contents = String::new();
    /// f.unwrap().read_to_string(&mut contents).unwrap();
    /// assert_eq!(contents, "--coverage");
    /// ```
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let mut status = Command::new("env")
    ///                          .env_clear()
    ///                          .env("FOO", "foo")
    ///                          .save_stdouterr()
    ///                          .status()
    ///                          .expect("failed to execute env");
    ///
    /// println!("status: {:?}", status.status());
    /// assert!(status.status().success() );
    /// let f = status.stdout().unwrap();
    /// assert!(f.is_some());
    /// let mut contents = String::new();
    /// f.unwrap().read_to_string(&mut contents).unwrap();
    /// assert_eq!(contents, "FOO=foo\n");
    /// ```
    pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
        where K: AsRef<OsStr>, V: AsRef<OsStr>
    {
        self.envs_removed.remove(key.as_ref());
        self.envs_set.insert(key.as_ref().to_os_string(), val.as_ref().to_os_string());
        self
    }

    /// Add or update multiple environment variable mappings.
    pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
        where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
    {
        for (k,v) in vars {
            self.env(k,v);
        }
        self
    }

    /// Remove an environment variable mapping
    pub fn env_remove<K>(&mut self, key: K) -> &mut Command
        where K: AsRef<OsStr>
    {
        self.envs_set.remove(key.as_ref());
        self.envs_removed.insert(key.as_ref().to_os_string());
        self
    }

    /// Clear the environment for the child
    pub fn env_clear(&mut self) -> &mut Command
    {
        self.envs_cleared = true;
        self.envs_set.clear();
        self.envs_removed.clear();
        self
    }

    /// Set the stdin of the command.
    pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
        self.inner.stdin(cfg);
        self
    }

    /// Set the stdout of the command.
    pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
        self.inner.stdout(cfg);
        self
    }

    /// Set the stderr of the command.
    pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
        self.inner.stderr(cfg);
        self
    }

    /// Set the stderr and stdout of the command to go to a temp file,
    /// from which they can be read after the command is run.
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let mut status = Command::new("echo")
    ///                          .arg("-n")
    ///                          .arg("hello")
    ///                          .save_stdouterr()
    ///                          .status()
    ///                          .expect("failed to execute echo");
    ///
    /// assert!(status.status().success() );
    /// let f = status.stdout().unwrap();
    /// assert!(f.is_some());
    /// let mut contents = String::new();
    /// f.unwrap().read_to_string(&mut contents);
    /// assert_eq!(contents, "hello");
    /// ```
    pub fn save_stdouterr(&mut self) -> &mut Command {
        self.inner.save_stdouterr();
        self
    }

    /// Set the stderr and stdout of the command to go to a file,
    /// from which they can be read after the command is run.
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let mut status = Command::new("echo")
    ///                          .arg("-n")
    ///                          .arg("hello")
    ///                          .log_stdouterr(&std::path::Path::new("/tmp/test-file"))
    ///                          .status()
    ///                          .expect("failed to execute echo");
    ///
    /// assert!(status.status().success() );
    /// let f = status.stdout().unwrap();
    /// assert!(f.is_some());
    /// let mut contents = String::new();
    /// f.unwrap().read_to_string(&mut contents).unwrap();
    /// assert_eq!(contents, "hello");
    /// ```
    pub fn log_stdouterr(&mut self, path: &std::path::Path) -> &mut Command {
        self.inner.log_stdouterr(path);
        self
    }

    /// Run the Command, wait for it to complete, and return its results.
    pub fn status(&mut self) -> std::io::Result<Status> {
        if self.am_blind {
            self.inner.blind(self.envs_cleared, &self.envs_removed, &self.envs_set)
                .map(|s| Status { inner: s })
        } else {
            self.inner.status(self.envs_cleared, &self.envs_removed, &self.envs_set)
                .map(|s| Status { inner: s })
        }
    }

    /// Do not actually track accesses.
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let (tx,rx) = std::sync::mpsc::channel();
    /// let mut cmd = Command::new("echo");
    /// cmd.arg("-n").arg("hello").save_stdouterr().blind(true);
    /// let _killer = cmd.spawn_and_hook(move |s| { tx.send(s).ok(); })
    ///                  .expect("failed to execute echo");
    /// let mut status = rx.recv().unwrap().unwrap();
    /// assert!(status.status().success() );
    /// let f = status.stdout().unwrap();
    /// assert!(f.is_some());
    /// let mut f = f.unwrap();
    /// let mut contents = String::new();
    /// f.read_to_string(&mut contents).unwrap();
    /// assert_eq!(contents, "hello");
    /// assert_eq!(status.read_from_files().len(), 0); // not tracking means no files listed
    /// ```

    pub fn blind(&mut self, am_blind: bool) -> &mut Command {
        self.am_blind = am_blind;
        self
    }

    /// Start running the Command and return without waiting for it to complete.
    pub fn spawn(self) -> std::io::Result<Child> {
        if self.am_blind {
            unimplemented!()
        } else {
            self.inner.spawn(self.envs_cleared, self.envs_removed, self.envs_set)
                .map(|s| Child { inner: s })
        }
    }

    /// Start running the Command and return without waiting for it to
    /// complete.  Return the final status via a callback, but return the
    /// pid information with which to kill the child synchronously.
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let (tx,rx) = std::sync::mpsc::channel();
    /// let mut cmd = Command::new("echo");
    /// cmd.arg("-n").arg("hello").log_stdouterr(&std::path::Path::new("/tmp/test-file"));
    /// let _killer = cmd.spawn_and_hook(move |s| { tx.send(s).ok(); })
    ///                  .expect("failed to execute echo");
    /// let mut status = rx.recv().unwrap().unwrap();
    /// assert!(status.status().success() );
    /// let f = status.stdout().unwrap();
    /// assert!(f.is_some());
    /// let mut contents = String::new();
    /// f.unwrap().read_to_string(&mut contents).unwrap();
    /// assert_eq!(contents, "hello");
    /// ```
    pub fn spawn_and_hook<F>(self, status_hook: F) -> std::io::Result<Killer>
        where F: FnOnce(std::io::Result<Status>) + Send + 'static
    {
        if self.am_blind {
            self.inner.spawn_hook_blind(self.envs_cleared, self.envs_removed,
                                        self.envs_set, status_hook)
        } else {
            self.inner.spawn_hook(self.envs_cleared, self.envs_removed, self.envs_set,
                                  status_hook)
        }
    }
}

/// A currently running (or possibly already completed) child process.
#[derive(Debug)]
pub struct Child {
    inner: imp::Child,
}

impl Child {
    /// Force the child process to exit
    pub fn kill(&mut self) -> std::io::Result<()> {
        self.inner.kill()
    }
    /// Ask the child process to exit
    pub fn terminate(&mut self) -> std::io::Result<()> {
        self.inner.terminate()
    }
    /// Wait for child to finish
    pub fn wait(&mut self) -> std::io::Result<Status> {
        self.inner.wait().map(|s| Status { inner: s })
    }
    /// Check if the child has finished
    pub fn try_wait(&mut self) -> std::io::Result<Option<Status>> {
        self.inner.try_wait().map(|s| s.map(|s| Status { inner: s}))
    }
}

/// A currently running (or possibly already completed) child process.
#[derive(Debug, Copy, Clone)]
pub struct Killer {
    inner: imp::Killer,
}

impl Killer {
    /// Force the child process to exit
    pub fn kill(&mut self) -> std::io::Result<()> {
        self.inner.kill()
    }
    /// Ask the child process to exit
    pub fn terminate(&mut self) -> std::io::Result<()> {
        self.inner.terminate()
    }
}

/// 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 {
    inner: imp::Status,
}


impl Status {
    /// This returns the `std::process::ExitStatus` of the process.

    /// Was termination successful? Signal termination not considered a success,
    /// and success is defined as a zero exit status.
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let status = Command::new("sh")
    ///                      .arg("-c")
    ///                      .arg("false")
    ///                      .status()
    ///                      .expect("failed to execute sh");
    ///
    /// assert!(! status.status().success() ); // should fail because "false" always fails
    /// ```
    pub fn status(&self) -> std::process::ExitStatus {
        self.inner.status()
    }
    /// This retuns the set of directories that the process read from.
    /// For details of what is meant by a process having "read from a
    /// directory", see [semantics](semantics.html).
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let dir = std::path::PathBuf::from("/tmp");
    /// let status = Command::new("ls")
    ///                      .arg(&dir)
    ///                      .status()
    ///                      .expect("failed to execute ls");
    ///
    /// assert!(status.status().success() );
    /// assert!(status.read_from_directories().contains(&dir) );
    /// ```
    pub fn read_from_directories(&self) -> std::collections::HashSet<PathBuf> {
       self.inner.read_from_directories()
    }
    /// This retuns the set of files that the process read.  For
    /// details of what is meant by a process having "read from a
    /// directory", see [semantics](semantics.html).
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let e = std::ffi::OsString::from("/usr/bin/python");
    /// let p = std::path::PathBuf::from("/usr/bin/python");
    /// let status = Command::new("sha1sum")
    ///                      .arg(&e)
    ///                      .status()
    ///                      .expect("failed to execute sha1sum");
    ///
    /// assert!(status.status().success() );
    /// for f in status.read_from_files() {
    ///    println!("read file {:#?}", f);
    /// }
    /// assert!(status.read_from_files().contains(&p) );
    pub fn read_from_files(&self) -> std::collections::HashSet<PathBuf> {
        self.inner.read_from_files()
    }
    /// This retuns the set of files that the process wrote to.  For
    /// details of what is meant by a process having "read from a
    /// directory", see [semantics](semantics.html).
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let p = std::path::PathBuf::from("/tmp/hello");
    /// let status = Command::new("sh")
    ///                      .args(&["-c", "echo hello > /tmp/hello"])
    ///                      .status()
    ///                      .expect("failed to execute sh");
    ///
    /// assert!(status.status().success() );
    /// for f in status.written_to_files() {
    ///    println!("wrote file {:#?}", f);
    /// }
    /// assert!(status.written_to_files().contains(&p) );
    /// assert!(status.written_to_files().len() == 1 );
    pub fn written_to_files(&self) -> std::collections::HashSet<PathBuf> {
        self.inner.written_to_files()
    }
    /// This retuns the set of directories that the process created.
    /// For details of what is meant by a process having "read from a
    /// directory", see [semantics](semantics.html).
    pub fn mkdir_directories(&self) -> std::collections::HashSet<PathBuf> {
        self.inner.mkdir_directories()
    }

    /// This retuns the stdout, if it has been saved using `save_stdouterr`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bigbro::Command;
    ///
    /// let mut status = Command::new("ls")
    ///                          .arg("-l")
    ///                          .save_stdouterr()
    ///                          .status()
    ///                          .expect("failed to execute ls");
    ///
    /// assert!(status.status().success() );
    /// let f = status.stdout().unwrap();
    /// assert!(f.is_some());
    /// let mut contents = String::new();
    /// f.unwrap().read_to_string(&mut contents);
    /// println!("ls gives: {}", contents);
    /// assert!(contents.contains("Cargo.toml"));
    /// assert!(contents.contains("src"));
    pub fn stdout(&mut self) -> std::io::Result<Option<Box<std::io::Read>>> {
        self.inner.stdout()
    }
}

#[cfg(target_os = "linux")]
#[cfg(test)]
fn count_file_descriptors() -> usize {
    let mut count = 0;
    for _ in std::fs::read_dir("/proc/self/fd").unwrap() {
        count += 1;
    }
    println!("open file descriptors: {}", count);
    count
}

#[cfg(target_os = "linux")]
#[test]
fn test_have_closed_fds() {
    let fds = count_file_descriptors();
    {
        let status = Command::new("echo")
            .arg("-n")
            .arg("hello")
            .save_stdouterr()
            .status()
            .expect("failed to execute echo");
        assert!(count_file_descriptors() > fds,
                "save_stdouterr should open a file descriptor?");
        println!("status: {:?}", status);
    }
    assert_eq!(count_file_descriptors(), fds);
    {
        Command::new("ls")
            .status()
            .expect("failed to execute ls");
        assert_eq!(count_file_descriptors(), fds);
    }
    assert_eq!(count_file_descriptors(), fds);
    {
        Command::new("ls")
            .stdin(Stdio::null())
            .status()
            .expect("failed to execute ls");
        assert_eq!(count_file_descriptors(), fds);
    }
    assert_eq!(count_file_descriptors(), fds);
    {
        let status = Command::new("echo")
            .arg("-n")
            .arg("hello")
            .stdin(Stdio::null())
            .save_stdouterr()
            .status()
            .expect("failed to execute echo");
        assert!(count_file_descriptors() > fds);
        println!("status: {:?}", status);
    }
    assert_eq!(count_file_descriptors(), fds);
    {
        let status = Command::new("echo")
            .arg("-n")
            .arg("hello")
            .stdin(Stdio::null())
            .log_stdouterr(&std::path::Path::new("/tmp/test-file"))
            .status()
            .expect("failed to execute echo");
        assert!(count_file_descriptors() > fds);
        println!("status: {:?}", status);
    }
    assert_eq!(count_file_descriptors(), fds);
}