file-mode 0.1.2

Decode Unix file mode bits, change them and apply them to files
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use crate::{Mode, User, Protection, ProtectionBit, Special, SpecialBit};
use std::str::FromStr;
use std::iter::Peekable;
use std::str::Chars;
use std::num::ParseIntError;
use std::fmt::{self, Display};
use std::error::Error;

/// Error parsing mode string.
#[derive(Debug)]
pub enum ModeParseError {
    UnexpectedChar(&'static str, char),
    UnexpectedEnd(&'static str),
    OctalParseError(ParseIntError),
}

impl Display for ModeParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ModeParseError::*;
        match self {
            UnexpectedChar(expected, c) => write!(f, "unexpected character '{}', expected: {}", c, expected),
            UnexpectedEnd(expected) => write!(f, "unexpected end of string, expected: {}", expected),
            OctalParseError(_) => write!(f, "failed to parse octal value"),
        }
    }
}

impl Error for ModeParseError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        use ModeParseError::*;
        match self {
            UnexpectedChar(_, _) => None,
            UnexpectedEnd(_) => None,
            OctalParseError(err) => Some(err),
        }
    }
}

// [ugoa]*
//
// Empty set: "If none of these are given, the effect is as if (a) were given, but bits that are set in the umask are not affected."
// So for empty mode needs to be masked by umask.
#[derive(Debug)]
struct Users(Vec<User>);

impl Users {
    fn parse(chars: &mut Peekable<Chars>) -> Users {
        use User::*;
        let mut users = Vec::new();
        loop {
            match chars.peek() {
                Some('u') => { users.push(Owner); },
                Some('g') => { users.push(Group); },
                Some('o') => { users.push(Other); },
                Some('a') => {
                    users.push(Owner);
                    users.push(Group);
                    users.push(Other);
                }
                _ => return Users(users)
            }
            chars.next();
        }
    }
}

// [-+=]
#[derive(Debug)]
enum Operator {
    Add,
    Sub,
    Set,
}

impl Operator {
    fn parse(chars: &mut Peekable<Chars>) -> Result<Operator, ModeParseError> {
        use Operator::*;
        let c = chars.next().ok_or(ModeParseError::UnexpectedEnd("operator"))?;
        match c {
            '-' => Ok(Sub),
            '+' => Ok(Add),
            '=' => Ok(Set),
            c => Err(ModeParseError::UnexpectedChar("[-+=]", c))
        }
    }
}

// [rwxXst]
#[derive(Debug)]
enum Bit {
    Protection(ProtectionBit),
    Special(SpecialBit),
}

impl Bit {
    fn parse(chars: &mut Peekable<Chars>) -> Result<Bit, ModeParseError> {
        use ProtectionBit::*;
        use SpecialBit::*;
        let c = chars.next().ok_or(ModeParseError::UnexpectedEnd("operator"))?;
        match c {
            'r' => Ok(Bit::Protection(Read)),
            'w' => Ok(Bit::Protection(Write)),
            'x' => Ok(Bit::Protection(Execute)),
            'X' => Ok(Bit::Protection(Search)),
            's' => Ok(Bit::Special(SetId)),
            't' => Ok(Bit::Special(Sticky)),
            c => Err(ModeParseError::UnexpectedChar("[rwxXst]", c))
        }
    }
}

// [rwxXst]*|[ugo]
#[derive(Debug)]
enum Value {
    Bits(Vec<Bit>),
    Source(User),
}

impl Value {
    fn parse(chars: &mut Peekable<Chars>) -> Result<Value, ModeParseError> {
        use Value::*;
        use User::*;

        if let Some(c) = chars.peek() {
            let user = match c {
                'u' => Some(Owner),
                'g' => Some(Group),
                'o' => Some(Other),
                _ => None,
            };

            if let Some(user) = user {
                chars.next();
                Ok(Source(user))
            } else {
                let mut bits = Vec::new();

                while chars.peek().is_some() {
                    bits.push(Bit::parse(chars).unwrap());
                }

                Ok(Value::Bits(bits))
            }
        } else {
            Ok(Value::Bits(Vec::new()))
        }
    }
}

