path.rs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. env,
  20. ffi::{CStr, OsString},
  21. fs, mem,
  22. os::unix::prelude::OsStringExt,
  23. path::{Path, PathBuf},
  24. ptr,
  25. };
  26. use crate::{Error, Result};
  27. /// Returns the path to the user's home directory.
  28. /// Use `$HOME`, fallbacks to `libc::getpwuid_r`, otherwise `None`.
  29. pub fn home_dir() -> Option<PathBuf> {
  30. env::var_os("HOME")
  31. .and_then(|h| if h.is_empty() { None } else { Some(h) })
  32. .or_else(|| unsafe { home_fallback() })
  33. .map(PathBuf::from)
  34. }
  35. /// Get the home directory from the passwd entry of the current user using
  36. /// `getpwuid_r(3)`. If it manages, returns an `OsString`, otherwise returns `None`.
  37. unsafe fn home_fallback() -> Option<OsString> {
  38. let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
  39. n if n < 0 => 512_usize,
  40. n => n as usize,
  41. };
  42. let mut buf = Vec::with_capacity(amt);
  43. let mut passwd: libc::passwd = mem::zeroed();
  44. let mut result = ptr::null_mut();
  45. let r = libc::getpwuid_r(
  46. libc::getuid(),
  47. &mut passwd,
  48. buf.as_mut_ptr(),
  49. buf.capacity(),
  50. &mut result,
  51. );
  52. match r {
  53. 0 if !result.is_null() => {
  54. let ptr = passwd.pw_dir as *const _;
  55. let bytes = CStr::from_ptr(ptr).to_bytes();
  56. if bytes.is_empty() {
  57. return None
  58. }
  59. Some(OsStringExt::from_vec(bytes.to_vec()))
  60. }
  61. _ => None,
  62. }
  63. }
  64. /// Returns `$XDG_CONFIG_HOME`, `$HOME/.config`, or `None`.
  65. pub fn config_dir() -> Option<PathBuf> {
  66. env::var_os("XDG_CONFIG_HOME")
  67. .and_then(is_absolute_path)
  68. .or_else(|| home_dir().map(|h| h.join(".config")))
  69. }
  70. fn is_absolute_path(path: OsString) -> Option<PathBuf> {
  71. let path = PathBuf::from(path);
  72. if path.is_absolute() {
  73. Some(path)
  74. } else {
  75. None
  76. }
  77. }
  78. pub fn expand_path(path: &str) -> Result<PathBuf> {
  79. let ret: PathBuf;
  80. if path.starts_with("~/") {
  81. if let Some(homedir) = home_dir() {
  82. let remains = PathBuf::from(path.strip_prefix("~/").unwrap());
  83. ret = [homedir, remains].iter().collect();
  84. } else {
  85. panic!("Could not fetch path for home directory");
  86. }
  87. } else if path.starts_with('~') {
  88. if let Some(homedir) = home_dir() {
  89. ret = homedir
  90. } else {
  91. panic!("Could not fetch path for home directory");
  92. }
  93. } else {
  94. ret = PathBuf::from(path);
  95. }
  96. Ok(ret)
  97. }
  98. /// Join a path with `config_dir()/darkfi`.
  99. pub fn join_config_path(file: &Path) -> Result<PathBuf> {
  100. let mut path = PathBuf::new();
  101. let dfi_path = Path::new("darkfi");
  102. if let Some(v) = config_dir() {
  103. path.push(v);
  104. }
  105. path.push(dfi_path);
  106. path.push(file);
  107. Ok(path)
  108. }
  109. pub fn get_config_path(arg: Option<String>, fallback: &str) -> Result<PathBuf> {
  110. if let Some(a) = arg {
  111. expand_path(&a)
  112. } else {
  113. join_config_path(&PathBuf::from(fallback))
  114. }
  115. }
  116. pub fn load_keypair_to_str(path: PathBuf) -> Result<String> {
  117. if Path::new(&path).exists() {
  118. let key = fs::read(&path)?;
  119. let str_buff = std::str::from_utf8(&key)?;
  120. Ok(str_buff.to_string())
  121. } else {
  122. println!("Could not parse keypair path");
  123. Err(Error::KeypairPathNotFound)
  124. }
  125. }