exacl 0.10.0

Manipulate file system access control lists (ACL) on macOS, Linux, and FreeBSD
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Implements the permissions flags.

use crate::bititer::{BitIter, BitIterable};
use crate::format;
use crate::sys::*;

use bitflags::bitflags;
#[cfg(feature = "serde")]
use serde::{de, ser, Deserialize, Serialize};
use std::fmt;

bitflags! {
    /// Represents file access permissions.
    #[derive(Default)]
    pub struct Perm : acl_perm_t {
        /// READ_DATA permission for a file.
        /// Same as LIST_DIRECTORY permission for a directory.
        const READ = ACL_READ;

        /// WRITE_DATA permission for a file.
        /// Same as ADD_FILE permission for a directory.
        const WRITE = ACL_WRITE;

        /// EXECUTE permission for a file.
        /// Same as SEARCH permission for a directory.
        const EXECUTE = ACL_EXECUTE;

        /// DELETE permission for a file.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const DELETE = np::ACL_DELETE;

        /// APPEND_DATA permission for a file.
        /// Same as ADD_SUBDIRECTORY permission for a directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const APPEND = np::ACL_APPEND_DATA;

        /// DELETE_CHILD permission for a directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const DELETE_CHILD = np::ACL_DELETE_CHILD;

        /// READ_ATTRIBUTES permission for file or directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const READATTR = np::ACL_READ_ATTRIBUTES;

        /// WRITE_ATTRIBUTES permission for a file or directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const WRITEATTR = np::ACL_WRITE_ATTRIBUTES;

        /// READ_EXTATTRIBUTES permission for a file or directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const READEXTATTR = np::ACL_READ_EXTATTRIBUTES;

        /// WRITE_EXTATTRIBUTES permission for a file or directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const WRITEEXTATTR = np::ACL_WRITE_EXTATTRIBUTES;

        /// READ_SECURITY permission for a file or directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const READSECURITY = np::ACL_READ_SECURITY;

        /// WRITE_SECURITY permission for a file or directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const WRITESECURITY = np::ACL_WRITE_SECURITY;

        /// CHANGE_OWNER permission for a file or directory.
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const CHOWN = np::ACL_CHANGE_OWNER;

        /// SYNCHRONIZE permission (unsupported).
        #[cfg(any(docsrs, target_os = "macos", target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "freebsd"))))]
        const SYNC = np::ACL_SYNCHRONIZE;

        /// NFSv4 READ_DATA permission.
        #[cfg(any(docsrs, target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(target_os = "freebsd")))]
        const READ_DATA = np::ACL_READ_DATA;

        /// NFSv4 WRITE_DATA permission.
        #[cfg(any(docsrs, target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(target_os = "freebsd")))]
        const WRITE_DATA = np::ACL_WRITE_DATA;

        /// Posix specific permissions.
        #[cfg(any(docsrs, target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(target_os = "freebsd")))]
        const POSIX_SPECIFIC = Self::READ.bits | Self::WRITE.bits | Self::EXECUTE.bits;

        /// All NFSv4 specific permissions.
        #[cfg(any(docsrs, target_os = "freebsd"))]
        #[cfg_attr(docsrs, doc(cfg(target_os = "freebsd")))]
        const NFS4_SPECIFIC = Self::READ_DATA.bits | Self::WRITE_DATA.bits
            | Self::DELETE.bits | Self::APPEND.bits | Self::DELETE_CHILD.bits
            | Self::READATTR.bits | Self::WRITEATTR.bits | Self::READEXTATTR.bits
            | Self::WRITEEXTATTR.bits | Self::READSECURITY.bits
            | Self::WRITESECURITY.bits | Self::CHOWN.bits | Self::SYNC.bits;
    }
}

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
type RevPermIter = std::iter::Rev<BitIter<Perm>>;

impl Perm {
    #[cfg(target_os = "macos")]
    fn iter(self) -> BitIter<Perm> {
        BitIter(self & Perm::all())
    }

    #[cfg(target_os = "linux")]
    fn iter(self) -> RevPermIter {
        BitIter(self & Perm::all()).rev()
    }

    #[cfg(target_os = "freebsd")]
    fn iter(self) -> std::iter::Chain<RevPermIter, BitIter<Perm>> {
        BitIter(self & Perm::POSIX_SPECIFIC)
            .rev()
            .chain(BitIter(self & Perm::NFS4_SPECIFIC))
    }
}

impl BitIterable for Perm {
    fn lsb(self) -> Option<Self> {
        if self.is_empty() {
            return None;
        }
        Some(Perm {
            bits: 1 << self.bits.trailing_zeros(),
        })
    }

