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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! This parser and the tests are a translation of the official Python netrc library.

use crate::lex::Lex;
use std::collections::HashMap;

#[derive(Debug)]
pub struct ParsingError {
    lineno: u32,
    message: String,
}

impl std::fmt::Display for ParsingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "parsing error: {} (line {})", self.message, self.lineno)
    }
}

/// Authenticators for host.
#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct Authenticator {
    /// Identify a user on the remote machine.
    pub login: String,

    /// Supply an additional account password.
    pub account: String,

    /// Supply a password
    pub password: String,
}

impl Authenticator {
    #[allow(dead_code)]
    pub fn new(login: &str, account: &str, password: &str) -> Self {
        Authenticator {
            login: login.to_owned(),
            account: account.to_owned(),
            password: password.to_owned(),
        }
    }
}

/// Represents the netrc file.
#[derive(Debug, Default)]
pub struct Netrc {
    /// Dictionary mapping host names to the authentificators.
    pub hosts: HashMap<String, Authenticator>,

    /// Dictionary mapping macro names to string lists.
    pub macros: HashMap<String, Vec<String>>,
}

impl std::fmt::Display for Netrc {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut rep = String::new();
        for (host, attrs) in self.hosts.iter() {
            rep.push_str(&format!("machine {}\n\tlogin {}\n", host, attrs.login));
            if !attrs.account.is_empty() {
                rep.push_str(&format!("\taccount  {}\n", attrs.account));
            }
            rep.push_str(&format!("\tpassword  {}\n", attrs.password));
        }
        for (macro_, lines) in self.macros.iter() {
            rep.push_str(&format!("macdef {}\n", macro_));
            for line in lines.iter() {
                rep.push_str(&format!("{}\n", line));
            }
        }
        write!(f, "{}", rep)
    }
}

impl std::str::FromStr for Netrc {
    type Err = ParsingError;

