unix.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use std::str::raw::from_c_str;
  2. use std::ptr::read;
  3. mod c {
  4. #![allow(non_camel_case_types)]
  5. extern crate libc;
  6. use self::libc::{
  7. c_char,
  8. c_int,
  9. uid_t,
  10. time_t
  11. };
  12. pub struct c_passwd {
  13. pub pw_name: *c_char, // login name
  14. pub pw_passwd: *c_char,
  15. pub pw_uid: c_int, // user ID
  16. pub pw_gid: c_int, // group ID
  17. pub pw_change: time_t,
  18. pub pw_class: *c_char,
  19. pub pw_gecos: *c_char, // full name
  20. pub pw_dir: *c_char, // login dir
  21. pub pw_shell: *c_char, // login shell
  22. pub pw_expire: time_t // password expiry time
  23. }
  24. pub struct c_group {
  25. pub gr_name: *c_char // group name
  26. }
  27. extern {
  28. pub fn getpwuid(uid: c_int) -> *c_passwd;
  29. pub fn getgrgid(gid: uid_t) -> *c_group;
  30. pub fn getuid() -> libc::c_int;
  31. }
  32. }
  33. pub fn get_user_name(uid: i32) -> Option<String> {
  34. let pw = unsafe { c::getpwuid(uid) };
  35. if pw.is_not_null() {
  36. return unsafe { Some(from_c_str(read(pw).pw_name)) };
  37. }
  38. else {
  39. return None;
  40. }
  41. }
  42. pub fn get_group_name(gid: u32) -> Option<String> {
  43. let gr = unsafe { c::getgrgid(gid) };
  44. if gr.is_not_null() {
  45. return unsafe { Some(from_c_str(read(gr).gr_name)) };
  46. }
  47. else {
  48. return None;
  49. }
  50. }
  51. pub fn get_current_user_id() -> u64 {
  52. unsafe { c::getuid() as u64 }
  53. }