    fn msb(self) -> Option<Self> {
        #[allow(clippy::cast_possible_truncation)]
        const MAX_BITS: acl_perm_t = 8 * std::mem::size_of::<Perm>() as acl_perm_t - 1;

        if self.is_empty() {
            return None;
        }
        Some(Perm {
            bits: 1 << (MAX_BITS - self.bits.leading_zeros()),
        })
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[repr(u32)]
#[allow(non_camel_case_types)]
pub enum PermName {
    // *N.B.* Update the corresponding table in format/format_no_serde.rs
    // if any of these entries change.
    read = Perm::READ.bits,

    write = Perm::WRITE.bits,

    execute = Perm::EXECUTE.bits,

    #[cfg(target_os = "freebsd")]
    read_data = Perm::READ_DATA.bits,

    #[cfg(target_os = "freebsd")]
    write_data = Perm::WRITE_DATA.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    delete = Perm::DELETE.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    append = Perm::APPEND.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    delete_child = Perm::DELETE_CHILD.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    readattr = Perm::READATTR.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    writeattr = Perm::WRITEATTR.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    readextattr = Perm::READEXTATTR.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    writeextattr = Perm::WRITEEXTATTR.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    readsecurity = Perm::READSECURITY.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    writesecurity = Perm::WRITESECURITY.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    chown = Perm::CHOWN.bits,

    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    sync = Perm::SYNC.bits,
}

impl PermName {
    const fn from_perm(perm: Perm) -> Option<PermName> {
        match perm {
            Perm::READ => Some(PermName::read),

            Perm::WRITE => Some(PermName::write),

            Perm::EXECUTE => Some(PermName::execute),

            #[cfg(target_os = "freebsd")]
            Perm::READ_DATA => Some(PermName::read_data),

            #[cfg(target_os = "freebsd")]
            Perm::WRITE_DATA => Some(PermName::write_data),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::DELETE => Some(PermName::delete),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::APPEND => Some(PermName::append),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::DELETE_CHILD => Some(PermName::delete_child),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::READATTR => Some(PermName::readattr),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::WRITEATTR => Some(PermName::writeattr),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::READEXTATTR => Some(PermName::readextattr),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::WRITEEXTATTR => Some(PermName::writeextattr),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::READSECURITY => Some(PermName::readsecurity),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::WRITESECURITY => Some(PermName::writesecurity),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::CHOWN => Some(PermName::chown),

            #[cfg(any(target_os = "macos", target_os = "freebsd"))]
            Perm::SYNC => Some(PermName::sync),

            _ => None,
        }
    }

    const fn to_perm(self) -> Perm {
        Perm { bits: self as u32 }
    }
}

impl fmt::Display for PermName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        format::write_permname(f, *self)
    }
}

impl fmt::Display for Perm {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut iter = self.iter();

        if let Some(perm) = iter.next() {
            write!(f, "{}", PermName::from_perm(perm).unwrap())?;

            for perm in iter {
                write!(f, ",{}", PermName::from_perm(perm).unwrap())?;
            }
        }

        Ok(())
    }
}

/// Parse an abbreviated permission, "rwx", "wx", "r-x" etc.
///
/// Order doesn't matter. "xwr" is the same as "rwx". Allow for "r-x" by
/// ignoring any number of '-'. Don't allow r, w, or x to be repeated.
fn parse_perm_abbreviation(s: &str) -> Option<Perm> {
    let mut perms = Perm::empty();
    for ch in s.chars() {
        match ch {
            'r' if !perms.contains(Perm::READ) => perms |= Perm::READ,
            'w' if !perms.contains(Perm::WRITE) => perms |= Perm::WRITE,
            'x' if !perms.contains(Perm::EXECUTE) => perms |= Perm::EXECUTE,
            '-' => (),
            // Any other character is invalid.
            _ => return None,
        }
    }
    Some(perms)
}

impl std::str::FromStr for PermName {
    type Err = format::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        format::read_permname(s)
    }
}

impl std::str::FromStr for Perm {
    type Err = format::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut result = Perm::empty();

        for item in s.split(',') {
            let word = item.trim();
            if !word.is_empty() {
                if let Some(perms) = parse_perm_abbreviation(word) {
                    result |= perms;
                } else {
                    result |= word.parse::<PermName>()?.to_perm();
                }
            }
        }

        Ok(result)
    }
}

#[cfg(feature = "serde")]
impl ser::Serialize for Perm {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ser::Serializer,
    {
        use ser::SerializeSeq;
        let mut seq = serializer.serialize_seq(None)?;

        for perm in self.iter() {
            seq.serialize_element(&PermName::from_perm(perm))?;
        }

