| 1 |
|
| 2 |
|
| 3 |
use ctl_error::*; |
| 4 |
use ctl_value::*; |
| 5 |
|
| 6 |
use std::io::{Read, Write}; |
| 7 |
|
| 8 |
pub fn path_to_name(name: &str) -> String { |
| 9 |
name.to_owned() |
| 10 |
.replace("/proc/sys/", "") |
| 11 |
.replace("..", ".") |
| 12 |
.replace("/", ".") |
| 13 |
} |
| 14 |
|
| 15 |
pub fn value(name: &str) -> Result<CtlValue, SysctlError> { |
| 16 |
let file_res = std::fs::OpenOptions::new() |
| 17 |
.read(true) |
| 18 |
.write(false) |
| 19 |
.open(&name); |
| 20 |
|
| 21 |
file_res |
| 22 |
.map(|mut file| { |
| 23 |
let mut v = String::new(); |
| 24 |
file.read_to_string(&mut v)?; |
| 25 |
Ok(CtlValue::String(v.trim().to_owned())) |
| 26 |
}) |
| 27 |
.map_err(|e| { |
| 28 |
if e.kind() == std::io::ErrorKind::NotFound { |
| 29 |
SysctlError::NotFound(name.into()) |
| 30 |
} else { |
| 31 |
e.into() |
| 32 |
} |
| 33 |
})? |
| 34 |
} |
| 35 |
|
| 36 |
pub fn set_value(name: &str, v: CtlValue) -> Result<CtlValue, SysctlError> { |
| 37 |
let file_res = std::fs::OpenOptions::new() |
| 38 |
.read(false) |
| 39 |
.write(true) |
| 40 |
.open(&name); |
| 41 |
|
| 42 |
file_res |
| 43 |
.map(|mut file| match v { |
| 44 |
CtlValue::String(v) => { |
| 45 |
file.write_all(&v.as_bytes())?; |
| 46 |
value(&name) |
| 47 |
} |
| 48 |
_ => Err(std::io::Error::from(std::io::ErrorKind::InvalidData).into()), |
| 49 |
}) |
| 50 |
.map_err(|e| { |
| 51 |
if e.kind() == std::io::ErrorKind::NotFound { |
| 52 |
SysctlError::NotFound(name.into()) |
| 53 |
} else { |
| 54 |
e.into() |
| 55 |
} |
| 56 |
})? |
| 57 |
} |