Debian Codegraph @

src/util/util_freebsd.rs

raw symbols SCIP
1 use crate::bititer::BitIter;
2 use crate::failx::*;
3 use crate::flag::Flag;
4 use crate::perm::Perm;
5 use crate::qualifier::Qualifier;
6 use crate::sys::*;
7 use crate::util::util_common;
8
9 use log::debug;
10 use scopeguard::defer;
11 use std::ffi::{c_void, CString};
12 use std::io;
13 use std::os::unix::ffi::OsStrExt;
14 use std::path::Path;
15 use std::ptr;
16
17 pub use util_common::{xacl_create_entry, xacl_foreach, xacl_free, xacl_init, xacl_is_empty};
18
19 use util_common::*;
20
21 fn get_acl_type(acl: acl_t, default_acl: bool) -> acl_type_t {
22 if !acl.is_null() && !xacl_is_posix(acl) {
23 sg::ACL_TYPE_NFS4
24 } else if default_acl {
25 sg::ACL_TYPE_DEFAULT
26 } else {
27 sg::ACL_TYPE_ACCESS
28 }
29 }
30
31 /// Get ACL from file path, don't follow symbolic links.
32 fn xacl_get_link(path: &Path, default_acl: bool) -> io::Result<acl_t> {
33 let mut acl_type = get_acl_type(ptr::null_mut(), default_acl);
34 let c_path = CString::new(path.as_os_str().as_bytes())?;
35 let acl = unsafe { acl_get_link_np(c_path.as_ptr(), acl_type) };
36
37 if !acl.is_null() {
38 return Ok(acl);
39 }
40
41 // `acl_get_link_np` returns EINVAL when the ACL type is not appropriate for
42 // the file system object. Retry with NFSv4 type.
43 // FIXME: `default_acl` setting is currently ignored!
44 if io::Error::last_os_error().raw_os_error() == Some(sg::EINVAL) {
45 acl_type = sg::ACL_TYPE_NFS4;
46 let nfs_acl = unsafe { acl_get_link_np(c_path.as_ptr(), acl_type) };
47 if !nfs_acl.is_null() {
48 return Ok(nfs_acl);
49 }
50 }
51
52 // Report acl_type and path to file that failed.
53 let func = match acl_type {
54 sg::ACL_TYPE_ACCESS => "acl_get_link_np/access",
55 sg::ACL_TYPE_DEFAULT => "acl_get_link_np/default",
56 sg::ACL_TYPE_NFS4 => "acl_get_link_np/nfs4",
57 _ => "acl_get_link_np/?",
58 };
59
60 fail_err("null", func, &c_path)
61 }
62
63 /// Get ACL from file path.
64 ///
65 /// This code first tries to obtain the Posix.1e ACL. If that's not appropriate
66 /// for the file system object, we try to access the NFS4 ACL.
67 pub fn xacl_get_file(path: &Path, symlink_acl: bool, default_acl: bool) -> io::Result<acl_t> {
68 // Symlinks will use `acl_get_link_np` instead of `acl_get_file`.
69 if symlink_acl {
70 return xacl_get_link(path, default_acl);
71 }
72
73 let mut acl_type = get_acl_type(ptr::null_mut(), default_acl);
74 let c_path = CString::new(path.as_os_str().as_bytes())?;
75 let acl = unsafe { acl_get_file(c_path.as_ptr(), acl_type) };
76
77 if !acl.is_null() {
78 return Ok(acl);
79 }
80
81 // `acl_get_file` returns EINVAL when the ACL type is not appropriate for
82 // the file system object. Retry with NFSv4 type.
83 if io::Error::last_os_error().raw_os_error() == Some(sg::EINVAL)
84 && xacl_is_nfs4(path, symlink_acl)?
85 {
86 // NFSv4 does not support default ACL.
87 if default_acl {
88 return fail_custom("Default ACL not supported");
89 }
90
91 acl_type = sg::ACL_TYPE_NFS4;
92 let nfs_acl = unsafe { acl_get_file(c_path.as_ptr(), acl_type) };
93 if !nfs_acl.is_null() {
94 return Ok(nfs_acl);
95 }
96 }
97
98 // Report acl_type and path to file that failed.
99 let func = match acl_type {
100 sg::ACL_TYPE_ACCESS => "acl_get_file/access",
101 sg::ACL_TYPE_DEFAULT => "acl_get_file/default",
102 sg::ACL_TYPE_NFS4 => "acl_get_file/nfs4",
103 _ => "acl_get_file/?",
104 };
105
106 fail_err("null", func, &c_path)
107 }
108
109 fn xacl_set_file_symlink(path: &Path, acl: acl_t, default_acl: bool) -> io::Result<()> {
110 let c_path = CString::new(path.as_os_str().as_bytes())?;
111
112 if default_acl && xacl_is_empty(acl) {
113 // Special case to delete the ACL. The FreeBSD version of
114 // acl_set_link_np does not handle this case.
115 let ret = unsafe { acl_delete_def_link_np(c_path.as_ptr()) };
116 if ret != 0 {
117 return fail_err(ret, "acl_delete_def_link_np", &c_path);
118 }
119 return Ok(());
120 }
121
122 let acl_type = get_acl_type(acl, default_acl);
123 let ret = unsafe { acl_set_link_np(c_path.as_ptr(), acl_type, acl) };
124 if ret != 0 {
125 let func = if default_acl {
126 "acl_set_link_np/default"
127 } else {
128 "acl_set_link_np/access"
129 };
130 return fail_err(ret, func, &c_path);
131 }
132
133 Ok(())
134 }
135
136 fn xacl_repair_nfs4(acl: acl_t) -> io::Result<()> {
137 xacl_foreach(acl, |entry| {
138 let entry_type = xacl_get_entry_type(entry)?;
139 if entry_type == 0 {
140 xacl_set_entry_type(entry, sg::ACL_ENTRY_TYPE_ALLOW)?;
141 }
142 // Translate READ -> READ_DATA and WRITE -> WRITE_DATA.
143 let mut perm = xacl_get_perm(entry)?;
144 let orig_perm = perm;
145 if perm.intersects(Perm::READ) {
146 perm.remove(Perm::READ);
147 perm.insert(Perm::READ_DATA);
148 }
149 if perm.intersects(Perm::WRITE) {
150 perm.remove(Perm::WRITE);
151 perm.insert(Perm::WRITE_DATA);
152 }
153 if perm != orig_perm {
154 xacl_set_perm(entry, perm)?;
155 }
156 Ok(())
157 })
158 }
159
160 pub fn xacl_set_file(
161 path: &Path,
162 acl: acl_t,
163 symlink_acl: bool,
164 default_acl: bool,
165 ) -> io::Result<()> {
166 let is_nfs4 = xacl_is_nfs4(path, symlink_acl)?;
167
168 if default_acl && is_nfs4 {
169 return fail_custom("Default ACL not supported");
170 }
171
172 if !xacl_is_posix(acl) || is_nfs4 {
173 // Fix up the ACL to make sure that all entry types are set.
174 // FIXME: This mutates the acl, violating the immutable invariant.
175 xacl_repair_nfs4(acl)?;
176 }
177
178 log_brand("xacl_set_file", acl)?;
179
180 if symlink_acl {
181 return xacl_set_file_symlink(path, acl, default_acl);
182 }
183
184 let c_path = CString::new(path.as_os_str().as_bytes())?;
185
186 if default_acl && xacl_is_empty(acl) {
187 // Special case to delete the ACL. The FreeBSD version of
188 // acl_set_file does not handle this case.
189 let ret = unsafe { acl_delete_def_file(c_path.as_ptr()) };
190 if ret != 0 {
191 return fail_err(ret, "acl_delete_def_file", &c_path);
192 }
193 return Ok(());
194 }
195
196 let acl_type = get_acl_type(acl, default_acl);
197 let ret = unsafe { acl_set_file(c_path.as_ptr(), acl_type, acl) };
198 if ret != 0 {
199 let func = match acl_type {
200 sg::ACL_TYPE_ACCESS => "acl_set_file/access",
201 sg::ACL_TYPE_DEFAULT => "acl_set_file/default",
202 sg::ACL_TYPE_NFS4 => "acl_set_file/nfs4",
203 _ => "acl_set_file/?",
204 };
205 return fail_err(ret, func, &c_path);
206 }
207
208 Ok(())
209 }
210
211 fn xacl_get_qualifier(entry: acl_entry_t) -> io::Result<Qualifier> {
212 let tag = xacl_get_tag_type(entry)?;
213
214 let id = if tag == sg::ACL_USER || tag == sg::ACL_GROUP {
215 let id_ptr = unsafe { acl_get_qualifier(entry).cast::<uid_t>() };
216 if id_ptr.is_null() {
217 return fail_err("null", "acl_get_qualifier", ());
218 }
219 defer! { xacl_free(id_ptr) };
220 Some(unsafe { *id_ptr })
221 } else {
222 None
223 };
224
225 let result = match tag {
226 sg::ACL_USER => Qualifier::User(id.unwrap()),
227 sg::ACL_GROUP => Qualifier::Group(id.unwrap()),
228 sg::ACL_USER_OBJ => Qualifier::UserObj,
229 sg::ACL_GROUP_OBJ => Qualifier::GroupObj,
230 sg::ACL_OTHER => Qualifier::Other,
231 sg::ACL_MASK => Qualifier::Mask,
232 sg::ACL_EVERYONE => Qualifier::Everyone,
233 tag => Qualifier::Unknown(format!("@tag {tag}")),
234 };
235
236 Ok(result)
237 }
238
239 fn xacl_get_entry_type(entry: acl_entry_t) -> io::Result<acl_entry_type_t> {
240 let mut entry_type: acl_entry_type_t = 0;
241
242 let ret = unsafe { acl_get_entry_type_np(entry, &mut entry_type) };
243 if ret != 0 {
244 return fail_err(ret, "acl_get_entry_type_np", ());
245 }
246
247 // FIXME: AUDIT, ALARM entry types are not supported.
248 debug_assert!(
249 entry_type == 0
250 || entry_type == sg::ACL_ENTRY_TYPE_ALLOW
251 || entry_type == sg::ACL_ENTRY_TYPE_DENY
252 );
253
254 Ok(entry_type)
255 }
256
257 fn xacl_get_tag_qualifier(acl: acl_t, entry: acl_entry_t) -> io::Result<(bool, Qualifier)> {
258 let qualifier = xacl_get_qualifier(entry)?;
259
260 let allow = if xacl_is_posix(acl) {
261 true
262 } else {
263 xacl_get_entry_type(entry)? == sg::ACL_ENTRY_TYPE_ALLOW
264 };
265
266 Ok((allow, qualifier))
267 }
268
269 fn xacl_get_flags(acl: acl_t, entry: acl_entry_t) -> io::Result<Flag> {
270 if xacl_is_posix(acl) {
271 return Ok(Flag::empty());
272 }
273
274 let mut flagset: acl_flagset_t = std::ptr::null_mut();
275 let ret = unsafe { acl_get_flagset_np(entry, &mut flagset) };
276 if ret != 0 {
277 return fail_err(ret, "acl_get_flagset_np", ());
278 }
279
280 assert!(!flagset.is_null());
281
282 let mut flags = Flag::empty();
283 for flag in BitIter(Flag::all() - Flag::DEFAULT) {
284 let res = unsafe { acl_get_flag_np(flagset, flag.bits()) };
285 debug_assert!((0..=1).contains(&res));
286 if res == 1 {
287 flags |= flag;
288 }
289 }
290
291 Ok(flags)
292 }
293
294 pub fn xacl_get_entry(acl: acl_t, entry: acl_entry_t) -> io::Result<(bool, Qualifier, Perm, Flag)> {
295 let (allow, qualifier) = xacl_get_tag_qualifier(acl, entry)?;
296 let perms = xacl_get_perm(entry)?;
297 let flags = xacl_get_flags(acl, entry)?;
298
299 Ok((allow, qualifier, perms, flags))
300 }
301
302 pub fn xacl_set_qualifier(entry: acl_entry_t, mut id: uid_t) -> io::Result<()> {
303 let id_ptr = std::ptr::addr_of_mut!(id);
304
305 let ret = unsafe { acl_set_qualifier(entry, id_ptr.cast::<c_void>()) };
306 if ret != 0 {
307 return fail_err(ret, "acl_set_qualifier", ());
308 }
309
310 Ok(())
311 }
312
313 fn xacl_set_entry_type(entry: acl_entry_t, entry_type: acl_entry_type_t) -> io::Result<()> {
314 let ret = unsafe { acl_set_entry_type_np(entry, entry_type) };
315 if ret != 0 {
316 return fail_err(ret, "acl_set_entry_type_np", ());
317 }
318
319 Ok(())
320 }
321
322 pub fn xacl_set_tag_qualifier(
323 entry: acl_entry_t,
324 allow: bool,
325 qualifier: &Qualifier,
326 ) -> io::Result<()> {
327 if !allow {
328 xacl_set_entry_type(entry, sg::ACL_ENTRY_TYPE_DENY)?;
329 };
330
331 match qualifier {
332 Qualifier::User(uid) => {
333 xacl_set_tag_type(entry, sg::ACL_USER)?;
334 xacl_set_qualifier(entry, *uid)?;
335 }
336 Qualifier::Group(gid) => {
337 xacl_set_tag_type(entry, sg::ACL_GROUP)?;
338 xacl_set_qualifier(entry, *gid)?;
339 }
340 Qualifier::UserObj => {
341 xacl_set_tag_type(entry, sg::ACL_USER_OBJ)?;
342 }
343 Qualifier::GroupObj => {
344 xacl_set_tag_type(entry, sg::ACL_GROUP_OBJ)?;
345 }
346 Qualifier::Other => {
347 xacl_set_tag_type(entry, sg::ACL_OTHER)?;
348 }
349 Qualifier::Mask => {
350 xacl_set_tag_type(entry, sg::ACL_MASK)?;
351 }
352 Qualifier::Everyone => {
353 xacl_set_tag_type(entry, sg::ACL_EVERYONE)?;
354 }
355 Qualifier::Unknown(tag) => {
356 return fail_custom(&format!("unknown tag: {tag}"));
357 }
358 }
359
360 Ok(())
361 }
362
363 fn xacl_set_flags(entry: acl_entry_t, flags: Flag) -> io::Result<()> {
364 if flags.is_empty() || flags == Flag::DEFAULT {
365 return Ok(());
366 }
367
368 let mut flagset: acl_flagset_t = std::ptr::null_mut();
369 let ret_get = unsafe { acl_get_flagset_np(entry, &mut flagset) };
370 if ret_get != 0 {
371 return fail_err(ret_get, "acl_get_flagset_np", ());
372 }
373
374 assert!(!flagset.is_null());
375
376 let ret_clear = unsafe { acl_clear_flags_np(flagset) };
377 if ret_clear != 0 {
378 return fail_err(ret_clear, "acl_clear_flags_np", ());
379 }
380
381 for flag in BitIter(flags) {
382 let ret = unsafe { acl_add_flag_np(flagset, flag.bits()) };
383 debug_assert!(ret == 0);
384 }
385
386 Ok(())
387 }
388
389 pub fn xacl_add_entry(
390 acl: &mut acl_t,
391 allow: bool,
392 qualifier: &Qualifier,
393 perms: Perm,
394 flags: Flag,
395 ) -> io::Result<acl_entry_t> {
396 let nfs4_specific =
397 perms.intersects(Perm::NFS4_SPECIFIC) || flags.intersects(Flag::NFS4_SPECIFIC);
398
399 if allow && xacl_is_posix(*acl) && !nfs4_specific {
400 // Check for duplicates already in the list.
401 xacl_foreach(*acl, |entry| {
402 let (_, prev) = xacl_get_tag_qualifier(*acl, entry)?;
403 if prev == *qualifier {
404 let default = if flags.contains(Flag::DEFAULT) {
405 "default "
406 } else {
407 ""
408 };
409 fail_custom(&format!("duplicate {default}entry for \"{prev}\""))?;
410 }
411 Ok(())
412 })?;
413 }
414
415 let entry = xacl_create_entry(acl)?;
416 xacl_set_tag_qualifier(entry, allow, qualifier)?;
417 xacl_set_perm(entry, perms)?;
418 xacl_set_flags(entry, flags)?;
419
420 // If permissions allow NFSv4 specific bits, set entry type `allow` to force
421 // the ACL brand to NFS4.
422 if allow && nfs4_specific {
423 xacl_set_entry_type(entry, sg::ACL_ENTRY_TYPE_ALLOW)?;
424 }
425
426 Ok(entry)
427 }
428
429 fn xacl_get_brand(acl: acl_t) -> io::Result<i32> {
430 let mut brand: i32 = 0;
431 let ret = unsafe { acl_get_brand_np(acl, &mut brand) };
432 if ret != 0 {
433 return fail_err(ret, "acl_get_brand_np", ());
434 }
435
436 Ok(brand)
437 }
438
439 pub fn xacl_is_posix(acl: acl_t) -> bool {
440 let brand = xacl_get_brand(acl).expect("xacl_get_brand failed");
441 debug_assert!(
442 brand == sg::ACL_BRAND_UNKNOWN
443 || brand == sg::ACL_BRAND_POSIX
444 || brand == sg::ACL_BRAND_NFS4
445 );
446
447 // Treat an Unknown branded ACL as Posix.
448 brand == sg::ACL_BRAND_POSIX || brand == sg::ACL_BRAND_UNKNOWN
449 }
450
451 fn log_brand(func: &str, acl: acl_t) -> io::Result<()> {
452 let brand = match xacl_get_brand(acl)? {
453 sg::ACL_BRAND_UNKNOWN => "brand_unknown".to_owned(),
454 sg::ACL_BRAND_POSIX => "brand_posix".to_owned(),
455 sg::ACL_BRAND_NFS4 => "brand_nfs4".to_owned(),
456 value => value.to_string(),
457 };
458
459 debug!("{}: acl {}", func, brand);
460
461 Ok(())
462 }
463
464 pub fn xacl_is_nfs4(path: &Path, symlink: bool) -> io::Result<bool> {
465 let c_path = CString::new(path.as_os_str().as_bytes())?;
466 let ret = if symlink {
467 unsafe { lpathconf(c_path.as_ptr(), sg::PC_ACL_NFS4) }
468 } else {
469 unsafe { pathconf(c_path.as_ptr(), sg::PC_ACL_NFS4) }
470 };
471
472 if ret < 0 {
473 return fail_err(ret, "pathconf", symlink);
474 }
475
476 assert!(ret == 0 || ret == 1);
477 Ok(ret == 1)
478 }
479
480 ////////////////////////////////////////////////////////////////////////////////
481
482 #[cfg(test)]
483 mod util_freebsd_test {
484 use super::*;
485
486 #[test]
487 fn test_acl_api_misuse() {
488 // Create empty list and add an entry.
489 let mut acl = xacl_init(1).unwrap();
490 let entry = xacl_create_entry(&mut acl).unwrap();
491
492 // Setting tag other than 1 or 2 results in EINVAL error.
493 let err = xacl_set_tag_type(entry, 0).unwrap_err();
494 assert_eq!(err.raw_os_error(), Some(sg::EINVAL));
495
496 // Setting qualifier without first setting tag to a valid value results in EINVAL.
497 let err = xacl_set_qualifier(entry, 500).unwrap_err();
498 assert_eq!(err.raw_os_error(), Some(sg::EINVAL));
499
500 // Try to set entry using unknown qualifier -- this should fail.
501 let err =
502 xacl_set_tag_qualifier(entry, true, &Qualifier::Unknown("x".to_string())).unwrap_err();
503 assert!(err.to_string().contains("unknown tag: x"));
504
505 // Add another entry and set it to a valid value.
506 let entry2 = xacl_create_entry(&mut acl).unwrap();
507 xacl_set_tag_type(entry2, sg::ACL_USER_OBJ).unwrap();
508
509 xacl_free(acl);
510 }
511
512 #[test]
513 fn test_empty_acl() {
514 let file = tempfile::NamedTempFile::new().unwrap();
515 let dir = tempfile::TempDir::new().unwrap();
516
517 let acl = xacl_init(1).unwrap();
518 assert!(xacl_is_empty(acl));
519
520 // Empty acl is not "valid".
521 let ret = unsafe { acl_valid(acl) };
522 assert_eq!(ret, -1);
523
524 // Not on FreeBSD.
525 let err = xacl_set_file(file.as_ref(), acl, false, false)
526 .err()
527 .unwrap();
528 assert_eq!(err.to_string(), "Invalid argument (os error 22)");
529
530 // Write an empty default ACL to a directory. Okay with Posix.1e ACL
531 // but fails on NFSv4, because default ACL is not supported.
532 let result = xacl_set_file(dir.as_ref(), acl, false, true);
533 if xacl_is_nfs4(dir.as_ref(), false).unwrap() {
534 assert_eq!(
535 result.err().unwrap().to_string(),
536 "Default ACL not supported"
537 );
538 } else {
539 result.ok().unwrap();
540 }
541
542 xacl_free(acl);
543 }
544
545 #[test]
546 fn test_uninitialized_entry() {
547 let mut acl = xacl_init(1).unwrap();
548 let entry_p = xacl_create_entry(&mut acl).unwrap();
549
550 let (allow, qualifier) = xacl_get_tag_qualifier(acl, entry_p).unwrap();
551 assert_eq!(qualifier.name().unwrap(), "@tag 0");
552 // FreeBSD: Unbranded entry is treated as Posix.
553 assert!(allow);
554
555 let brand = xacl_get_brand(acl).unwrap();
556 assert_eq!(brand, sg::ACL_BRAND_UNKNOWN);
557
558 xacl_free(acl);
559 }
560 }