    fn from_str(s: &str) -> Result<Self, ParsingError> {
        let mut res = Netrc::default();
        let mut lexer = Lex::new(s);

        loop {
            let saved_lineno = lexer.lineno;
            let tt = lexer.get_token();
            if tt.is_empty() {
                break;
            }
            if tt.chars().nth(0) == Some('#') {
                if lexer.lineno == saved_lineno && tt.len() == 1 {
                    lexer.read_line();
                }
                continue;
            }

            #[allow(clippy::needless_late_init)]
            let entryname;
            match tt.as_str() {
                "" => {
                    break;
                }
                "machine" => {
                    entryname = lexer.get_token();
                }
                "default" => {
                    entryname = String::from("default");
                }
                "macdef" => {
                    entryname = lexer.get_token();
                    let mut v = Vec::new();
                    loop {
                        let line = lexer.read_line();
                        if line.trim().is_empty() {
                            break;
                        }
                        v.push(line.trim().to_owned());
                    }
                    res.macros.insert(entryname, v);
                    continue;
                }
                _ => {
                    return Err(ParsingError {
                        lineno: lexer.lineno,
                        message: format!("bad toplevel token '{}'", tt),
                    });
                }
            };
            if entryname.is_empty() {
                return Err(ParsingError {
                    lineno: lexer.lineno,
                    message: format!("missing '{}' name", tt),
                });
            }

            let mut auth = Authenticator::default();

            loop {
                let prev_lineno = lexer.lineno;
                let tt = lexer.get_token();
                if tt.starts_with('#') {
                    if lexer.lineno == prev_lineno {
                        lexer.read_line();
                    }
                    continue;
                }
                match tt.as_str() {
                    "" | "machine" | "default" | "macdef" => {
                        res.hosts.insert(entryname, auth);
                        lexer.push_token(&tt);
                        break;
                    }
                    "login" | "user" => {
                        auth.login = lexer.get_token();
                    }
                    "account" => {
                        auth.account = lexer.get_token();
                    }
                    "password" => {
                        auth.password = lexer.get_token();
                    }
                    _ => {
                        return Err(ParsingError {
                            lineno: lexer.lineno,
                            message: format!("bad follower token '{}'", tt),
                        });
                    }
                };
            }
        }

        Ok(res)
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn test_toplevel_non_ordered_tokens() {
        let nrc = Netrc::from_str(
            "\
            machine host.domain.com password pass1 login log1 account acct1
            default login log2 password pass2 account acct2
        ",
        )
        .unwrap();

        assert_eq!(
            nrc.hosts["host.domain.com"],
            Authenticator::new("log1", "acct1", "pass1")
        );
        assert_eq!(
            nrc.hosts["default"],
            Authenticator::new("log2", "acct2", "pass2")
        );
    }

    #[test]
    fn test_toplevel_tokens() {
        let nrc = Netrc::from_str(
            "\
            machine host.domain.com login log1 password pass1 account acct1
            default login log2 password pass2 account acct2
        ",
        )
        .unwrap();
        assert_eq!(
            nrc.hosts["host.domain.com"],
            Authenticator::new("log1", "acct1", "pass1")
        );
        assert_eq!(
            nrc.hosts["default"],
            Authenticator::new("log2", "acct2", "pass2")
        );
    }

    #[test]
    fn test_macros() {
        let nrc = Netrc::from_str(
            "\
            macdef macro1
            line1
            line2

            macdef macro2
            line3
            line4
            ",
        )
        .unwrap();
        assert_eq!(nrc.macros["macro1"], vec!["line1", "line2"]);
        assert_eq!(nrc.macros["macro2"], vec!["line3", "line4"]);
    }

    #[test]
    fn test_optional_tokens_machine() {
        let data = vec![
            "machine host.domain.com",
            "machine host.domain.com login",
            "machine host.domain.com account",
            "machine host.domain.com password",
            "machine host.domain.com login \"\" account",
            "machine host.domain.com login \"\" password",
            "machine host.domain.com account \"\" password",
        ];

        for item in data {
            let nrc = Netrc::from_str(item).unwrap();
            assert_eq!(nrc.hosts["host.domain.com"], Authenticator::new("", "", ""));
        }
    }

    #[test]
    fn test_optional_tokens_default() {
        let data = vec![
            "default",
            "default login",
            "default account",
            "default password",
            "default login \"\" account",
            "default login \"\" password",
            "default account \"\" password",
        ];

        for item in data {
            let nrc = Netrc::from_str(item).unwrap();
            assert_eq!(nrc.hosts["default"], Authenticator::new("", "", ""));
        }
    }

    #[test]
    fn test_invalid_tokens() {
        let data = vec![
            (
                "invalid host.domain.com",
                "parsing error: bad toplevel token 'invalid' (line 1)",
            ),
            (
                "machine host.domain.com invalid",
                "parsing error: bad follower token 'invalid' (line 1)",
            ),
            (
                "machine host.domain.com login log password pass account acct invalid",
                "parsing error: bad follower token 'invalid' (line 1)",
            ),
            (
                "default host.domain.com invalid",
                "parsing error: bad follower token 'host.domain.com' (line 1)",
            ),
            (
                "default host.domain.com login log password pass account acct invalid",
                "parsing error: bad follower token 'host.domain.com' (line 1)",
            ),
        ];

        for (item, msg) in data {
            let nrc = Netrc::from_str(item);
            assert_eq!(nrc.unwrap_err().to_string(), msg);
        }
    }

    fn test_token_x(data: &str, token: &str, value: &str) {
        let nrc = Netrc::from_str(data).unwrap();
        match token {
            "login" => {
                assert_eq!(
                    nrc.hosts["host.domain.com"],
                    Authenticator::new(value, "acct", "pass")
                );
            }
            "account" => {
                assert_eq!(
                    nrc.hosts["host.domain.com"],
                    Authenticator::new("log", value, "pass")
                );
            }
            "password" => {
                assert_eq!(
                    nrc.hosts["host.domain.com"],
                    Authenticator::new("log", "acct", value)
                );
            }
            _ => {}
        };
    }

    #[test]
    fn test_token_value_quotes() {
        test_token_x(
            "\
            machine host.domain.com login \"log\" password pass account acct
            ",
            "login",
            "log",
        );
        test_token_x(
            "\
            machine host.domain.com login log password pass account \"acct\"
            ",
            "account",
            "acct",
        );
        test_token_x(
            "\
            machine host.domain.com login log password \"pass\" account acct
            ",
            "password",
            "pass",
        );
    }

    #[test]
    fn test_token_value_escape() {
        test_token_x(
            r#"machine host.domain.com login \"log password pass account acct"#,
            "login",
            "\"log",
        );
        test_token_x(
            "\
            machine host.domain.com login \"\\\"log\" password pass account acct
            ",
            "login",
            "\"log",
        );
        test_token_x(
            "\
            machine host.domain.com login log password pass account \\\"acct
            ",
            "account",
            "\"acct",
        );
        test_token_x(
            "\
            machine host.domain.com login log password pass account \"\\\"acct\"
            ",
            "account",
            "\"acct",
        );
        test_token_x(
            "\
            machine host.domain.com login log password \\\"pass account acct
            ",
            "password",
            "\"pass",
        );
        test_token_x(
            "\
            machine host.domain.com login log password \"\\\"pass\" account acct
            ",
            "password",
            "\"pass",
        );
    }

    #[test]
    fn test_token_value_whitespace() {
        test_token_x(
            r#"machine host.domain.com login "lo g" password pass account acct"#,
            "login",
            "lo g",
        );
        test_token_x(
            r#"machine host.domain.com login log password "pas s" account acct"#,
            "password",
            "pas s",
        );
        test_token_x(
            r#"machine host.domain.com login log password pass account "acc t""#,
            "account",
            "acc t",
        );
    }

    #[test]
    fn test_token_value_non_ascii() {
        test_token_x(
            r#"machine host.domain.com login ¡¢ password pass account acct"#,
            "login",
            "¡¢",
        );
        test_token_x(
            r#"machine host.domain.com login log password pass account ¡¢"#,
            "account",
            "¡¢",
        );
        test_token_x(
            r#"machine host.domain.com login log password ¡¢ account acct"#,
            "password",
            "¡¢",
        );
    }

    #[test]
    fn test_token_value_leading_hash() {
        test_token_x(
            r#"machine host.domain.com login #log password pass account acct"#,
            "login",
            "#log",
        );
        test_token_x(
            r#"machine host.domain.com login log password pass account #acct"#,
            "account",
            "#acct",
        );
        test_token_x(
            r#"machine host.domain.com login log password #pass account acct"#,
            "password",
            "#pass",
        );
    }

    #[test]
    fn test_token_value_trailing_hash() {
        test_token_x(
            r#"machine host.domain.com login log# password pass account acct"#,
            "login",
            "log#",
        );
        test_token_x(
            r#"machine host.domain.com login log password pass account acct#"#,
            "account",
            "acct#",
        );
        test_token_x(
            r#"machine host.domain.com login log password pass# account acct"#,
            "password",
            "pass#",
        );
    }

    #[test]
    fn test_token_value_internal_hash() {
        test_token_x(
            r#"machine host.domain.com login lo#g password pass account acct"#,
            "login",
            "lo#g",
        );
        test_token_x(
            r#"machine host.domain.com login log password pass account ac#ct"#,
            "account",
            "ac#ct",
        );
        test_token_x(
            r#"machine host.domain.com login log password pa#ss account acct"#,
            "password",
            "pa#ss",
        );
    }

    fn test_comment(data: &str) {
        let nrc = Netrc::from_str(data).unwrap();
        assert_eq!(
            nrc.hosts["foo.domain.com"],
            Authenticator::new("bar", "", "pass")
        );
        assert_eq!(
            nrc.hosts["bar.domain.com"],
            Authenticator::new("foo", "", "pass")
        );
    }

    #[test]
    fn test_comment_before_machine_line() {
        test_comment(
            r#"# comment
            machine foo.domain.com login bar password pass
            machine bar.domain.com login foo password pass
            "#,
        );
    }
    #[test]
    fn test_comment_before_machine_line_no_space() {
        test_comment(
            r#"#comment
            machine foo.domain.com login bar password pass
            machine bar.domain.com login foo password pass
            "#,
        );
    }

    #[test]
    fn test_comment_before_machine_line_hash_only() {
        test_comment(
            r#"#
            machine foo.domain.com login bar password pass
            machine bar.domain.com login foo password pass
            "#,
        );
    }

    #[test]
    fn test_comment_after_machine_line() {
        test_comment(
            r#"machine foo.domain.com login bar password pass
            # comment
            machine bar.domain.com login foo password pass
            "#,
        );
        test_comment(
            r#"machine foo.domain.com login bar password pass
            machine bar.domain.com login foo password pass
            # comment
            "#,
        );
    }

    #[test]
    fn test_comment_after_machine_line_no_space() {
        test_comment(
            r#"machine foo.domain.com login bar password pass
            #comment
            machine bar.domain.com login foo password pass
            "#,
        );
        test_comment(
            r#"machine foo.domain.com login bar password pass
            machine bar.domain.com login foo password pass
            #comment
            "#,
        );
    }

    #[test]
    fn test_comment_after_machine_line_hash_only() {
        test_comment(
            r#"machine foo.domain.com login bar password pass
            #
            machine bar.domain.com login foo password pass
            "#,
        );
        test_comment(
            r#"machine foo.domain.com login bar password pass
            machine bar.domain.com login foo password pass
            #
            "#,
        );
    }

    #[test]
    fn test_comment_at_end_of_machine_line() {
        test_comment(
            r#"machine foo.domain.com login bar password pass # comment
            machine bar.domain.com login foo password pass
            "#,
        );
    }

    #[test]
    fn test_comment_at_end_of_machine_line_no_space() {
        test_comment(
            r#"machine foo.domain.com login bar password pass #comment
            machine bar.domain.com login foo password pass
            "#,
        );
    }

    #[test]
    fn test_comment_at_end_of_machine_line_pass_has_hash() {
        let nrc = Netrc::from_str(
            r#"machine foo.domain.com login bar password #pass #comment
            machine bar.domain.com login foo password pass
        "#,
        )
        .unwrap();
        assert_eq!(
            nrc.hosts["foo.domain.com"],
            Authenticator::new("bar", "", "#pass")
        );
        assert_eq!(
            nrc.hosts["bar.domain.com"],
            Authenticator::new("foo", "", "pass")
        );
    }
}