Skip to main content

file_system/fundamentals/
permission.rs

1use core::fmt::{self, Display};
2
3use bitflags::bitflags;
4
5use crate::Kind;
6
7bitflags! {
8    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9    pub struct Permission: u8 {
10        const Execute = 1 << 0;
11        const Write = 1 << 1;
12        const Read = 1 << 2;
13    }
14}
15
16impl Permission {
17    pub const READ_WRITE: Self = Permission::Read.union(Permission::Write);
18    pub const READ_EXECUTE: Self = Permission::Read.union(Permission::Execute);
19    pub const WRITE_EXECUTE: Self = Permission::Write.union(Permission::Execute);
20
21    pub const fn from_unix(unix: u8) -> Option<Self> {
22        if unix > 0b111 {
23            return None;
24        }
25
26        Some(Self::from_bits_retain(unix))
27    }
28
29    pub const fn to_unix(&self) -> u8 {
30        self.bits()
31    }
32}
33
34impl Display for Permission {
35    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36        let read = if self.contains(Permission::Read) {
37            "r"
38        } else {
39            "-"
40        };
41        let write = if self.contains(Permission::Write) {
42            "w"
43        } else {
44            "-"
45        };
46        let execute = if self.contains(Permission::Execute) {
47            "x"
48        } else {
49            "-"
50        };
51
52        write!(f, "{read}{write}{execute}")
53    }
54}
55
56bitflags! {
57    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
58    pub struct Special: u8 {
59        const Sticky = 1 << 0;
60        const SetUserIdentifier = 1 << 1;
61        const SetGroupIdentifier = 1 << 2;
62    }
63}
64
65impl fmt::Display for Special {
66    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67        let sticky = if self.contains(Special::Sticky) {
68            "t"
69        } else {
70            "-"
71        };
72        let set_gid = if self.contains(Special::SetGroupIdentifier) {
73            "u"
74        } else {
75            "-"
76        };
77        let set_uid = if self.contains(Special::SetUserIdentifier) {
78            "g"
79        } else {
80            "-"
81        };
82
83        write!(f, "{sticky}{set_gid}{set_uid}")
84    }
85}
86
87/// Represents the permissions of a file or directory.
88///
89/// The permissions are divided into three groups: user, group, and others.
90/// Each group has three permissions: read, write, and execute.
91///
92/// # Examples
93///
94/// ```rust
95/// use file_system::{Permissions, Permission, Special};
96///
97/// let user = Permission::Read; // Read only
98/// let group = Permission::Write; // Write only
99/// let others = Permission::Execute; // Execute only
100/// let special = Special::empty();
101///
102/// let permissions = Permissions::new(user, group, others, special);
103///
104/// assert_eq!(permissions.get_user(), user);
105/// assert_eq!(permissions.get_group(), group);
106/// assert_eq!(permissions.get_others(), others);
107/// assert_eq!(permissions.get_special(), special);
108/// ```
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110#[repr(transparent)]
111pub struct Permissions(u16);
112
113impl fmt::Display for Permissions {
114    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115        let user = self.get_user();
116        let group = self.get_group();
117        let others = self.get_others();
118
119        write!(f, "{user}{group}{others}")
120    }
121}
122
123impl From<(Permission, Permission, Permission)> for Permissions {
124    fn from(value: (Permission, Permission, Permission)) -> Self {
125        Self::new(value.0, value.1, value.2, Special::NONE)
126    }
127}
128
129impl From<(Permission, Permission, Permission, Special)> for Permissions {
130    fn from(value: (Permission, Permission, Permission, Special)) -> Self {
131        Self::new(value.0, value.1, value.2, value.3)
132    }
133}
134
135impl Permissions {
136    pub const NONE: Self = Self::new(
137        Permission::empty(),
138        Permission::empty(),
139        Permission::empty(),
140        Special::NONE,
141    );
142    pub const ALL_FULL: Self = Self::new(
143        Permission::all(),
144        Permission::all(),
145        Permission::all(),
146        Special::NONE,
147    );
148    pub const ALL_READ_WRITE: Self = Self::new(
149        Permission::READ_WRITE,
150        Permission::READ_WRITE,
151        Permission::READ_WRITE,
152        Special::NONE,
153    );
154    pub const USER_FULL: Self = Self::new(
155        Permission::all(),
156        Permission::empty(),
157        Permission::empty(),
158        Special::NONE,
159    );
160    pub const USER_READ_WRITE: Self = Self::new(
161        Permission::READ_WRITE,
162        Permission::empty(),
163        Permission::empty(),
164        Special::NONE,
165    );
166    pub const EXECUTABLE: Self = Self::new(
167        Permission::all(),
168        Permission::READ_EXECUTE,
169        Permission::READ_EXECUTE,
170        Special::NONE,
171    );
172    pub const FILE_DEFAULT: Self = Self::new(
173        Permission::READ_WRITE,
174        Permission::READ_WRITE,
175        Permission::Read,
176        Special::NONE,
177    );
178    pub const DIRECTORY_DEFAULT: Self = Self::new(
179        Permission::all(),
180        Permission::all(),
181        Permission::READ_EXECUTE,
182        Special::NONE,
183    );
184    /// World-writable directory where only an entry's owner may remove or rename it, like Unix mode 1777.
185    pub const SHARED_DIRECTORY: Self = Self::new(
186        Permission::all(),
187        Permission::all(),
188        Permission::all(),
189        Special::STICKY,
190    );
191    pub const DEVICE_DEFAULT: Self = Self::new(
192        Permission::all(),
193        Permission::READ_WRITE,
194        Permission::READ_WRITE,
195        Special::NONE,
196    );
197    /// Device whose writes are reserved to its owner (root when the runtime
198    /// mounts it): owner read-write, group and others read-only. Used for
199    /// device nodes whose write commands change system state, like the
200    /// real-time clock.
201    pub const PRIVILEGED_DEVICE: Self = Self::new(
202        Permission::READ_WRITE,
203        Permission::Read,
204        Permission::Read,
205        Special::NONE,
206    );
207
208    /// Creates a new permission.
209    pub const fn new(
210        user: Permission,
211        group: Permission,
212        others: Permission,
213        special: Special,
214    ) -> Self {
215        Self(
216            (special.to_unix() as u16) << 9
217                | (user.to_unix() as u16) << 6
218                | (group.to_unix() as u16) << 3
219                | others.to_unix() as u16,
220        )
221    }
222
223    /// Creates a new permission with read access for user. No access for group and others.
224    pub const fn new_default(r#type: Kind) -> Self {
225        match r#type {
226            Kind::Directory => Self::new(
227                Permission::all(),
228                Permission::READ_EXECUTE,
229                Permission::READ_EXECUTE,
230                Special::NONE,
231            ),
232            Kind::File => Self::new(
233                Permission::READ_WRITE,
234                Permission::Read,
235                Permission::Read,
236                Special::NONE,
237            ),
238            Kind::Pipe => Self::new(
239                Permission::READ_WRITE,
240                Permission::empty(),
241                Permission::empty(),
242                Special::NONE,
243            ),
244            Kind::BlockDevice => Self::new(
245                Permission::all(),
246                Permission::READ_WRITE,
247                Permission::READ_WRITE,
248                Special::NONE,
249            ),
250            Kind::CharacterDevice => Self::new(
251                Permission::READ_WRITE,
252                Permission::READ_WRITE,
253                Permission::empty(),
254                Special::NONE,
255            ),
256            Kind::Socket => Self::ALL_READ_WRITE,
257            Kind::SymbolicLink => Self::ALL_FULL,
258        }
259    }
260
261    /// Sets the permission for the user.
262    pub fn set_user(mut self, user: Permission) -> Self {
263        self.0 = (self.0 & 0o7077) | (user.to_unix() as u16) << 6;
264        self
265    }
266
267    /// Sets the permission for the group.
268    pub fn set_group(mut self, group: Permission) -> Self {
269        self.0 = (self.0 & 0o7707) | (group.to_unix() as u16) << 3;
270        self
271    }
272
273    /// Sets the permission for others.
274    pub fn set_others(mut self, others: Permission) -> Self {
275        self.0 = (self.0 & 0o7770) | others.to_unix() as u16;
276        self
277    }
278
279    /// Sets the special permissions.
280    pub fn set_special(mut self, special: Special) -> Self {
281        self.0 = (self.0 & 0o0777) | (special.to_unix() as u16) << 9;
282        self
283    }
284
285    /// Gets the permission for the user.
286    pub fn get_user(&self) -> Permission {
287        Permission::from_unix(((self.0 >> 6) & 0b111) as u8).unwrap()
288    }
289
290    /// Gets the permission for the group.
291    pub fn get_group(&self) -> Permission {
292        Permission::from_unix(((self.0 >> 3) & 0b111) as u8).unwrap()
293    }
294
295    /// Gets the permission for others.
296    pub fn get_others(&self) -> Permission {
297        Permission::from_unix((self.0 & 0b111) as u8).unwrap()
298    }
299
300    /// Gets the special permissions.
301    pub fn get_special(&self) -> Special {
302        Special::from_unix((self.0 >> 9) as u8).unwrap()
303    }
304
305    /// Converts the permission to a Unix permission.
306    pub const fn from_octal(unix: u16) -> Option<Self> {
307        if unix > 0o777 {
308            return None;
309        }
310
311        Some(Self(unix))
312    }
313
314    /// Converts the permission to a Unix permission.
315    pub const fn as_u16(&self) -> u16 {
316        self.0
317    }
318}
319
320impl Special {
321    pub const NONE: Self = Self::empty();
322    pub const STICKY: Self = Self::from_bits_retain(1);
323    pub const SET_USER_IDENTIFIER: Self = Self::from_bits_retain(2);
324    pub const SET_GROUP_IDENTIFIER: Self = Self::from_bits_retain(4);
325
326    pub fn new(sticky: bool, set_gid: bool, set_uid: bool) -> Self {
327        Self::from_bits_retain((sticky as u8) | (set_gid as u8) << 1 | (set_uid as u8) << 2)
328    }
329
330    pub fn set_sticky(mut self, sticky: bool) -> Self {
331        self = Self::from_bits_retain((self.bits() & 0b110) | sticky as u8);
332        self
333    }
334
335    pub fn set_set_group_identifier(mut self, set_gid: bool) -> Self {
336        self = Self::from_bits_retain((self.bits() & 0b101) | (set_gid as u8) << 1);
337        self
338    }
339
340    pub fn set_set_user_identifier(mut self, set_uid: bool) -> Self {
341        self = Self::from_bits_retain((self.bits() & 0b011) | (set_uid as u8) << 2);
342        self
343    }
344
345    pub const fn get_sticky(&self) -> bool {
346        self.bits() & 0b001 != 0
347    }
348
349    pub const fn get_set_group_identifier(&self) -> bool {
350        self.bits() & 0b010 != 0
351    }
352
353    pub const fn get_set_user_identifier(&self) -> bool {
354        self.bits() & 0b100 != 0
355    }
356
357    pub const fn to_unix(&self) -> u8 {
358        self.bits()
359    }
360
361    pub fn from_unix(unix: u8) -> Option<Self> {
362        if unix > 0b111 {
363            return None;
364        }
365
366        Some(Self::from_bits_retain(unix))
367    }
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn test_new_permissions() {
376        let user = Permission::Read; // Read only
377        let group = Permission::Write; // Write only
378        let others = Permission::Execute; // Execute only
379        let special = Special::new(true, false, true); // Sticky and set user identifier
380        let permissions = Permissions::new(user, group, others, special);
381        assert_eq!(permissions.0, 0b101_100_010_001);
382    }
383
384    #[test]
385    fn test_new_permission() {
386        assert_eq!(Permission::Read.bits(), 0b100);
387        assert_eq!(Permission::Write.bits(), 0b010);
388        assert_eq!(Permission::Execute.bits(), 0b001);
389        assert_eq!(Permission::READ_WRITE.bits(), 0b110);
390        assert_eq!(Permission::WRITE_EXECUTE.bits(), 0b011);
391        assert_eq!(Permission::READ_EXECUTE.bits(), 0b101);
392        assert_eq!(Permission::empty().bits(), 0b000);
393        assert_eq!(Permission::all().bits(), 0b111);
394    }
395
396    #[test]
397    fn test_permission_type_to_unix() {
398        let read = Permission::Read;
399        assert_eq!(read.to_unix(), 4);
400        let write = Permission::Write;
401        assert_eq!(write.to_unix(), 2);
402        let execute = Permission::Execute;
403        assert_eq!(execute.to_unix(), 1);
404        let full = Permission::all();
405        assert_eq!(full.to_unix(), 7);
406        let none = Permission::empty();
407        assert_eq!(none.to_unix(), 0);
408    }
409
410    #[test]
411    fn test_permission_type_from_unix() {
412        let read = Permission::from_unix(4).unwrap();
413        assert_eq!(read, Permission::Read);
414        let write = Permission::from_unix(2).unwrap();
415        assert_eq!(write, Permission::Write);
416        let execute = Permission::from_unix(1).unwrap();
417        assert_eq!(execute, Permission::Execute);
418        let full = Permission::from_unix(7).unwrap();
419        assert_eq!(full, Permission::all());
420        let no = Permission::from_unix(0).unwrap();
421        assert_eq!(no, Permission::empty());
422    }
423
424    #[test]
425    fn test_permissions_type_from_unix() {
426        let permissions = Permissions::from_octal(0b101_101_101).unwrap();
427        assert_eq!(permissions.get_user().to_unix(), 5);
428        assert_eq!(permissions.get_group().to_unix(), 5);
429        assert_eq!(permissions.get_others().to_unix(), 5);
430    }
431
432    #[test]
433    fn test_permissions_type_to_unix() {
434        let user = Permission::Read | Permission::Execute; // Read and execute
435        let group = Permission::Read | Permission::Write; // Read and write
436        let others = Permission::Write | Permission::Execute; // Write and execute
437        let special = Special::new(true, false, true); // Sticky and set user identifier
438        let permissions = Permissions::new(user, group, others, special);
439        assert_eq!(permissions.as_u16(), 0b101_101_110_011);
440    }
441
442    #[test]
443    fn test_permission_type_contains() {
444        let read = Permission::Read;
445        let write = Permission::Write;
446        let read_write = Permission::READ_WRITE;
447        let read_execute = Permission::READ_EXECUTE;
448        let write_execute = Permission::WRITE_EXECUTE;
449        let execute = Permission::Execute;
450        let full = Permission::all();
451        let no = Permission::empty();
452
453        assert!(full.contains(read));
454        assert!(full.contains(write));
455        assert!(full.contains(execute));
456        assert!(full.contains(read_write));
457        assert!(full.contains(read_execute));
458        assert!(full.contains(write_execute));
459        assert!(full.contains(full));
460        assert!(full.contains(no));
461
462        assert!(read.contains(read));
463        assert!(!read.contains(write));
464        assert!(!read.contains(execute));
465        assert!(!read.contains(read_write));
466        assert!(!read.contains(read_execute));
467        assert!(!read.contains(write_execute));
468        assert!(!read.contains(full));
469        assert!(read.contains(no));
470
471        assert!(!write.contains(read));
472        assert!(write.contains(write));
473        assert!(!write.contains(execute));
474        assert!(!write.contains(read_write));
475        assert!(!write.contains(read_execute));
476        assert!(!write.contains(write_execute));
477        assert!(!write.contains(full));
478        assert!(write.contains(no));
479
480        assert!(!execute.contains(read));
481        assert!(!execute.contains(write));
482        assert!(execute.contains(execute));
483        assert!(!execute.contains(read_write));
484        assert!(!execute.contains(read_execute));
485        assert!(!execute.contains(write_execute));
486        assert!(!execute.contains(full));
487        assert!(execute.contains(no));
488
489        assert!(read_write.contains(read));
490        assert!(read_write.contains(write));
491        assert!(!read_write.contains(execute));
492        assert!(read_write.contains(read_write));
493        assert!(!read_write.contains(read_execute));
494        assert!(!read_write.contains(write_execute));
495        assert!(!read_write.contains(full));
496        assert!(read_write.contains(no));
497
498        assert!(read_execute.contains(read));
499        assert!(!read_execute.contains(write));
500        assert!(read_execute.contains(execute));
501        assert!(!read_execute.contains(read_write));
502        assert!(read_execute.contains(read_execute));
503        assert!(!read_execute.contains(write_execute));
504        assert!(!read_execute.contains(full));
505        assert!(read_execute.contains(no));
506
507        assert!(!write_execute.contains(read));
508        assert!(write_execute.contains(write));
509        assert!(write_execute.contains(execute));
510        assert!(!write_execute.contains(read_write));
511        assert!(!write_execute.contains(read_execute));
512        assert!(write_execute.contains(write_execute));
513        assert!(!write_execute.contains(full));
514        assert!(write_execute.contains(no));
515
516        assert!(!no.contains(read));
517        assert!(!no.contains(write));
518        assert!(!no.contains(execute));
519        assert!(!no.contains(read_write));
520        assert!(!no.contains(read_execute));
521        assert!(!no.contains(write_execute));
522        assert!(!no.contains(full));
523        assert!(no.contains(no));
524    }
525
526    #[test]
527    fn test_permission_unknown_bits() {
528        assert_eq!(Permission::from_bits(1 << 3), None);
529        assert_eq!(Permission::from_bits_truncate(0b1_1111), Permission::all());
530        assert_eq!(Permission::from_bits_retain(1 << 3).bits(), 1 << 3);
531
532        assert_eq!(Special::from_bits(1 << 3), None);
533        assert_eq!(Special::from_bits_truncate(0b1_1111), Special::all());
534        assert_eq!(Special::from_bits_retain(1 << 3).bits(), 1 << 3);
535    }
536
537    #[test]
538    fn test_shared_directory_permissions() {
539        let permissions = Permissions::SHARED_DIRECTORY;
540        assert_eq!(permissions.get_user(), Permission::all());
541        assert_eq!(permissions.get_group(), Permission::all());
542        assert_eq!(permissions.get_others(), Permission::all());
543        assert_eq!(permissions.get_special(), Special::STICKY);
544        assert!(permissions.get_special().get_sticky());
545        assert_eq!(permissions.as_u16(), 0o1777);
546    }
547}