xattr-1.0.0/.cargo_vcs_info.json0000644000000001360000000000100121740ustar { "git": { "sha1": "ff560090847031db0591c1019293cc1f590c6a1e" }, "path_in_vcs": "" }xattr-1.0.0/.cirrus.yml000064400000000000000000000021211046102023000130700ustar 00000000000000cargo_cache: folder: $CARGO_HOME/registry fingerprint_script: cat Cargo.lock || echo "" env: RUSTFLAGS: -D warnings RUSTDOCFLAGS: -D warnings test: &TEST test_script: - . $HOME/.cargo/env || true - cargo test doc_script: - . $HOME/.cargo/env || true - cargo doc --no-deps task: name: FreeBSD freebsd_instance: image: freebsd-12-3-release-amd64 # Install Rust setup_script: - pkg install -y curl - curl https://sh.rustup.rs -sSf --output rustup.sh - sh rustup.sh -y << : *TEST before_cache_script: rm -rf $CARGO_HOME/registry/index task: name: MacOS env: TARGET: x86_64-apple-darwin osx_instance: image: big-sur-xcode setup_script: - curl --proto '=https' --tlsv1.2 -sSf -o rustup.sh https://sh.rustup.rs - sh rustup.sh -y << : *TEST before_cache_script: rm -rf $CARGO_HOME/registry/index task: matrix: - name: Linux container: image: rust:latest - name: Linux nightly container: image: rustlang/rust:nightly << : *TEST before_cache_script: rm -rf $CARGO_HOME/registry/index xattr-1.0.0/.gitignore000064400000000000000000000000221046102023000127460ustar 00000000000000target Cargo.lock xattr-1.0.0/Cargo.toml0000644000000017030000000000100101730ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "xattr" version = "1.0.0" authors = ["Steven Allen "] description = "unix extended filesystem attributes" documentation = "https://docs.rs/xattr" readme = "README.md" keywords = [ "xattr", "filesystem", "unix", ] license = "MIT/Apache-2.0" repository = "https://github.com/Stebalien/xattr" [dependencies.libc] version = "0.2.44" [dev-dependencies.tempfile] version = "3" [features] default = ["unsupported"] unsupported = [] xattr-1.0.0/Cargo.toml.orig000064400000000000000000000013701046102023000136540ustar 00000000000000[package] name = "xattr" edition = "2021" version = "1.0.0" authors = ["Steven Allen "] description = "unix extended filesystem attributes" documentation = "https://docs.rs/xattr" repository = "https://github.com/Stebalien/xattr" keywords = ["xattr", "filesystem", "unix"] license = "MIT/Apache-2.0" [features] default = ["unsupported"] # Adds a dummy implementation for unsupported platforms. This is useful when # developing platform-independent code that doesn't absolutely need xattr # support. # # You can disable this feature if you want compilation to fail on unsupported # platforms. This would make sense if you absolutely need xattr support. unsupported = [] [dependencies] libc = "0.2.44" [dev-dependencies] tempfile = "3" xattr-1.0.0/LICENSE-APACHE000064400000000000000000000251371046102023000127200ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. xattr-1.0.0/LICENSE-MIT000064400000000000000000000020401046102023000124140ustar 00000000000000Copyright (c) 2015 Steven Allen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. xattr-1.0.0/README.md000064400000000000000000000014421046102023000122440ustar 00000000000000xattr ===== [![Build Status](https://api.cirrus-ci.com/github/Stebalien/xattr.svg)](https://cirrus-ci.com/github/Stebalien/xattr) A small library for setting, getting, and listing extended attributes. Supported Platforms: Android, Linux, MacOS, FreeBSD, and NetBSD. API Documentation: https://stebalien.github.com/xattr/xattr/ Unsupported Platforms -------------------------- This library includes no-op support for unsupported platforms. That is, it will build on *all* platforms but always fail on unsupported platforms. 1. You can turn this off by disabling the default `unsupported` feature. If you do so, this library will fail to compile on unsupported platforms. 2. Alternatively, you can detect unsupported platforms at runtime by checking the `xattr::SUPPORTED_PLATFORM` boolean. xattr-1.0.0/src/error.rs000064400000000000000000000015671046102023000132630ustar 00000000000000use std::error::Error; use std::fmt; /// The error type returned on unsupported platforms. /// /// On unsupported platforms, all operations will fail with an `io::Error` with /// a kind `io::ErrorKind::Unsupported` and an `UnsupportedPlatformError` error as the inner error. /// While you *could* check the inner error, it's probably simpler just to check /// `xattr::SUPPORTED_PLATFORM`. /// /// This error mostly exists for pretty error messages. #[derive(Copy, Clone, Debug)] pub struct UnsupportedPlatformError; impl Error for UnsupportedPlatformError { fn description(&self) -> &str { "unsupported platform" } } impl fmt::Display for UnsupportedPlatformError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "unsupported platform, please file a bug at `https://github.com/Stebalien/xattr'" ) } } xattr-1.0.0/src/lib.rs000064400000000000000000000062611046102023000126740ustar 00000000000000#![allow(clippy::comparison_chain)] //! A pure-Rust library to manage extended attributes. //! //! It provides support for manipulating extended attributes //! (`xattrs`) on modern Unix filesystems. See the `attr(5)` //! manpage for more details. //! //! An extension trait [`FileExt`] is provided to directly work with //! standard `File` objects and file descriptors. //! //! NOTE: In case of a symlink as path argument, all methods //! in this library work on the symlink itself **without** //! de-referencing it. //! //! ```rust //! let mut xattrs = xattr::list("/").unwrap().peekable(); //! //! if xattrs.peek().is_none() { //! println!("no xattr set on root"); //! return; //! } //! //! println!("Extended attributes:"); //! for attr in xattrs { //! println!(" - {:?}", attr); //! } //! ``` mod error; mod sys; mod util; use std::ffi::OsStr; use std::fs::File; use std::io; use std::os::unix::io::AsRawFd; use std::path::Path; pub use error::UnsupportedPlatformError; pub use sys::{XAttrs, SUPPORTED_PLATFORM}; /// Get an extended attribute for the specified file. pub fn get(path: P, name: N) -> io::Result>> where P: AsRef, N: AsRef, { util::extract_noattr(sys::get_path(path.as_ref(), name.as_ref())) } /// Set an extended attribute on the specified file. pub fn set(path: P, name: N, value: &[u8]) -> io::Result<()> where P: AsRef, N: AsRef, { sys::set_path(path.as_ref(), name.as_ref(), value) } /// Remove an extended attribute from the specified file. pub fn remove(path: P, name: N) -> io::Result<()> where P: AsRef, N: AsRef, { sys::remove_path(path.as_ref(), name.as_ref()) } /// List extended attributes attached to the specified file. /// /// Note: this may not list *all* attributes. Speficially, it definitely won't list any trusted /// attributes unless you are root and it may not list system attributes. pub fn list