// [-+=]([rwxXst]*|[ugo])
#[derive(Debug)]
struct Expression {
    operator: Operator,
    value: Value,
}

impl Expression {
    fn parse(chars: &mut Peekable<Chars>) -> Result<Expression, ModeParseError> {
        Ok(Expression {
            operator: Operator::parse(chars)?,
            value: Value::parse(chars)?,
        })
    }
}

// [ugoa]*([-+=]([rwxXst]*|[ugo]))+
#[derive(Debug)]
struct SymbolicMode {
    users: Users,
    // non-empty
    expressions: Vec<Expression>,
}

impl SymbolicMode {
    fn parse(chars: &mut Peekable<Chars>) -> Result<SymbolicMode, ModeParseError> {
        let users = Users::parse(chars);
        let mut expressions = Vec::new();

        loop {
            if chars.peek().is_none() {
                break
            }

            expressions.push(Expression::parse(chars)?);
        }

        if expressions.is_empty() {
           Err(ModeParseError::UnexpectedEnd("bits or user flags"))
        } else {
            Ok(SymbolicMode {
                users,
                expressions,
            })
        }
    }
}

// [-+=][0-7]+
#[derive(Debug)]
struct OctalMode {
    operator: Operator,
    mode: Mode,
}

impl OctalMode {
    fn parse(chars: &mut Peekable<Chars>) -> Result<OctalMode, ModeParseError> {
        let operator = Operator::parse(chars)?;

        let mut mode = String::new();
        for c in chars {
            match c {
                c @ '0'..='7' => mode.push(c),
                c => return Err(ModeParseError::UnexpectedChar("[0-7]", c)),
            }
        }

        if mode.is_empty() {
            mode.push('0')
        }

        let mode = u32::from_str_radix(&mode, 8).map_err(ModeParseError::OctalParseError)?;

        Ok(OctalMode {
            operator,
            mode: Mode::new(mode, 0o7777),
        })
    }
}

// [ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+
#[derive(Debug)]
enum ModeString {
    Symbolic(SymbolicMode),
    Octal(OctalMode),
}

impl FromStr for ModeString {
    type Err = ModeParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars().peekable();

        let mode_string = if s.ends_with(|c| ('0'..='7').contains(&c)) {
            ModeString::Octal(OctalMode::parse(&mut chars)?)
        } else {
            ModeString::Symbolic(SymbolicMode::parse(&mut chars)?)
        };

        if let Some(c) = chars.next() {
            Err(ModeParseError::UnexpectedChar("no more characters", c))
        } else {
            Ok(mode_string)
        }
    }
}

impl ModeString {
    //TODO: rewrite as an iterator to avoid allocation
    fn into_operations(self, ref_mode: u32, umask: u32) -> Vec<(Operator, Mode)> {
        let mut ops = Vec::new();

        match self {
            ModeString::Symbolic(symbolic) =>  {
                let (users, umask) = if symbolic.users.0.is_empty() {
                    (vec![User::Owner, User::Group, User::Other], umask)
                } else {
                    (symbolic.users.0, 0o0)
                };

                for expr in symbolic.expressions {
                    let mut mode = Mode::empty();

                    let mut protection = match &expr.operator {
                        Operator::Set => Protection::all_clear(), // for = all bits needs to be managed
                        _ => Protection::empty(),
                    };

                    let mut special = Special::empty();

                    match expr.value {
                        Value::Bits(bits) => for bit in bits {
                            match bit {
                                Bit::Protection(protection_bit) => protection.set(protection_bit),
                                Bit::Special(special_bit) => special.set(special_bit),
                            }
                        }
                        Value::Source(source_user) => {
                            let mask = match &expr.operator {
                                Operator::Set => 0o777, // copy all bits
                                _ => ref_mode, // copy only bits set
                            };

                            let mut ref_mode = Mode::new(ref_mode, mask);
                            ref_mode.set(&mode);
                            protection = ref_mode.user_protection(source_user);
                        }
                    }

                    for user in &users {
                        mode.set_protection(*user, &protection);
                        mode.set_special(*user, &special);
                    }

                    mode.apply_umask(umask);

                    ops.push((expr.operator, mode));
                }
            }
            ModeString::Octal(OctalMode { operator, mode }) => ops.push((operator, mode)),
        }

        ops
    }
}

