Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Squash some PRs from the original repo #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
target
Cargo.lock
.idea
16 changes: 15 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,25 @@ rust:
- stable
- nightly

env:
-
- CARGO_BUILD_TARGET=arm-linux-androideabi
- CARGO_BUILD_TARGET=x86_64-linux-android
- CARGO_BUILD_TARGET=aarch64-linux-android

os:
- linux

matrix:
exclude:
rust: 1.13.0
env: CARGO_BUILD_TARGET=x86_64-linux-android

script:
- if [[ $CARGO_BUILD_TARGET ]]; then
rustup target add $CARGO_BUILD_TARGET;
fi
- cargo build --verbose
- if [[ $TRAVIS_RUST_VERSION = nightly* ]]; then
- if [[ $TRAVIS_RUST_VERSION = nightly* && -z "$CARGO_BUILD_TARGET" ]]; then
env RUST_BACKTRACE=1 cargo test -v;
fi
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ currently the following interfaces are provided:

* `/proc/loadavg`
* `/proc/<pid>/cwd`
* `/proc/<pid>/environ`
* `/proc/<pid>/limits`
* `/proc/<pid>/maps`
* `/proc/<pid>/mountinfo`
* `/proc/<pid>/stat`
* `/proc/<pid>/statm`
Expand Down
87 changes: 87 additions & 0 deletions src/filesystems.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! Supported filesystems from `/proc/filesystems`.

use std::fs::File;
use std::io::{BufRead, BufReader, Result};

use nom::tab;

use parsers::{map_result, parse_line};

/// Supported filesystems.
///
/// This is a list of filesystems which which are supported by the
/// kernel, namely filesystems which were compiled into the kernel
/// or whose kernel modules are currently loaded. If a filesystem
/// is marked with "nodev", this means that it does not require a
/// block device to be mounted (e.g., virtual filesystem, network
/// filesystem).
///
/// See `man 5 proc` and `Linux/fs/filesystems.c`.
#[derive(Debug, Default, PartialEq)]
pub struct Filesystem {
/// The filesystem does not require a block device to be mounted (e.g., virtual filesytems, network filesystems).
pub nodev: bool,
/// The name of the filesystem (e.g. "ext4").
pub name: String,
}

/// Parses a filesystem entry according to filesystems file format.
named!(parse_filesystem<Filesystem>,
do_parse!(nodev: opt!(tag!("nodev")) >> tab >>
name: parse_line >>
( Filesystem { nodev: nodev.is_some(), name: name } )));

/// Returns the supported filesystems.
pub fn filesystems() -> Result<Vec<Filesystem>> {
let mut file = try!(File::open("/proc/filesystems"));
let mut r = Vec::new();
for line in BufReader::new(&mut file).lines() {
let fs = try!(map_result(parse_filesystem(try!(line).as_bytes())));
r.push(fs);
}
Ok(r)
}

