From 698f8c2f01ea549d77d7dc3338a12e04c11057b9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:02:58 +0200 Subject: Adding upstream version 1.64.0+dfsg1. Signed-off-by: Daniel Baumann --- vendor/dirs-sys-next/src/lib.rs | 198 ++++++++++++++++++++++++ vendor/dirs-sys-next/src/xdg_user_dirs.rs | 248 ++++++++++++++++++++++++++++++ 2 files changed, 446 insertions(+) create mode 100644 vendor/dirs-sys-next/src/lib.rs create mode 100644 vendor/dirs-sys-next/src/xdg_user_dirs.rs (limited to 'vendor/dirs-sys-next/src') diff --git a/vendor/dirs-sys-next/src/lib.rs b/vendor/dirs-sys-next/src/lib.rs new file mode 100644 index 000000000..f76862e85 --- /dev/null +++ b/vendor/dirs-sys-next/src/lib.rs @@ -0,0 +1,198 @@ +#![warn(rust_2018_idioms)] + +use std::ffi::OsString; +use std::path::PathBuf; + +// we don't need to explicitly handle empty strings in the code above, +// because an empty string is not considered to be a absolute path here. +pub fn is_absolute_path(path: OsString) -> Option { + let path = PathBuf::from(path); + if path.is_absolute() { + Some(path) + } else { + None + } +} + +#[cfg(all(unix, not(target_os = "redox")))] +mod target_unix_not_redox { + + use std::env; + use std::ffi::{CStr, OsString}; + use std::mem; + use std::os::unix::ffi::OsStringExt; + use std::path::PathBuf; + use std::ptr; + + // https://github.com/rust-lang/rust/blob/ef3e3863939217678e5f7e755c4234d224107c64/library/std/src/sys/unix/os.rs#L587 + pub fn home_dir() -> Option { + return env::var_os("HOME") + .and_then(|h| if h.is_empty() { None } else { Some(h) }) + .or_else(|| unsafe { fallback() }) + .map(PathBuf::from); + + #[cfg(any(target_os = "android", target_os = "ios", target_os = "emscripten"))] + unsafe fn fallback() -> Option { + None + } + #[cfg(not(any(target_os = "android", target_os = "ios", target_os = "emscripten")))] + unsafe fn fallback() -> Option { + let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) { + n if n < 0 => 512 as usize, + n => n as usize, + }; + let mut buf = Vec::with_capacity(amt); + let mut passwd: libc::passwd = mem::zeroed(); + let mut result = ptr::null_mut(); + match libc::getpwuid_r(libc::getuid(), &mut passwd, buf.as_mut_ptr(), buf.capacity(), &mut result) { + 0 if !result.is_null() => { + let ptr = passwd.pw_dir as *const _; + let bytes = CStr::from_ptr(ptr).to_bytes(); + if bytes.is_empty() { + None + } else { + Some(OsStringExt::from_vec(bytes.to_vec())) + } + } + _ => None, + } + } + } +} + +#[cfg(all(unix, not(target_os = "redox")))] +pub use self::target_unix_not_redox::home_dir; + +#[cfg(target_os = "redox")] +mod target_redox { + + use std::path::PathBuf; + + use redox_users::{All, AllUsers, Config}; + + pub fn home_dir() -> Option { + let current_uid = redox_users::get_uid().ok()?; + let users = AllUsers::basic(Config::default()).ok()?; + let user = users.get_by_id(current_uid)?; + + Some(PathBuf::from(user.home.clone())) + } +} + +#[cfg(target_os = "redox")] +pub use self::target_redox::home_dir; + +#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] +mod xdg_user_dirs; + +#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] +mod target_unix_not_mac { + + use std::collections::HashMap; + use std::env; + use std::path::{Path, PathBuf}; + + use super::xdg_user_dirs; + use super::{home_dir, is_absolute_path}; + + fn user_dir_file(home_dir: &Path) -> PathBuf { + env::var_os("XDG_CONFIG_HOME") + .and_then(is_absolute_path) + .unwrap_or_else(|| home_dir.join(".config")) + .join("user-dirs.dirs") + } + + // this could be optimized further to not create a map and instead retrieve the requested path only + pub fn user_dir(user_dir_name: &str) -> Option { + if let Some(home_dir) = home_dir() { + xdg_user_dirs::single(&home_dir, &user_dir_file(&home_dir), user_dir_name).remove(user_dir_name) + } else { + None + } + } + + pub fn user_dirs(home_dir_path: &Path) -> HashMap { + xdg_user_dirs::all(home_dir_path, &user_dir_file(home_dir_path)) + } +} + +#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] +pub use self::target_unix_not_mac::{user_dir, user_dirs}; + +#[cfg(target_os = "windows")] +mod target_windows { + + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + use std::path::PathBuf; + use std::ptr; + use std::slice; + + use winapi::shared::winerror; + use winapi::um::{combaseapi, knownfolders, shlobj, shtypes, winbase, winnt}; + + pub fn known_folder(folder_id: shtypes::REFKNOWNFOLDERID) -> Option { + unsafe { + let mut path_ptr: winnt::PWSTR = ptr::null_mut(); + let result = shlobj::SHGetKnownFolderPath(folder_id, 0, ptr::null_mut(), &mut path_ptr); + if result == winerror::S_OK { + let len = winbase::lstrlenW(path_ptr) as usize; + let path = slice::from_raw_parts(path_ptr, len); + let ostr: OsString = OsStringExt::from_wide(path); + combaseapi::CoTaskMemFree(path_ptr as *mut winapi::ctypes::c_void); + Some(PathBuf::from(ostr)) + } else { + None + } + } + } + + pub fn known_folder_profile() -> Option { + known_folder(&knownfolders::FOLDERID_Profile) + } + + pub fn known_folder_roaming_app_data() -> Option { + known_folder(&knownfolders::FOLDERID_RoamingAppData) + } + + pub fn known_folder_local_app_data() -> Option { + known_folder(&knownfolders::FOLDERID_LocalAppData) + } + + pub fn known_folder_music() -> Option { + known_folder(&knownfolders::FOLDERID_Music) + } + + pub fn known_folder_desktop() -> Option { + known_folder(&knownfolders::FOLDERID_Desktop) + } + + pub fn known_folder_documents() -> Option { + known_folder(&knownfolders::FOLDERID_Documents) + } + + pub fn known_folder_downloads() -> Option { + known_folder(&knownfolders::FOLDERID_Downloads) + } + + pub fn known_folder_pictures() -> Option { + known_folder(&knownfolders::FOLDERID_Pictures) + } + + pub fn known_folder_public() -> Option { + known_folder(&knownfolders::FOLDERID_Public) + } + pub fn known_folder_templates() -> Option { + known_folder(&knownfolders::FOLDERID_Templates) + } + pub fn known_folder_videos() -> Option { + known_folder(&knownfolders::FOLDERID_Videos) + } +} + +#[cfg(target_os = "windows")] +pub use self::target_windows::{ + known_folder, known_folder_desktop, known_folder_documents, known_folder_downloads, known_folder_local_app_data, + known_folder_music, known_folder_pictures, known_folder_profile, known_folder_public, + known_folder_roaming_app_data, known_folder_templates, known_folder_videos, +}; diff --git a/vendor/dirs-sys-next/src/xdg_user_dirs.rs b/vendor/dirs-sys-next/src/xdg_user_dirs.rs new file mode 100644 index 000000000..4fabc81d9 --- /dev/null +++ b/vendor/dirs-sys-next/src/xdg_user_dirs.rs @@ -0,0 +1,248 @@ +use std::collections::HashMap; +use std::ffi::OsString; +use std::fs; +use std::io::{self, Read}; +use std::os::unix::ffi::OsStringExt; +use std::path::{Path, PathBuf}; +use std::str; + +/// Returns all XDG user directories obtained from $(XDG_CONFIG_HOME)/user-dirs.dirs. +pub fn all(home_dir_path: &Path, user_dir_file_path: &Path) -> HashMap { + let bytes = read_all(user_dir_file_path).unwrap_or_default(); + parse_user_dirs(home_dir_path, None, &bytes) +} + +/// Returns a single XDG user directory obtained from $(XDG_CONFIG_HOME)/user-dirs.dirs. +pub fn single(home_dir_path: &Path, user_dir_file_path: &Path, user_dir_name: &str) -> HashMap { + let bytes = read_all(user_dir_file_path).unwrap_or_default(); + parse_user_dirs(home_dir_path, Some(user_dir_name), &bytes) +} + +fn parse_user_dirs(home_dir: &Path, user_dir: Option<&str>, bytes: &[u8]) -> HashMap { + let mut user_dirs = HashMap::new(); + + for line in bytes.split(|b| *b == b'\n') { + let mut single_dir_found = false; + let (key, value) = match split_once(line, b'=') { + Some(kv) => kv, + None => continue, + }; + + let key = trim_blank(key); + let key = if key.starts_with(b"XDG_") && key.ends_with(b"_DIR") { + match str::from_utf8(&key[4..key.len() - 4]) { + Ok(key) => { + if user_dir.is_some() && option_contains(user_dir, key) { + single_dir_found = true; + key + } else if user_dir.is_none() { + key + } else { + continue; + } + } + Err(_) => continue, + } + } else { + continue; + }; + + // xdg-user-dirs-update uses double quotes and we don't support anything else. + let value = trim_blank(value); + let mut value = + if value.starts_with(b"\"") && value.ends_with(b"\"") { &value[1..value.len() - 1] } else { continue }; + + // Path should be either relative to the home directory or absolute. + let is_relative = if value == b"$HOME/" { + // "Note: To disable a directory, point it to the homedir." + // Source: https://www.freedesktop.org/wiki/Software/xdg-user-dirs/ + // Additionally directory is reassigned to homedir when removed. + continue; + } else if value.starts_with(b"$HOME/") { + value = &value[b"$HOME/".len()..]; + true + } else if value.starts_with(b"/") { + false + } else { + continue; + }; + + let value = OsString::from_vec(shell_unescape(value)); + + let path = if is_relative { + let mut path = PathBuf::from(&home_dir); + path.push(value); + path + } else { + PathBuf::from(value) + }; + + user_dirs.insert(key.to_owned(), path); + if single_dir_found { + break; + } + } + + user_dirs +} + +/// Reads the entire contents of a file into a byte vector. +fn read_all(path: &Path) -> io::Result> { + let mut file = fs::File::open(path)?; + let mut bytes = Vec::with_capacity(1024); + file.read_to_end(&mut bytes)?; + Ok(bytes) +} + +/// Returns bytes before and after first occurrence of separator. +fn split_once(bytes: &[u8], separator: u8) -> Option<(&[u8], &[u8])> { + bytes.iter().position(|b| *b == separator).map(|i| (&bytes[..i], &bytes[i + 1..])) +} + +/// Returns a slice with leading and trailing characters removed. +fn trim_blank(bytes: &[u8]) -> &[u8] { + // Trim leading characters. + let i = bytes.iter().cloned().take_while(|b| *b == b' ' || *b == b'\t').count(); + let bytes = &bytes[i..]; + + // Trim trailing characters. + let i = bytes.iter().cloned().rev().take_while(|b| *b == b' ' || *b == b'\t').count(); + &bytes[..bytes.len() - i] +} + +/// Unescape bytes escaped with POSIX shell double-quotes rules (as used by xdg-user-dirs-update). +fn shell_unescape(escaped: &[u8]) -> Vec { + // We assume that byte string was created by xdg-user-dirs-update which + // escapes all characters that might potentially have special meaning, + // so there is no need to check if backslash is actually followed by + // $ ` " \ or a . + + let mut unescaped: Vec = Vec::with_capacity(escaped.len()); + let mut i = escaped.iter().cloned(); + + while let Some(b) = i.next() { + if b == b'\\' { + if let Some(b) = i.next() { + unescaped.push(b); + } + } else { + unescaped.push(b); + } + } + + unescaped +} + +fn option_contains(option: Option, value: T) -> bool { + match option { + Some(val) => val == value, + None => false, + } +} + +#[cfg(test)] +mod tests { + use super::{parse_user_dirs, shell_unescape, split_once, trim_blank}; + use std::collections::HashMap; + use std::path::{Path, PathBuf}; + + #[test] + fn test_trim_blank() { + assert_eq!(b"x", trim_blank(b"x")); + assert_eq!(b"", trim_blank(b" \t ")); + assert_eq!(b"hello there", trim_blank(b" \t hello there \t ")); + assert_eq!(b"\r\n", trim_blank(b"\r\n")); + } + + #[test] + fn test_split_once() { + assert_eq!(None, split_once(b"a b c", b'=')); + assert_eq!(Some((b"before".as_ref(), b"after".as_ref())), split_once(b"before=after", b'=')); + } + + #[test] + fn test_shell_unescape() { + assert_eq!(b"abc", shell_unescape(b"abc").as_slice()); + assert_eq!(b"x\\y$z`", shell_unescape(b"x\\\\y\\$z\\`").as_slice()); + } + + #[test] + fn test_parse_empty() { + assert_eq!(HashMap::new(), parse_user_dirs(Path::new("/root/"), None, b"")); + assert_eq!(HashMap::new(), parse_user_dirs(Path::new("/root/"), Some("MUSIC"), b"")); + } + + #[test] + fn test_absolute_path_is_accepted() { + let mut dirs = HashMap::new(); + dirs.insert("MUSIC".to_owned(), PathBuf::from("/media/music")); + let bytes = br#"XDG_MUSIC_DIR="/media/music""#; + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes)); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes)); + } + + #[test] + fn test_relative_path_is_rejected() { + let dirs = HashMap::new(); + let bytes = br#"XDG_MUSIC_DIR="music""#; + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes)); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes)); + } + + #[test] + fn test_relative_to_home() { + let mut dirs = HashMap::new(); + dirs.insert("MUSIC".to_owned(), PathBuf::from("/home/john/Music")); + let bytes = br#"XDG_MUSIC_DIR="$HOME/Music""#; + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes)); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes)); + } + + #[test] + fn test_disabled_directory() { + let dirs = HashMap::new(); + let bytes = br#"XDG_MUSIC_DIR="$HOME/""#; + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes)); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes)); + } + + #[test] + fn test_parse_user_dirs() { + let mut dirs: HashMap = HashMap::new(); + dirs.insert("DESKTOP".to_string(), PathBuf::from("/home/bob/Desktop")); + dirs.insert("DOWNLOAD".to_string(), PathBuf::from("/home/bob/Downloads")); + dirs.insert("PICTURES".to_string(), PathBuf::from("/home/eve/pics")); + + let bytes = br#" +# This file is written by xdg-user-dirs-update +# If you want to change or add directories, just edit the line you're +# interested in. All local changes will be retained on the next run. +# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped +# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an +# absolute path. No other format is supported. +XDG_DESKTOP_DIR="$HOME/Desktop" +XDG_DOWNLOAD_DIR="$HOME/Downloads" +XDG_TEMPLATES_DIR="" +XDG_PUBLICSHARE_DIR="$HOME" +XDG_DOCUMENTS_DIR="$HOME/" +XDG_PICTURES_DIR="/home/eve/pics" +XDG_VIDEOS_DIR="$HOxyzME/Videos" +"#; + + assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), None, bytes)); + + let mut dirs: HashMap = HashMap::new(); + dirs.insert("DESKTOP".to_string(), PathBuf::from("/home/bob/Desktop")); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("DESKTOP"), bytes)); + + let mut dirs: HashMap = HashMap::new(); + dirs.insert("PICTURES".to_string(), PathBuf::from("/home/eve/pics")); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("PICTURES"), bytes)); + + let dirs: HashMap = HashMap::new(); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("TEMPLATES"), bytes)); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("PUBLICSHARE"), bytes)); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("DOCUMENTS"), bytes)); + assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("VIDEOS"), bytes)); + } +} -- cgit v1.2.3