pub(crate) fn mode_set_from_str(mode: &mut Mode, mode_str: &str, umask: u32) -> Result<(), ModeParseError> {
    for mode_str in mode_str.split(',') {
        set(mode, mode_str, umask)?;
    }
    Ok(())
}

/* Examples:
 * g=r+w
 * g=o
 * =
 */
fn set(target: &mut Mode, mode_str: &str, umask: u32) -> Result<(), ModeParseError> {
    let ms = ModeString::from_str(mode_str)?;

    for (operator, mode) in ms.into_operations(target.mode, umask) {
        match operator {
            Operator::Add => target.add(&mode),
            Operator::Sub => target.sub(&mode),
            Operator::Set => target.set(&mode),
        }
    }

    Ok(())
}

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

    #[test]
    fn test_parse_users() {
        use User::*;

        let mut i = "a".chars().peekable();
        assert_eq!(Users::parse(&mut i).0, vec![Owner, Group, Other]);
        assert!(i.next().is_none());

        let mut i = "uog".chars().peekable();
        assert_eq!(Users::parse(&mut i).0, vec![Owner, Other, Group]);
        assert!(i.next().is_none());

        let mut i = "uxog".chars().peekable();
        assert_eq!(Users::parse(&mut i).0, vec![Owner]);
        assert_eq!(&i.collect::<String>(), "xog");

        let mut i = "uoxg".chars().peekable();
        assert_eq!(Users::parse(&mut i).0, vec![Owner, Other]);
        assert_eq!(&i.collect::<String>(), "xg");

        let mut i = "uogx".chars().peekable();
        assert_eq!(Users::parse(&mut i).0, vec![Owner, Other, Group]);
        assert_eq!(&i.collect::<String>(), "x");
    }

    #[test]
    fn test_parse_value() {
        use ProtectionBit::*;
        use SpecialBit::*;

        let mut i = "".chars().peekable();
        assert_matches!(Value::parse(&mut i).unwrap(), Value::Bits(bits) => {
            assert!(bits.is_empty());
        });
        assert!(i.next().is_none());

        let mut i = "rwxst".chars().peekable();
        assert_matches!(Value::parse(&mut i).unwrap(), Value::Bits(bits) => {
            let mut b = bits.into_iter();
            assert_matches!(b.next().unwrap(), Bit::Protection(Read));
            assert_matches!(b.next().unwrap(), Bit::Protection(Write));
            assert_matches!(b.next().unwrap(), Bit::Protection(Execute));
            assert_matches!(b.next().unwrap(), Bit::Special(SetId));
            assert_matches!(b.next().unwrap(), Bit::Special(Sticky));
            assert!(b.next().is_none());
        });
        assert!(i.next().is_none());

        let mut i = "xw".chars().peekable();
        assert_matches!(Value::parse(&mut i).unwrap(), Value::Bits(bits) => {
            let mut b = bits.into_iter();
            assert_matches!(b.next().unwrap(), Bit::Protection(Execute));
            assert_matches!(b.next().unwrap(), Bit::Protection(Write));
            assert!(b.next().is_none());
        });
        assert!(i.next().is_none());

        let mut i = "u".chars().peekable();
        assert_matches!(Value::parse(&mut i).unwrap(), Value::Source(User::Owner));
        assert!(i.next().is_none());

        let mut i = "g".chars().peekable();
        assert_matches!(Value::parse(&mut i).unwrap(), Value::Source(User::Group));
        assert!(i.next().is_none());

        let mut i = "o".chars().peekable();
        assert_matches!(Value::parse(&mut i).unwrap(), Value::Source(User::Other));
        assert!(i.next().is_none());

        let mut i = "oo?".chars().peekable();
        assert_matches!(Value::parse(&mut i).unwrap(), Value::Source(User::Other));
        assert_eq!(i.next(), Some('o'));
    }

    #[test]
    fn test_parse_symbolic_mode() {
        use User::*;

        let mut i = "u+r".chars().peekable();
        assert_matches!(SymbolicMode::parse(&mut i).unwrap(), SymbolicMode { users, expressions } => {
            assert_eq!(users.0, vec![Owner]);

            let mut e = expressions.into_iter();
            assert_matches!(e.next().unwrap(), Expression { operator: Operator::Add, value } => {
                assert_matches!(value, Value::Bits(bits) => {
                    let mut b = bits.into_iter();
                    assert_matches!(b.next().unwrap(), Bit::Protection(ProtectionBit::Read));
                    assert!(b.next().is_none());
                });
            });
            assert!(e.next().is_none());
        });
        assert!(i.next().is_none());

        let mut i = "=rs".chars().peekable();
        assert_matches!(SymbolicMode::parse(&mut i).unwrap(), SymbolicMode { users, expressions } => {
            assert_eq!(users.0, vec![]);

            let mut e = expressions.into_iter();
            assert_matches!(e.next().unwrap(), Expression { operator: Operator::Set, value } => {
                assert_matches!(value, Value::Bits(bits) => {
                    let mut b = bits.into_iter();
                    assert_matches!(b.next().unwrap(), Bit::Protection(ProtectionBit::Read));
                    assert_matches!(b.next().unwrap(), Bit::Special(SpecialBit::SetId));
                    assert!(b.next().is_none());
                });
            });
            assert!(e.next().is_none());
        });
        assert!(i.next().is_none());

        let mut i = "a=u".chars().peekable();
        assert_matches!(SymbolicMode::parse(&mut i).unwrap(), SymbolicMode { users, expressions } => {
            assert_eq!(users.0, vec![Owner, Group, Other]);

            let mut e = expressions.into_iter();
            assert_matches!(e.next().unwrap(), Expression { operator: Operator::Set, value } => {
                assert_matches!(value, Value::Source(Owner));
            });
            assert!(e.next().is_none());
        });
        assert!(i.next().is_none());
    }

    #[test]
    fn test_parse_octal_mode() {
        let mut i = "=777".chars().peekable();
        assert_matches!(OctalMode::parse(&mut i).unwrap(), OctalMode { operator: Operator::Set, mode } => {
            assert_eq!(mode, Mode::new(0o777, 0o7777));
        });
        assert!(i.next().is_none());

        let mut i = "-7".chars().peekable();
        assert_matches!(OctalMode::parse(&mut i).unwrap(), OctalMode { operator: Operator::Sub, mode } => {
            assert_eq!(mode, Mode::new(0o007, 0o7777));
        });
        assert!(i.next().is_none());

        let mut i = "+23".chars().peekable();
        assert_matches!(OctalMode::parse(&mut i).unwrap(), OctalMode { operator: Operator::Add, mode } => {
            assert_eq!(mode, Mode::new(0o023, 0o7777));
        });
        assert!(i.next().is_none());

        let mut i = "+023".chars().peekable();
        assert_matches!(OctalMode::parse(&mut i).unwrap(), OctalMode { operator: Operator::Add, mode } => {
            assert_eq!(mode, Mode::new(0o023, 0o7777));
        });
        assert!(i.next().is_none());

        let mut i = "=".chars().peekable();
        assert_matches!(OctalMode::parse(&mut i).unwrap(), OctalMode { operator: Operator::Set, mode } => {
            assert_eq!(mode, Mode::new(0o000, 0o7777));
        });
        assert!(i.next().is_none());
    }
}