path.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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::OsString,
  21. fs,
  22. path::{Path, PathBuf},
  23. };
  24. use crate::{Error, Result};
  25. #[cfg(target_family = "unix")]
  26. mod home_dir_impl {
  27. use std::{
  28. env,
  29. ffi::{CStr, OsString},
  30. mem,
  31. os::unix::prelude::OsStringExt,
  32. path::PathBuf,
  33. ptr,
  34. };
  35. /// Returns the path to the user's home directory.
  36. /// Use `$HOME`, fallbacks to `libc::getpwuid_r`, otherwise `None`.
  37. pub fn home_dir() -> Option<PathBuf> {
  38. env::var_os("HOME")
  39. .and_then(|h| if h.is_empty() { None } else { Some(h) })
  40. .or_else(|| unsafe { home_fallback() })
  41. .map(PathBuf::from)
  42. }
  43. /// Get the home directory from the passwd entry of the current user using
  44. /// `getpwuid_r(3)`. If it manages, returns an `OsString`, otherwise returns `None`.
  45. unsafe fn home_fallback() -> Option<OsString> {
  46. let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
  47. n if n < 0 => 512_usize,
  48. n => n as usize,
  49. };
  50. let mut buf = Vec::with_capacity(amt);
  51. let mut passwd: libc::passwd = mem::zeroed();
  52. let mut result = ptr::null_mut();
  53. let r = libc::getpwuid_r(
  54. libc::getuid(),
  55. &mut passwd,
  56. buf.as_mut_ptr(),
  57. buf.capacity(),
  58. &mut result,
  59. );
  60. match r {
  61. 0 if !result.is_null() => {
  62. let ptr = passwd.pw_dir as *const _;
  63. let bytes = CStr::from_ptr(ptr).to_bytes();
  64. if bytes.is_empty() {
  65. return None
  66. }
  67. Some(OsStringExt::from_vec(bytes.to_vec()))
  68. }
  69. _ => None,
  70. }
  71. }
  72. }
  73. #[cfg(target_family = "windows")]
  74. mod home_dir_impl {
  75. use std::{env, path::PathBuf};
  76. pub fn home_dir() -> Option<PathBuf> {
  77. env::var_os("APPDATA").map(PathBuf::from)
  78. }
  79. }
  80. pub use home_dir_impl::home_dir;
  81. /// Returns `$XDG_CONFIG_HOME`, `$HOME/.config`, or `None`.
  82. pub fn config_dir() -> Option<PathBuf> {
  83. env::var_os("XDG_CONFIG_HOME")
  84. .and_then(is_absolute_path)
  85. .or_else(|| home_dir().map(|h| h.join(".config")))
  86. }
  87. fn is_absolute_path(path: OsString) -> Option<PathBuf> {
  88. let path = PathBuf::from(path);
  89. if path.is_absolute() {
  90. Some(path)
  91. } else {
  92. None
  93. }
  94. }
  95. pub fn expand_path(path: &str) -> Result<PathBuf> {
  96. let ret: PathBuf;
  97. if path.starts_with("~/") {
  98. if let Some(homedir) = home_dir() {
  99. let remains = PathBuf::from(path.strip_prefix("~/").unwrap());
  100. ret = [homedir, remains].iter().collect();
  101. } else {
  102. panic!("Could not fetch path for home directory");
  103. }
  104. } else if path.starts_with('~') {
  105. if let Some(homedir) = home_dir() {
  106. ret = homedir
  107. } else {
  108. panic!("Could not fetch path for home directory");
  109. }
  110. } else {
  111. ret = PathBuf::from(path);
  112. }
  113. Ok(ret)
  114. }
  115. /// Join a path with `config_dir()/darkfi`.
  116. pub fn join_config_path(file: &Path) -> Result<PathBuf> {
  117. let mut path = PathBuf::new();
  118. let dfi_path = Path::new("darkfi");
  119. if let Some(v) = config_dir() {
  120. path.push(v);
  121. }
  122. path.push(dfi_path);
  123. path.push(file);
  124. Ok(path)
  125. }
  126. pub fn get_config_path(arg: Option<String>, fallback: &str) -> Result<PathBuf> {
  127. if let Some(a) = arg {
  128. expand_path(&a)
  129. } else {
  130. join_config_path(&PathBuf::from(fallback))
  131. }
  132. }
  133. pub fn load_keypair_to_str(path: PathBuf) -> Result<String> {
  134. if Path::new(&path).exists() {
  135. let key = fs::read(&path)?;
  136. let str_buff = std::str::from_utf8(&key)?;
  137. Ok(str_buff.to_string())
  138. } else {
  139. println!("Could not parse keypair path");
  140. Err(Error::KeypairPathNotFound)
  141. }
  142. }