summaryrefslogtreecommitdiff
path: root/src/secure.rs
blob: 5fb0cc8be74315d8ed62d27b4993c3d8054fa6c6 (plain)
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
use std::{os::{unix::prelude::PermissionsExt, linux::fs::MetadataExt}, fs, io};
use nix::unistd;

pub fn write_file(dir: &str, file: &str, data: &str) -> Result<(), io::Error> {
  fs::create_dir_all(dir)?;
  set_file_permissions(0, 0, 0o100600, dir)?;
  let path = path(dir, file);
  fs::write(&path, "")?;
  set_file_permissions(0, 0, 0o100600, &path)?;
  fs::write(&path, data)?;
  Ok(())
}

pub fn read_file(dir: &str, file: &str) -> Option<String> {
  let path = path(dir,file);
  if !check_file_permissions(0, 0, 0o100600, &path) {
      return None;
  }
  match fs::read_to_string(&path) {
      Ok(data) => return Some(data),
      Err(_) => return None
  };
}

fn set_file_permissions(uid: u32, gid: u32, mode: u32, path: &str) -> Result<(), io::Error> {
  unistd::chown(std::path::Path::new(path), Some(unistd::Uid::from(uid)), Some(unistd::Gid::from(gid)))?;
  let metadata = fs::metadata(path)?;
  let mut perms = metadata.permissions();
  perms.set_mode(mode);
  fs::set_permissions(path, perms)?;
  Ok(())
}

fn check_file_permissions(uid: u32, gid: u32, mode: u32, path: &str) -> bool {
  let metadata = match fs::metadata(path) {
    Ok(data) => data,
    Err(_) => return false
  };
  let perms = metadata.permissions();
  return perms.mode() == mode && metadata.st_uid() == uid && metadata.st_gid() == gid;
}

fn path(dir: &str, file: &str) -> String {
  return format!("{}/{}", dir, file);
}