        seq.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> de::Deserialize<'de> for Perm {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        struct PermVisitor;

        impl<'de> de::Visitor<'de> for PermVisitor {
            type Value = Perm;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("list of permissions")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: de::SeqAccess<'de>,
            {
                let mut perms: Perm = Perm::empty();

                while let Some(value) = seq.next_element()? {
                    let name: PermName = value;
                    perms |= name.to_perm();
                }

                Ok(perms)
            }
        }

        deserializer.deserialize_seq(PermVisitor)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod perm_tests {
    use super::*;

    #[test]
    #[cfg(target_os = "macos")]
    fn test_perm_equivalences() {
        assert_eq!(acl_perm_t_ACL_READ_DATA, acl_perm_t_ACL_LIST_DIRECTORY);
        assert_eq!(acl_perm_t_ACL_WRITE_DATA, acl_perm_t_ACL_ADD_FILE);
        assert_eq!(acl_perm_t_ACL_EXECUTE, acl_perm_t_ACL_SEARCH);
        assert_eq!(acl_perm_t_ACL_APPEND_DATA, acl_perm_t_ACL_ADD_SUBDIRECTORY);
    }

    #[test]
    fn test_perm_display() {
        assert_eq!(Perm::empty().to_string(), "");

        let perms = Perm::READ | Perm::EXECUTE;
        assert_eq!(perms.to_string(), "read,execute");

        let bad_perm = Perm { bits: 0x0080_0000 } | Perm::READ;
        assert_eq!(bad_perm.to_string(), "read");

        #[cfg(target_os = "macos")]
        assert_eq!(Perm::all().to_string(), "read,write,execute,delete,append,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,sync");

        #[cfg(target_os = "linux")]
        assert_eq!(Perm::all().to_string(), "read,write,execute");

        #[cfg(target_os = "freebsd")]
        assert_eq!(Perm::all().to_string(), "read,write,execute,read_data,write_data,append,readextattr,writeextattr,delete_child,readattr,writeattr,delete,readsecurity,writesecurity,chown,sync");
    }

    #[test]
    fn test_perm_fromstr() {
        let flags = Perm::READ | Perm::EXECUTE;
        assert_eq!(flags, "read, execute".parse().unwrap());
        assert_eq!(flags, "rx".parse().unwrap());
        assert_eq!(flags, "r-x".parse().unwrap());
        assert_eq!(flags, "--x--r--".parse().unwrap());
        assert_eq!(flags, "xr".parse().unwrap());
        assert_eq!(Perm::WRITE, "w".parse().unwrap());
        assert_eq!(Perm::empty(), "".parse().unwrap());

        // Duplicate abbreviations not supported.
        assert!("rr".parse::<Perm>().is_err());

        #[cfg(target_os = "macos")]
        {
            assert_eq!("unknown variant `q`, expected one of `read`, `write`, `execute`, `delete`, `append`, `delete_child`, `readattr`, `writeattr`, `readextattr`, `writeextattr`, `readsecurity`, `writesecurity`, `chown`, `sync`", " ,q ".parse::<Perm>().unwrap_err().to_string());

            assert_eq!(Perm::all(), "read,write,execute,delete,append,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,sync".parse().unwrap());
        }

        #[cfg(target_os = "linux")]
        {
            assert_eq!(
                "unknown variant `qq`, expected one of `read`, `write`, `execute`",
                " ,qq ".parse::<Perm>().unwrap_err().to_string()
            );

            assert_eq!(Perm::all(), "read,write,execute".parse().unwrap());
        }

        #[cfg(target_os = "freebsd")]
        {
            assert_eq!(
                "unknown variant `qq`, expected one of `read`, `write`, `execute`, `read_data`, `write_data`, `delete`, `append`, `delete_child`, `readattr`, `writeattr`, `readextattr`, `writeextattr`, `readsecurity`, `writesecurity`, `chown`, `sync`",
                " ,qq ".parse::<Perm>().unwrap_err().to_string()
            );

            assert_eq!(Perm::all(), "read,write,execute,delete,append,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,sync,read_data,write_data".parse().unwrap());
        }
    }

    #[test]
    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    fn test_perm_unix_permission() {
        // Test that READ, WRITE, EXECUTE constant correspond to the same bits
        // as the permissions in unix mode.

        assert_eq!(Perm::READ.bits, 0x04);
        assert_eq!(Perm::WRITE.bits, 0x02);
        assert_eq!(Perm::EXECUTE.bits, 0x01);

        assert_eq!(
            Perm::from_bits(0x07),
            Some(Perm::READ | Perm::WRITE | Perm::EXECUTE)
        );
    }
}