Debian Codegraph @

debian/rust-vendor/xattr/src/sys/bsd.rs

raw
1 //! FreeBSD and NetBSD xattr support.
2
3 use libc::{c_int, c_void, size_t, EPERM};
4 use std::ffi::{CString, OsStr, OsString};
5 use std::mem::MaybeUninit;
6 use std::os::unix::ffi::{OsStrExt, OsStringExt};
7 use std::os::unix::io::{AsRawFd, BorrowedFd};
8 use std::path::Path;
9 use std::ptr;
10 use std::{io, slice};
11
12 use libc::{
13 extattr_delete_fd, extattr_delete_file, extattr_delete_link, extattr_get_fd, extattr_get_file,
14 extattr_get_link, extattr_list_fd, extattr_list_file, extattr_list_link, extattr_set_fd,
15 extattr_set_file, extattr_set_link, EXTATTR_NAMESPACE_SYSTEM, EXTATTR_NAMESPACE_USER,
16 };
17
18 pub const ENOATTR: i32 = libc::ENOATTR;
19 pub const ERANGE: i32 = libc::ERANGE;
20
21 const EXTATTR_NAMESPACE_USER_STRING: &str = "user";
22 const EXTATTR_NAMESPACE_SYSTEM_STRING: &str = "system";
23 const EXTATTR_NAMESPACE_NAMES: [&str; 3] = [
24 "empty",
25 EXTATTR_NAMESPACE_USER_STRING,
26 EXTATTR_NAMESPACE_SYSTEM_STRING,
27 ];
28
29 fn path_to_c(path: &Path) -> io::Result<CString> {
30 match CString::new(path.as_os_str().as_bytes()) {
31 Ok(name) => Ok(name),
32 Err(_) => Err(io::Error::new(io::ErrorKind::NotFound, "file not found")),
33 }
34 }
35
36 #[inline]
37 fn cvt(res: libc::ssize_t) -> io::Result<usize> {
38 if res < 0 {
39 Err(io::Error::last_os_error())
40 } else {
41 Ok(res as usize)
42 }
43 }
44
45 #[inline]
46 fn slice_parts(buf: &mut [MaybeUninit<u8>]) -> (*mut c_void, size_t) {
47 if buf.is_empty() {
48 (ptr::null_mut(), 0)
49 } else {
50 (buf.as_mut_ptr().cast(), buf.len() as size_t)
51 }
52 }
53
54 fn allocate_loop<F: Fn(*mut c_void, size_t) -> libc::ssize_t>(f: F) -> io::Result<Vec<u8>> {
55 crate::util::allocate_loop(
56 |buf| unsafe {
57 let (ptr, len) = slice_parts(buf);
58 let new_len = cvt(f(ptr, len))?;
59 if new_len < len {
60 Ok(slice::from_raw_parts_mut(ptr.cast(), new_len))
61 } else {
62 // If the length of the value isn't strictly smaller than the length of the value
63 // read, there may be more to read. Fake an ERANGE error so we can try again with a
64 // bigger buffer.
65 Err(io::Error::from_raw_os_error(crate::sys::ERANGE))
66 }
67 },
68 // Estimate size + 1 because, on freebsd, the only way to tell if we've read the entire
69 // value is read a value smaller than the buffer we passed.
70 || Ok(cvt(f(ptr::null_mut(), 0))? + 1),
71 )
72 }
73
74 /// An iterator over a set of extended attributes names.
75 #[derive(Default, Clone)]
76 pub struct XAttrs {
77 user_attrs: Box<[u8]>,
78 system_attrs: Box<[u8]>,
79 offset: usize,
80 }
81
82 impl Iterator for XAttrs {
83 type Item = OsString;
84 fn next(&mut self) -> Option<OsString> {
85 if self.user_attrs.is_empty() && self.system_attrs.is_empty() {
86 return None;
87 }
88
89 if self.offset == self.user_attrs.len() + self.system_attrs.len() {
90 return None;
91 }
92
93 let data = if self.offset < self.system_attrs.len() {
94 &self.system_attrs[self.offset..]
95 } else {
96 &self.user_attrs[self.offset - self.system_attrs.len()..]
97 };
98
99 let siz = data[0] as usize;
100
101 self.offset += siz + 1;
102 if self.offset < self.system_attrs.len() {
103 Some(prefix_namespace(
104 OsStr::from_bytes(&data[1..siz + 1]),
105 EXTATTR_NAMESPACE_SYSTEM,
106 ))
107 } else {
108 Some(prefix_namespace(
109 OsStr::from_bytes(&data[1..siz + 1]),
110 EXTATTR_NAMESPACE_USER,
111 ))
112 }
113 }
114
115 fn size_hint(&self) -> (usize, Option<usize>) {
116 if self.user_attrs.len() + self.system_attrs.len() == self.offset {
117 (0, Some(0))
118 } else {
119 (1, None)
120 }
121 }
122 }
123
124 // This could use libc::extattr_string_to_namespace, but it's awkward because
125 // that requires nul-terminated strings, which Rust's std is loathe to provide.
126 fn name_to_ns(name: &OsStr) -> io::Result<(c_int, CString)> {
127 let mut groups = name.as_bytes().splitn(2, |&b| b == b'.').take(2);
128 let nsname = match groups.next() {
129 Some(s) => s,
130 None => {
131 return Err(io::Error::new(
132 io::ErrorKind::InvalidInput,
133 "couldn't find namespace",
134 ))
135 }
136 };
137
138 let propname = match groups.next() {
139 Some(s) => s,
140 None => {
141 return Err(io::Error::new(
142 io::ErrorKind::InvalidInput,
143 "couldn't find attribute",
144 ))
145 }
146 };
147
148 let ns_int = match EXTATTR_NAMESPACE_NAMES
149 .iter()
150 .position(|&s| s.as_bytes() == nsname)
151 {
152 Some(i) => i,
153 None => {
154 return Err(io::Error::new(
155 io::ErrorKind::InvalidInput,
156 "no matching namespace",
157 ))
158 }
159 };
160
161 Ok((ns_int as c_int, CString::new(propname)?))
162 }
163
164 fn prefix_namespace(attr: &OsStr, ns: c_int) -> OsString {
165 let nsname = EXTATTR_NAMESPACE_NAMES[ns as usize].as_bytes();
166 let attr = attr.as_bytes();
167 let mut v = Vec::with_capacity(nsname.len() + attr.len() + 1);
168 v.extend_from_slice(nsname);
169 v.extend_from_slice(b".");
170 v.extend_from_slice(attr);
171 OsString::from_vec(v)
172 }
173
174 pub fn get_fd(fd: BorrowedFd<'_>, name: &OsStr) -> io::Result<Vec<u8>> {
175 let (ns, name) = name_to_ns(name)?;
176 unsafe { allocate_loop(|ptr, len| extattr_get_fd(fd.as_raw_fd(), ns, name.as_ptr(), ptr, len)) }
177 }
178
179 pub fn set_fd(fd: BorrowedFd<'_>, name: &OsStr, value: &[u8]) -> io::Result<()> {
180 let (ns, name) = name_to_ns(name)?;
181 let ret = unsafe {
182 extattr_set_fd(
183 fd.as_raw_fd(),
184 ns,
185 name.as_ptr(),
186 value.as_ptr() as *const c_void,
187 value.len() as size_t,
188 )
189 };
190 if ret == -1 {
191 Err(io::Error::last_os_error())
192 } else {
193 Ok(())
194 }
195 }
196
197 pub fn remove_fd(fd: BorrowedFd<'_>, name: &OsStr) -> io::Result<()> {
198 let (ns, name) = name_to_ns(name)?;
199 let ret = unsafe { extattr_delete_fd(fd.as_raw_fd(), ns, name.as_ptr()) };
200 if ret != 0 {
201 Err(io::Error::last_os_error())
202 } else {
203 Ok(())
204 }
205 }
206
207 pub fn list_fd(fd: BorrowedFd<'_>) -> io::Result<XAttrs> {
208 let sysvec = unsafe {
209 let res = allocate_loop(|ptr, len| {
210 extattr_list_fd(fd.as_raw_fd(), EXTATTR_NAMESPACE_SYSTEM, ptr, len)
211 });
212 // On FreeBSD, system attributes require root privileges to view. However,
213 // to mimic the behavior of listxattr in linux and osx, we need to query
214 // them anyway and return empty results if we get EPERM
215 match res {
216 Ok(v) => v,
217 Err(err) => {
218 if err.raw_os_error() == Some(EPERM) {
219 Vec::new()
220 } else {
221 return Err(err);
222 }
223 }
224 }
225 };
226
227 let uservec = unsafe {
228 allocate_loop(|ptr, len| extattr_list_fd(fd.as_raw_fd(), EXTATTR_NAMESPACE_USER, ptr, len))?
229 };
230
231 Ok(XAttrs {
232 system_attrs: sysvec.into_boxed_slice(),
233 user_attrs: uservec.into_boxed_slice(),
234 offset: 0,
235 })
236 }
237
238 pub fn get_path(path: &Path, name: &OsStr, deref: bool) -> io::Result<Vec<u8>> {
239 let (ns, name) = name_to_ns(name)?;
240 let path = path_to_c(path)?;
241 let extattr_get_func = if deref {
242 extattr_get_file
243 } else {
244 extattr_get_link
245 };
246 unsafe {
247 allocate_loop(|ptr, len| extattr_get_func(path.as_ptr(), ns, name.as_ptr(), ptr, len))
248 }
249 }
250
251 pub fn set_path(path: &Path, name: &OsStr, value: &[u8], deref: bool) -> io::Result<()> {
252 let (ns, name) = name_to_ns(name)?;
253 let path = path_to_c(path)?;
254 let extattr_set_func = if deref {
255 extattr_set_file
256 } else {
257 extattr_set_link
258 };
259 let ret = unsafe {
260 extattr_set_func(
261 path.as_ptr(),
262 ns,
263 name.as_ptr(),
264 value.as_ptr() as *const c_void,
265 value.len() as size_t,
266 )
267 };
268 if ret == -1 {
269 Err(io::Error::last_os_error())
270 } else {
271 Ok(())
272 }
273 }
274
275 pub fn remove_path(path: &Path, name: &OsStr, deref: bool) -> io::Result<()> {
276 let (ns, name) = name_to_ns(name)?;
277 let path = path_to_c(path)?;
278 let extattr_delete_func = if deref {
279 extattr_delete_file
280 } else {
281 extattr_delete_link
282 };
283 let ret = unsafe { extattr_delete_func(path.as_ptr(), ns, name.as_ptr()) };
284 if ret != 0 {
285 Err(io::Error::last_os_error())
286 } else {
287 Ok(())
288 }
289 }
290
291 pub fn list_path(path: &Path, deref: bool) -> io::Result<XAttrs> {
292 let path = path_to_c(path)?;
293 let extattr_list_func = if deref {
294 extattr_list_file
295 } else {
296 extattr_list_link
297 };
298 let sysvec = unsafe {
299 let res = allocate_loop(|ptr, len| {
300 extattr_list_func(path.as_ptr(), EXTATTR_NAMESPACE_SYSTEM, ptr, len)
301 });
302 // On FreeBSD, system attributes require root privileges to view. However,
303 // to mimic the behavior of listxattr in linux and osx, we need to query
304 // them anyway and return empty results if we get EPERM
305 match res {
306 Ok(v) => v,
307 Err(err) => {
308 if err.raw_os_error() == Some(EPERM) {
309 Vec::new()
310 } else {
311 return Err(err);
312 }
313 }
314 }
315 };
316
317 let uservec = unsafe {
318 allocate_loop(|ptr, len| {
319 extattr_list_func(path.as_ptr(), EXTATTR_NAMESPACE_USER, ptr, len)
320 })?
321 };
322
323 Ok(XAttrs {
324 system_attrs: sysvec.into_boxed_slice(),
325 user_attrs: uservec.into_boxed_slice(),
326 offset: 0,
327 })
328 }