(path: P) -> io::Result where P: AsRef, { sys::list_path(path.as_ref()) } /// Extension trait to manipulate extended attributes on `File`-like objects. pub trait FileExt: AsRawFd { /// Get an extended attribute for the specified file. fn get_xattr(&self, name: N) -> io::Result>> where N: AsRef, { util::extract_noattr(sys::get_fd(self.as_raw_fd(), name.as_ref())) } /// Set an extended attribute on the specified file. fn set_xattr(&self, name: N, value: &[u8]) -> io::Result<()> where N: AsRef, { sys::set_fd(self.as_raw_fd(), name.as_ref(), value) } /// Remove an extended attribute from the specified file. fn remove_xattr(&self, name: N) -> io::Result<()> where N: AsRef, { sys::remove_fd(self.as_raw_fd(), name.as_ref()) } /// List extended attributes attached to the specified file. /// /// Note: this may not list *all* attributes. Speficially, it definitely won't list any trusted /// attributes unless you are root and it may not list system attributes. fn list_xattr(&self) -> io::Result { sys::list_fd(self.as_raw_fd()) } } impl FileExt for File {} xattr-1.0.0/src/sys/bsd.rs000064400000000000000000000216171046102023000135160ustar 00000000000000//! FreeBSD and NetBSD xattr support. use std::ffi::{CString, OsStr, OsString}; use std::io; use std::mem; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::os::unix::io::RawFd; use std::path::Path; use libc::{c_int, c_void, size_t, EPERM}; use libc::{ extattr_delete_fd, extattr_delete_link, extattr_get_fd, extattr_get_link, extattr_list_fd, extattr_list_link, extattr_set_fd, extattr_set_link, EXTATTR_NAMESPACE_SYSTEM, EXTATTR_NAMESPACE_USER, }; use crate::util::{allocate_loop, path_to_c}; const EXTATTR_NAMESPACE_USER_STRING: &'static str = "user"; const EXTATTR_NAMESPACE_SYSTEM_STRING: &'static str = "system"; const EXTATTR_NAMESPACE_NAMES: [&'static str; 3] = [ "empty", EXTATTR_NAMESPACE_USER_STRING, EXTATTR_NAMESPACE_SYSTEM_STRING, ]; /// An iterator over a set of extended attributes names. pub struct XAttrs { user_attrs: Box<[u8]>, system_attrs: Box<[u8]>, offset: usize, } impl Clone for XAttrs { fn clone(&self) -> Self { XAttrs { user_attrs: Vec::from(&*self.user_attrs).into_boxed_slice(), system_attrs: Vec::from(&*self.system_attrs).into_boxed_slice(), offset: self.offset, } } fn clone_from(&mut self, other: &XAttrs) { self.offset = other.offset; let mut data = mem::replace(&mut self.user_attrs, Box::new([])).into_vec(); data.extend(other.user_attrs.iter().cloned()); self.user_attrs = data.into_boxed_slice(); data = mem::replace(&mut self.system_attrs, Box::new([])).into_vec(); data.extend(other.system_attrs.iter().cloned()); self.system_attrs = data.into_boxed_slice(); } } impl Iterator for XAttrs { type Item = OsString; fn next(&mut self) -> Option { if self.user_attrs.is_empty() && self.system_attrs.is_empty() { return None; } if self.offset == self.user_attrs.len() + self.system_attrs.len() { return None; } let data = if self.offset < self.system_attrs.len() { &self.system_attrs[self.offset..] } else { &self.user_attrs[self.offset - self.system_attrs.len()..] }; let siz = data[0] as usize; self.offset += siz + 1; if self.offset < self.system_attrs.len() { Some(prefix_namespace( OsStr::from_bytes(&data[1..siz + 1]), EXTATTR_NAMESPACE_SYSTEM, )) } else { Some(prefix_namespace( OsStr::from_bytes(&data[1..siz + 1]), EXTATTR_NAMESPACE_USER, )) } } fn size_hint(&self) -> (usize, Option) { if self.user_attrs.len() + self.system_attrs.len() == self.offset { (0, Some(0)) } else { (1, None) } } } // This could use libc::extattr_string_to_namespace, but it's awkward because // that requires nul-terminated strings, which Rust's std is loathe to provide. fn name_to_ns(name: &OsStr) -> io::Result<(c_int, CString)> { let mut groups = name.as_bytes().splitn(2, |&b| b == b'.').take(2); let nsname = match groups.next() { Some(s) => s, None => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "couldn't find namespace", )) } }; let propname = match groups.next() { Some(s) => s, None => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "couldn't find attribute", )) } }; let ns_int = match EXTATTR_NAMESPACE_NAMES .iter() .position(|&s| s.as_bytes() == nsname) { Some(i) => i, None => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "no matching namespace", )) } }; Ok((ns_int as c_int, CString::new(propname)?)) } fn prefix_namespace(attr: &OsStr, ns: c_int) -> OsString { let nsname = EXTATTR_NAMESPACE_NAMES[ns as usize]; let mut v = Vec::with_capacity(nsname.as_bytes().len() + attr.as_bytes().len() + 1); v.extend(nsname.as_bytes()); v.extend(".".as_bytes()); v.extend(attr.as_bytes()); OsString::from_vec(v) } pub fn get_fd(fd: RawFd, name: &OsStr) -> io::Result> { let (ns, name) = name_to_ns(name)?; unsafe { allocate_loop(|buf, len| { extattr_get_fd(fd, ns, name.as_ptr(), buf as *mut c_void, len as size_t) }) } } pub fn set_fd(fd: RawFd, name: &OsStr, value: &[u8]) -> io::Result<()> { let (ns, name) = name_to_ns(name)?; let ret = unsafe { extattr_set_fd( fd, ns, name.as_ptr(), value.as_ptr() as *const c_void, value.len() as size_t, ) }; if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn remove_fd(fd: RawFd, name: &OsStr) -> io::Result<()> { let (ns, name) = name_to_ns(name)?; let ret = unsafe { extattr_delete_fd(fd, ns, name.as_ptr()) }; if ret != 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn list_fd(fd: RawFd) -> io::Result { let sysvec = unsafe { let res = allocate_loop(|buf, len| { extattr_list_fd( fd, EXTATTR_NAMESPACE_SYSTEM, buf as *mut c_void, len as size_t, ) }); // On FreeBSD, system attributes require root privileges to view. However, // to mimic the behavior of listxattr in linux and osx, we need to query // them anyway and return empty results if we get EPERM match res { Ok(v) => v, Err(err) => { if err.raw_os_error() == Some(EPERM) { Vec::new() } else { return Err(err); } } } }; let uservec = unsafe { let res = allocate_loop(|buf, len| { extattr_list_fd( fd, EXTATTR_NAMESPACE_USER, buf as *mut c_void, len as size_t, ) }); match res { Ok(v) => v, Err(err) => return Err(err), } }; Ok(XAttrs { system_attrs: sysvec.into_boxed_slice(), user_attrs: uservec.into_boxed_slice(), offset: 0, }) } pub fn get_path(path: &Path, name: &OsStr) -> io::Result> { let (ns, name) = name_to_ns(name)?; let path = path_to_c(path)?; unsafe { allocate_loop(|buf, len| { extattr_get_link( path.as_ptr(), ns, name.as_ptr(), buf as *mut c_void, len as size_t, ) }) } } pub fn set_path(path: &Path, name: &OsStr, value: &[u8]) -> io::Result<()> { let (ns, name) = name_to_ns(name)?; let path = path_to_c(path)?; let ret = unsafe { extattr_set_link( path.as_ptr(), ns, name.as_ptr(), value.as_ptr() as *const c_void, value.len() as size_t, ) }; if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn remove_path(path: &Path, name: &OsStr) -> io::Result<()> { let (ns, name) = name_to_ns(name)?; let path = path_to_c(path)?; let ret = unsafe { extattr_delete_link(path.as_ptr(), ns, name.as_ptr()) }; if ret != 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn list_path(path: &Path) -> io::Result { let path = path_to_c(path)?; let sysvec = unsafe { let res = allocate_loop(|buf, len| { extattr_list_link( path.as_ptr(), EXTATTR_NAMESPACE_SYSTEM, buf as *mut c_void, len as size_t, ) }); // On FreeBSD, system attributes require root privileges to view. However, // to mimic the behavior of listxattr in linux and osx, we need to query // them anyway and return empty results if we get EPERM match res { Ok(v) => v, Err(err) => { if err.raw_os_error() == Some(EPERM) { Vec::new() } else { return Err(err); } } } }; let uservec = unsafe { let res = allocate_loop(|buf, len| { extattr_list_link( path.as_ptr(), EXTATTR_NAMESPACE_USER, buf as *mut c_void, len as size_t, ) }); match res { Ok(v) => v, Err(err) => return Err(err), } }; Ok(XAttrs { system_attrs: sysvec.into_boxed_slice(), user_attrs: uservec.into_boxed_slice(), offset: 0, }) } xattr-1.0.0/src/sys/linux_macos/linux.rs000064400000000000000000000010301046102023000164110ustar 00000000000000use libc::{c_char, c_int, c_void, size_t}; pub use libc::{fgetxattr, flistxattr, fremovexattr, lgetxattr, llistxattr, lremovexattr}; pub unsafe fn fsetxattr( fd: c_int, name: *const c_char, value: *const c_void, size: size_t, ) -> c_int { use libc::fsetxattr; fsetxattr(fd, name, value, size, 0) } pub unsafe fn lsetxattr( path: *const c_char, name: *const c_char, value: *const c_void, size: size_t, ) -> c_int { use libc::lsetxattr; lsetxattr(path, name, value, size, 0) } xattr-1.0.0/src/sys/linux_macos/macos.rs000064400000000000000000000031571046102023000163700ustar 00000000000000use libc::{c_char, c_int, c_void, size_t, ssize_t}; const XATTR_NOFOLLOW: c_int = 0x0001; #[inline(always)] pub unsafe fn fremovexattr(fd: c_int, name: *const c_char) -> c_int { use libc::fremovexattr; fremovexattr(fd, name, 0) } #[inline(always)] pub unsafe fn fsetxattr( fd: c_int, name: *const c_char, value: *const c_void, size: size_t, ) -> c_int { use libc::fsetxattr; fsetxattr(fd, name, value, size, 0, 0) } #[inline(always)] pub unsafe fn fgetxattr( fd: c_int, name: *const c_char, value: *mut c_void, size: size_t, ) -> ssize_t { use libc::fgetxattr; fgetxattr(fd, name, value, size, 0, 0) } #[inline(always)] pub unsafe fn flistxattr(fd: c_int, buf: *mut c_char, size: size_t) -> ssize_t { use libc::flistxattr; flistxattr(fd, buf, size, 0) } #[inline(always)] pub unsafe fn lremovexattr(path: *const c_char, name: *const c_char) -> c_int { use libc::removexattr; removexattr(path, name, XATTR_NOFOLLOW) } #[inline(always)] pub unsafe fn lsetxattr( path: *const c_char, name: *const c_char, value: *const c_void, size: size_t, ) -> c_int { use libc::setxattr; setxattr(path, name, value, size, 0, XATTR_NOFOLLOW) } #[inline(always)] pub unsafe fn lgetxattr( path: *const c_char, name: *const c_char, value: *mut c_void, size: size_t, ) -> ssize_t { use libc::getxattr; getxattr(path, name, value, size, 0, XATTR_NOFOLLOW) } #[inline(always)] pub unsafe fn llistxattr(path: *const c_char, buf: *mut c_char, size: size_t) -> ssize_t { use libc::listxattr; listxattr(path, buf, size, XATTR_NOFOLLOW) } xattr-1.0.0/src/sys/linux_macos/mod.rs000064400000000000000000000104321046102023000160370ustar 00000000000000#[cfg(any(target_os = "linux", target_os = "android"))] mod linux; #[cfg(any(target_os = "linux", target_os = "android"))] use self::linux::*; #[cfg(target_os = "macos")] mod macos; #[cfg(target_os = "macos")] use self::macos::*; use std::ffi::{OsStr, OsString}; use std::io; use std::mem; use std::os::unix::ffi::OsStrExt; use std::os::unix::io::RawFd; use std::path::Path; use libc::{c_char, c_void, size_t}; use crate::util::{allocate_loop, name_to_c, path_to_c}; /// An iterator over a set of extended attributes names. pub struct XAttrs { data: Box<[u8]>, offset: usize, } impl Clone for XAttrs { fn clone(&self) -> Self { XAttrs { data: Vec::from(&*self.data).into_boxed_slice(), offset: self.offset, } } fn clone_from(&mut self, other: &XAttrs) { self.offset = other.offset; let mut data = mem::replace(&mut self.data, Box::new([])).into_vec(); data.extend(other.data.iter().cloned()); self.data = data.into_boxed_slice(); } } // Yes, I could avoid these allocations on linux/macos. However, if we ever want to be freebsd // compatible, we need to be able to prepend the namespace to the extended attribute names. // Furthermore, borrowing makes the API messy. impl Iterator for XAttrs { type Item = OsString; fn next(&mut self) -> Option { let data = &self.data[self.offset..]; if data.is_empty() { None } else { // always null terminated (unless empty). let end = data.iter().position(|&b| b == 0u8).unwrap(); self.offset += end + 1; Some(OsStr::from_bytes(&data[..end]).to_owned()) } } fn size_hint(&self) -> (usize, Option) { if self.data.len() == self.offset { (0, Some(0)) } else { (1, None) } } } pub fn get_fd(fd: RawFd, name: &OsStr) -> io::Result> { let name = name_to_c(name)?; unsafe { allocate_loop(|buf, len| fgetxattr(fd, name.as_ptr(), buf as *mut c_void, len as size_t)) } } pub fn set_fd(fd: RawFd, name: &OsStr, value: &[u8]) -> io::Result<()> { let name = name_to_c(name)?; let ret = unsafe { fsetxattr( fd, name.as_ptr(), value.as_ptr() as *const c_void, value.len() as size_t, ) }; if ret != 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn remove_fd(fd: RawFd, name: &OsStr) -> io::Result<()> { let name = name_to_c(name)?; let ret = unsafe { fremovexattr(fd, name.as_ptr()) }; if ret != 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn list_fd(fd: RawFd) -> io::Result { let vec = unsafe { allocate_loop(|buf, len| flistxattr(fd, buf as *mut c_char, len as size_t))? }; Ok(XAttrs { data: vec.into_boxed_slice(), offset: 0, }) } pub fn get_path(path: &Path, name: &OsStr) -> io::Result> { let name = name_to_c(name)?; let path = path_to_c(path)?; unsafe { allocate_loop(|buf, len| { lgetxattr( path.as_ptr(), name.as_ptr(), buf as *mut c_void, len as size_t, ) }) } } pub fn set_path(path: &Path, name: &OsStr, value: &[u8]) -> io::Result<()> { let name = name_to_c(name)?; let path = path_to_c(path)?; let ret = unsafe { lsetxattr( path.as_ptr(), name.as_ptr(), value.as_ptr() as *const c_void, value.len() as size_t, ) }; if ret != 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn remove_path(path: &Path, name: &OsStr) -> io::Result<()> { let name = name_to_c(name)?; let path = path_to_c(path)?; let ret = unsafe { lremovexattr(path.as_ptr(), name.as_ptr()) }; if ret != 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } pub fn list_path(path: &Path) -> io::Result { let path = path_to_c(path)?; let vec = unsafe { allocate_loop(|buf, len| llistxattr(path.as_ptr(), buf as *mut c_char, len as size_t))? }; Ok(XAttrs { data: vec.into_boxed_slice(), offset: 0, }) } xattr-1.0.0/src/sys/mod.rs000064400000000000000000000031131046102023000135140ustar 00000000000000macro_rules! platforms { ($($($platform:expr);* => $module:ident),*) => { $( #[cfg(any($(target_os = $platform),*))] #[cfg_attr(not(any($(target_os = $platform),*)), allow(dead_code))] mod $module; #[cfg(any($(target_os = $platform),*))] pub use self::$module::*; #[cfg(any($(target_os = $platform),*))] #[allow(deprecated)] // other platforms still use ENOATTR pub const ENOATTR: ::libc::c_int = ::libc::ENOATTR; )* #[cfg(all(feature = "unsupported", not(any($($(target_os = $platform),*),*))))] #[cfg_attr(any($($(target_os = $platform),*),*), allow(dead_code))] mod unsupported; #[cfg(all(feature = "unsupported", not(any($($(target_os = $platform),*),*))))] pub use self::unsupported::*; #[cfg(all(feature = "unsupported", not(any($($(target_os = $platform),*),*))))] pub const ENOATTR: ::libc::c_int = 0; /// A constant indicating whether or not the target platform is supported. /// /// To make programmer's lives easier, this library builds on all platforms. /// However, all function calls on unsupported platforms will return /// `io::Error`s. /// /// Note: If you would like compilation to simply fail on unsupported platforms, /// turn of the `unsupported` feature. pub const SUPPORTED_PLATFORM: bool = cfg!(any($($(target_os = $platform),*),*)); } } platforms! { "android"; "linux"; "macos" => linux_macos, "freebsd"; "netbsd" => bsd } xattr-1.0.0/src/sys/unsupported.rs000064400000000000000000000034031046102023000153270ustar 00000000000000use std::ffi::{OsStr, OsString}; use std::io; use std::os::unix::io::RawFd; use std::path::Path; use UnsupportedPlatformError; /// An iterator over a set of extended attributes names. #[derive(Clone, Debug)] pub struct XAttrs; impl Iterator for XAttrs { type Item = OsString; fn next(&mut self) -> Option { unreachable!("this should never exist") } fn size_hint(&self) -> (usize, Option) { unreachable!("this should never exist") } } pub fn get_fd(_: RawFd, _: &OsStr) -> io::Result> { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } pub fn set_fd(_: RawFd, _: &OsStr, _: &[u8]) -> io::Result<()> { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } pub fn remove_fd(_: RawFd, _: &OsStr) -> io::Result<()> { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } pub fn list_fd(_: RawFd) -> io::Result { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } pub fn get_path(_: &Path, _: &OsStr) -> io::Result> { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } pub fn set_path(_: &Path, _: &OsStr, _: &[u8]) -> io::Result<()> { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } pub fn remove_path(_: &Path, _: &OsStr) -> io::Result<()> { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } pub fn list_path(_: &Path) -> io::Result { Err(io::Error::new( io::ErrorKind::Unsupported, UnsupportedPlatformError, )) } xattr-1.0.0/src/util.rs000064400000000000000000000035071046102023000131030ustar 00000000000000use std::ffi::CString; use std::ffi::OsStr; use std::io; use std::os::unix::ffi::OsStrExt; use std::path::Path; use std::ptr; use libc::{ssize_t, ERANGE}; // Need to use this one as libc only defines this on supported platforms. Given // that we want to at least compile on unsupported platforms, we define this in // our platform-specific modules. use crate::sys::ENOATTR; #[allow(dead_code)] pub fn name_to_c(name: &OsStr) -> io::Result { match CString::new(name.as_bytes()) { Ok(name) => Ok(name), Err(_) => Err(io::Error::new( io::ErrorKind::InvalidInput, "name must not contain null bytes", )), } } pub fn path_to_c(path: &Path) -> io::Result { match CString::new(path.as_os_str().as_bytes()) { Ok(name) => Ok(name), Err(_) => Err(io::Error::new(io::ErrorKind::NotFound, "file not found")), } } pub fn extract_noattr(result: io::Result>) -> io::Result>> { result.map(Some).or_else(|e| match e.raw_os_error() { Some(ENOATTR) => Ok(None), _ => Err(e), }) } pub unsafe fn allocate_loop ssize_t>(mut f: F) -> io::Result> { let mut vec: Vec = Vec::new(); loop { let ret = (f)(ptr::null_mut(), 0); if ret < 0 { return Err(io::Error::last_os_error()); } else if ret == 0 { break; } vec.reserve_exact(ret as usize); let ret = (f)(vec.as_mut_ptr(), vec.capacity()); if ret >= 0 { vec.set_len(ret as usize); break; } else { let error = io::Error::last_os_error(); if error.raw_os_error() == Some(ERANGE) { continue; } return Err(error); } } vec.shrink_to_fit(); Ok(vec) } xattr-1.0.0/tests/main.rs000064400000000000000000000061661046102023000134310ustar 00000000000000use std::collections::BTreeSet; use std::ffi::OsStr; use xattr::FileExt; use tempfile::{tempfile_in, NamedTempFile}; #[test] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))] fn test_fd() { use std::os::unix::ffi::OsStrExt; // Only works on "real" filesystems. let tmp = tempfile_in("/var/tmp").unwrap(); assert!(tmp.get_xattr("user.test").unwrap().is_none()); assert_eq!( tmp.list_xattr() .unwrap() .filter(|x| x.as_bytes().starts_with(b"user.")) .count(), 0 ); tmp.set_xattr("user.test", b"my test").unwrap(); assert_eq!(tmp.get_xattr("user.test").unwrap().unwrap(), b"my test"); assert_eq!( tmp.list_xattr() .unwrap() .filter(|x| x.as_bytes().starts_with(b"user.")) .collect::>(), vec![OsStr::new("user.test")] ); tmp.remove_xattr("user.test").unwrap(); assert!(tmp.get_xattr("user.test").unwrap().is_none()); assert_eq!( tmp.list_xattr() .unwrap() .filter(|x| x.as_bytes().starts_with(b"user.")) .count(), 0 ); } #[test] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))] fn test_path() { use std::os::unix::ffi::OsStrExt; // Only works on "real" filesystems. let tmp = NamedTempFile::new_in("/var/tmp").unwrap(); assert!(xattr::get(tmp.path(), "user.test").unwrap().is_none()); assert_eq!( xattr::list(tmp.path()) .unwrap() .filter(|x| x.as_bytes().starts_with(b"user.")) .count(), 0 ); xattr::set(tmp.path(), "user.test", b"my test").unwrap(); assert_eq!( xattr::get(tmp.path(), "user.test").unwrap().unwrap(), b"my test" ); assert_eq!( xattr::list(tmp.path()) .unwrap() .filter(|x| x.as_bytes().starts_with(b"user.")) .collect::>(), vec![OsStr::new("user.test")] ); xattr::remove(tmp.path(), "user.test").unwrap(); assert!(xattr::get(tmp.path(), "user.test").unwrap().is_none()); assert_eq!( xattr::list(tmp.path()) .unwrap() .filter(|x| x.as_bytes().starts_with(b"user.")) .count(), 0 ); } #[test] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))] fn test_missing() { assert!(xattr::get("/var/empty/does-not-exist", "user.test").is_err()); } #[test] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))] fn test_multi() { use std::os::unix::ffi::OsStrExt; // Only works on "real" filesystems. let tmp = tempfile_in("/var/tmp").unwrap(); let mut items: BTreeSet<_> = [ OsStr::new("user.test1"), OsStr::new("user.test2"), OsStr::new("user.test3"), ] .iter() .cloned() .collect(); for it in &items { tmp.set_xattr(it, b"value").unwrap(); } for it in tmp .list_xattr() .unwrap() .filter(|x| x.as_bytes().starts_with(&*b"user.")) { assert!(items.remove(&*it)); } assert!(items.is_empty()); }