|
| 1 | +//! Process initial environment from `/proc/[pid]/environ`. |
| 2 | +
|
| 3 | +use std::collections::BTreeMap; |
| 4 | +use std::fs::{File, metadata}; |
| 5 | +use std::io::{Result, Read}; |
| 6 | +use std::path::Path; |
| 7 | + |
| 8 | +use parsers::map_result; |
| 9 | +use nom::IResult; |
| 10 | + |
| 11 | +use libc::pid_t; |
| 12 | + |
| 13 | +/// Parses the provided buffer. |
| 14 | +fn parse_environ(input: &[u8]) -> IResult<&[u8], BTreeMap<Vec<u8>, Vec<u8>>> { |
| 15 | + // Parse 'key=value" pair. |
| 16 | + named!( |
| 17 | + pair<&[u8], (&[u8], &[u8])>, |
| 18 | + tuple!(take_until_and_consume!("="), take_until!("\0")) |
| 19 | + ); |
| 20 | + // Parse (key=value\0) list. |
| 21 | + named!( |
| 22 | + multi<&[u8],Vec<(&[u8], &[u8])> >, |
| 23 | + terminated!( |
| 24 | + separated_list!(tag!("\0"), pair), |
| 25 | + tag!("\0") |
| 26 | + ) |
| 27 | + ); |
| 28 | + multi(input).map(|r| { |
| 29 | + r.into_iter() |
| 30 | + .map(|(x, y)| (x.to_vec(), y.to_vec())) |
| 31 | + .collect() |
| 32 | + }) |
| 33 | +} |
| 34 | + |
| 35 | +#[test] |
| 36 | +fn test_parse() { |
| 37 | + use nom::IResult::Done; |
| 38 | + let res = parse_environ(&b"key1=val1\0key2=val2\0"[..]); |
| 39 | + let reference = vec![ |
| 40 | + (b"key1".to_vec(), b"val1".to_vec()), |
| 41 | + (b"key2".to_vec(), b"val2".to_vec()), |
| 42 | + ]; |
| 43 | + assert_eq!(res, Done(&b""[..], reference.into_iter().collect())); |
| 44 | +} |
| 45 | + |
| 46 | +/// Parses the provided environ file. |
| 47 | +fn environ_path<P: AsRef<Path>>(path: P) -> Result<BTreeMap<Vec<u8>, Vec<u8>>> { |
| 48 | + let file_size = metadata(&path)?.len(); |
| 49 | + let mut buf = vec![0u8; file_size as usize]; |
| 50 | + File::open(path)?.read_exact(&mut buf)?; |
| 51 | + map_result(parse_environ(&buf)) |
| 52 | +} |
| 53 | + |
| 54 | +/// Returns initial environment for the process with the provided pid in the form of 'key' => |
| 55 | +/// 'value' BTreeMap. |
| 56 | +pub fn environ(pid: pid_t) -> Result<BTreeMap<Vec<u8>, Vec<u8>>> { |
| 57 | + environ_path(format!("/proc/{}/environ", pid)) |
| 58 | +} |
| 59 | + |
| 60 | +/// Returns initial environment for the current process in the form of 'key' => 'value' BTreeMap. |
| 61 | +pub fn environ_self() -> Result<BTreeMap<Vec<u8>, Vec<u8>>> { |
| 62 | + environ_path("/proc/self/environ") |
| 63 | +} |
0 commit comments