|
| 1 | +//! Process initial environment from `/proc/[pid]/environ`. |
| 2 | +
|
| 3 | +use std::ffi::{OsStr, OsString}; |
| 4 | +use std::fs::File; |
| 5 | +use std::io::{Result, Read}; |
| 6 | +use std::os::unix::ffi::OsStrExt; |
| 7 | +use std::path::Path; |
| 8 | + |
| 9 | +use parsers::map_result; |
| 10 | +use nom::IResult; |
| 11 | + |
| 12 | +use libc::pid_t; |
| 13 | + |
| 14 | +/// A list of environment variables and their values. |
| 15 | +pub type Environ = Vec<(OsString, OsString)>; |
| 16 | + |
| 17 | +/// Parses the provided buffer. |
| 18 | +fn parse_environ(input: &[u8]) -> IResult<&[u8], Environ> { |
| 19 | + // Parse 'key=value" pair. |
| 20 | + named!( |
| 21 | + pair<&[u8], (&[u8], &[u8])>, |
| 22 | + tuple!(take_until_and_consume!("="), take_until!("\0")) |
| 23 | + ); |
| 24 | + // Parse (key=value\0) list. |
| 25 | + named!( |
| 26 | + multi<&[u8],Vec<(&[u8], &[u8])> >, |
| 27 | + terminated!( |
| 28 | + separated_list!(tag!("\0"), pair), |
| 29 | + tag!("\0") |
| 30 | + ) |
| 31 | + ); |
| 32 | + multi(input).map(|r| { |
| 33 | + r.into_iter() |
| 34 | + .map(|(x, y)| { |
| 35 | + ( |
| 36 | + OsString::from(OsStr::from_bytes(x)), |
| 37 | + OsString::from(OsStr::from_bytes(y)), |
| 38 | + ) |
| 39 | + }) |
| 40 | + .collect() |
| 41 | + }) |
| 42 | +} |
| 43 | + |
| 44 | +#[test] |
| 45 | +fn test_parse() { |
| 46 | + use nom::IResult::Done; |
| 47 | + let res = parse_environ(&b"key1=val1\0key2=val2\0"[..]); |
| 48 | + let reference: Environ = vec![ |
| 49 | + ("key1".into(), "val1".into()), |
| 50 | + ("key2".into(), "val2".into()), |
| 51 | + ]; |
| 52 | + assert_eq!(res, Done(&b""[..], reference)); |
| 53 | +} |
| 54 | + |
| 55 | +/// Parses the provided environ file. |
| 56 | +fn environ_path<P: AsRef<Path>>(path: P) -> Result<Environ> { |
| 57 | + let mut buf = Vec::new(); |
| 58 | + if File::open(path)?.read_to_end(&mut buf)? == 0 { |
| 59 | + // Don't attempt to parse an empty file. |
| 60 | + return Ok(Default::default()); |
| 61 | + } |
| 62 | + map_result(parse_environ(&buf)) |
| 63 | +} |
| 64 | + |
| 65 | +/// Returns initial environment for the process with the provided pid as key-value pairs. |
| 66 | +pub fn environ(pid: pid_t) -> Result<Environ> { |
| 67 | + environ_path(format!("/proc/{}/environ", pid)) |
| 68 | +} |
| 69 | + |
| 70 | +/// Returns initial environment for the current process as key-value pairs. |
| 71 | +pub fn environ_self() -> Result<Environ> { |
| 72 | + environ_path("/proc/self/environ") |
| 73 | +} |
| 74 | + |
| 75 | +#[test] |
| 76 | +fn test_environ() { |
| 77 | + assert!(environ_self().is_ok()); |
| 78 | +} |
0 commit comments