#[cfg(test)]
pub mod tests {
use super::{Filesystem, parse_filesystem, filesystems};

/// Test parsing a single filesystems entry (positive check).
#[test]
fn test_parse_filesystem() {
let entry =
b"\text4";
let got_fs = parse_filesystem(entry).unwrap().1;
let want_fs = Filesystem {
nodev: false,
name: "ext4".to_string(),
};
assert_eq!(got_fs, want_fs);
}

/// Test parsing a single filesystems entry with nodev (positive check).
#[test]
fn test_parse_nodev_filesystem() {
let entry =
b"nodev\tfuse";
let got_fs = parse_filesystem(entry).unwrap().1;
let want_fs = Filesystem {
nodev: true,
name: "fuse".to_string(),
};
assert_eq!(got_fs, want_fs);
}

/// Test parsing a single filesystem entry (negative check).
#[test]
fn test_parse_filesystem_error() {
let entry = b"garbage";
parse_filesystem(entry).unwrap_err();
}

/// Test that the system filesystems file can be parsed.
#[test]
fn test_filesystems() {
filesystems().unwrap();
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ extern crate libc;

#[macro_use]
mod parsers;
mod unmangle;

mod filesystems;
mod loadavg;
pub mod pid;
pub mod sys;
pub mod net;

pub use filesystems::{Filesystem, filesystems};
pub use loadavg::{LoadAvg, loadavg};
14 changes: 14 additions & 0 deletions src/parsers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ named!(pub parse_u32<u32>,
named!(pub parse_u64<u64>,
map_res!(map_res!(digit, str::from_utf8), FromStr::from_str));

/// Parses a u128 in base-10 format.
named!(pub parse_u128<u128>,
map_res!(map_res!(digit, str::from_utf8), FromStr::from_str));

/// Parses a usize in base-10 format.
named!(pub parse_usize<usize>,
map_res!(map_res!(digit, str::from_utf8), FromStr::from_str));
Expand Down Expand Up @@ -164,11 +168,21 @@ named!(pub parse_u32_octal<u32>,
map_res!(map_res!(alphanumeric, str::from_utf8),
|s| u32::from_str_radix(s, 8)));

/// Parses a u16 in base-8 format.
named!(pub parse_u16_octal<u16>,
map_res!(map_res!(alphanumeric, str::from_utf8),
|s| u16::from_str_radix(s, 8)));

/// Parses a u64 in base-16 format.
named!(pub parse_u64_hex<u64>,
map_res!(map_res!(alphanumeric, str::from_utf8),
|s| u64::from_str_radix(s, 16)));

/// Parses a usize in base-16 format.
named!(pub parse_usize_hex<usize>,
map_res!(map_res!(alphanumeric, str::from_utf8),
|s| usize::from_str_radix(s, 16)));

/// Reverses the bits in a byte.
fn reverse(n: u8) -> u8 {
// stackoverflow.com/questions/2602823/in-c-c-whats-the-simplest-way-to-reverse-the-order-of-bits-in-a-byte
Expand Down
6 changes: 6 additions & 0 deletions src/pid/cwd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ pub fn cwd(pid: pid_t) -> Result<PathBuf> {
fs::read_link(format!("/proc/{}/cwd", pid))
}

/// Gets path of current working directory for the process with the provided
/// pid and tid.
pub fn cwd_task(pid: pid_t, tid: pid_t) -> Result<PathBuf> {
fs::read_link(format!("/proc/{}/task/{}/cwd", pid, tid))
}

/// Gets path of current working directory for the current process.
pub fn cwd_self() -> Result<PathBuf> {
fs::read_link("/proc/self/cwd")
Expand Down
186 changes: 186 additions & 0 deletions src/pid/environ.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
//! Process initial environment from `/proc/[pid]/environ`.

use std::ffi::OsStr;
use std::fs::File;
use std::io::{Error, ErrorKind, Read, Result};
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::iter::Iterator;

use libc::pid_t;
use nom::{self, IResult};

/// An environment holder.
///
/// Use the `into_iter` method to access environment variables as key-value pairs.
#[derive(Debug, Clone)]
pub struct Environ {
data: Vec<u8>,
}

/// A lazy iterator over environment variables.
pub struct EnvironIter<'a> {
data_pointer: &'a [u8],
}

impl<'a> Iterator for EnvironIter<'a> {
/// Since the data is parsed on the fly, a parsing error could be encountered, hence using an
/// `io::Result` as an iterator item.
type Item = Result<(&'a OsStr, &'a OsStr)>;

fn next(&mut self) -> Option<Self::Item> {
if self.data_pointer.is_empty() {
return None;
}
match parse_pair(self.data_pointer) {
IResult::Done(data, parsed) => {
self.data_pointer = data;
Some(Ok(parsed))
}
IResult::Incomplete(_) => None,
IResult::Error(err) => Some(Err(Error::new(
ErrorKind::InvalidInput,
format!("Unable to parse input: {:?}", err),
))),
}
}
}

impl<'a> IntoIterator for &'a Environ {
type Item = Result<(&'a OsStr, &'a OsStr)>;
type IntoIter = EnvironIter<'a>;

fn into_iter(self) -> Self::IntoIter {
EnvironIter {
data_pointer: &self.data,
}
}
}

/// Extracts name of a variable. Also consumes a delimiter.
fn get_name(src: &[u8]) -> IResult<&[u8], &OsStr> {
// Calculate position of the *equal* sign.
let pos = match src.iter().skip(1).position(|c| c == &b'=') {
Some(p) => p,
None => return IResult::Error(error_position!(nom::ErrorKind::Custom(0), src)),
};
IResult::Done(&src[pos + 2..], from_bytes(&src[..pos + 1]))
}

/// Parses "key=value" pair.
named!(
parse_pair<&[u8], (&OsStr, &OsStr)>,
tuple!(get_name, map!(take_until_and_consume!("\0"), from_bytes))
);

/// A helper function to convert a slice of bytes to an `OsString`.
fn from_bytes(s: &[u8]) -> &OsStr {
OsStr::from_bytes(s)
}

/// Parses the provided environ file.
fn environ_path<P: AsRef<Path>>(path: P) -> Result<Environ> {
let mut buf = Vec::new();
File::open(path)?.read_to_end(&mut buf)?;
Ok(Environ { data: buf })
}

/// Returns initial environment for the process with the provided pid as key-value pairs.
pub fn environ(pid: pid_t) -> Result<Environ> {
environ_path(format!("/proc/{}/environ", pid))
}

/// Returns initial environment for the process with the provided process id and thread id
/// as key-value pairs.
pub fn environ_task(pid: pid_t, tid: pid_t) -> Result<Environ> {
environ_path(format!("/proc/{}/task/{}/environ", pid, tid))
}

/// Returns initial environment for the current process as key-value pairs.
pub fn environ_self() -> Result<Environ> {
environ_path("/proc/self/environ")
}

#[cfg(test)]
mod test {
use super::*;
use std::collections::BTreeMap;

#[test]
fn test_get_name() {
let src = &b"FOO=BAR"[..];
assert_eq!(get_name(src), IResult::Done(&b"BAR"[..], OsStr::new("FOO")));
let src = &b"FOO="[..];
assert_eq!(get_name(src), IResult::Done(&b""[..], OsStr::new("FOO")));
let src = &b"=FOO=BAR"[..];
assert_eq!(
get_name(src),
IResult::Done(&b"BAR"[..], OsStr::new("=FOO"))
);
let src = &b"=FOO="[..];
assert_eq!(get_name(src), IResult::Done(&b""[..], OsStr::new("=FOO")));
}

#[test]
fn test_pair() {
let source = &b"FOO=BAR\0123"[..];
assert_eq!(
parse_pair(source),
IResult::Done(&b"123"[..], (OsStr::new("FOO"), OsStr::new("BAR")))
);
let source = &b"FOO=\0123"[..];
assert_eq!(
parse_pair(source),
IResult::Done(&b"123"[..], (OsStr::new("FOO"), OsStr::new("")))
);
let source = &b"=FOO=BAR\0-"[..];
assert_eq!(
parse_pair(source),
IResult::Done(&b"-"[..], (OsStr::new("=FOO"), OsStr::new("BAR")))
);
let source = &b"=FOO=\0-"[..];
assert_eq!(
parse_pair(source),
IResult::Done(&b"-"[..], (OsStr::new("=FOO"), OsStr::new("")))
);
}

#[test]
fn test_iter() {
let env = Environ {
data: b"key1=val1\0=key2=val 2\0key3=val3\0".to_vec(),
};
// Here's how you convert the env into a vector.
let pairs_vec: Result<Vec<(&OsStr, &OsStr)>> = env.into_iter().collect();
let pairs_vec = match pairs_vec {
Err(e) => panic!("Parsing has failed: {:?}", e),
Ok(pairs) => pairs,
};
assert_eq!(
pairs_vec,
vec![
(OsStr::new("key1"), OsStr::new("val1")),
(OsStr::new("=key2"), OsStr::new("val 2")),
(OsStr::new("key3"), OsStr::new("val3")),
]
);
// And here's how you create a map.
let pairs_map: Result<BTreeMap<&OsStr, &OsStr>> = env.into_iter().collect();
let pairs_map = match pairs_map {
Err(e) => panic!("Parsing has failed: {:?}", e),
Ok(pairs) => pairs,
};
assert_eq!(pairs_map.get(OsStr::new("key1")), Some(&OsStr::new("val1")));
assert_eq!(
pairs_map.get(OsStr::new("=key2")),
Some(&OsStr::new("val 2"))
);
assert_eq!(pairs_map.get(OsStr::new("key3")), Some(&OsStr::new("val3")));
}

#[test]
fn test_environ_self() {
let env = environ_self().unwrap();
assert!(env.into_iter().all(|x| x.is_ok()));
}
}
Loading