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
use crate::{
    parse::{
        address::{General_address_literal, IPv4_address_literal, IPv6_address_literal},
        base64,
        imf::atom::is_atext,
    },
    types::Command,
};
use abnf_core::streaming::{is_ALPHA, is_DIGIT, CRLF, DQUOTE, SP};
use nom::{
    branch::alt,
    bytes::streaming::{tag, tag_no_case, take_while, take_while1, take_while_m_n},
    combinator::{map_res, opt, recognize},
    multi::many0,
    sequence::{delimited, preceded, tuple},
    IResult,
};

pub fn command(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = alt((
        helo, ehlo, mail, rcpt, data, rset, vrfy, expn, help, noop, quit,
        starttls,   // Extensions
        auth_login, // https://interoperability.blob.core.windows.net/files/MS-XLOGIN/[MS-XLOGIN].pdf
        auth_plain, // RFC 4616
    ));

    let (remaining, parsed) = parser(input)?;

    Ok((remaining, parsed))
}

/// helo = "HELO" SP Domain CRLF
pub fn helo(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((
        tag_no_case(b"HELO"),
        SP,
        alt((Domain, address_literal)), // address_literal alternative for Geary
        CRLF,
    ));

    let (remaining, (_, _, data, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Helo {
            fqdn_or_address_literal: data.into(),
        },
    ))
}

/// ehlo = "EHLO" SP ( Domain / address-literal ) CRLF
pub fn ehlo(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((
        tag_no_case(b"EHLO"),
        SP,
        alt((Domain, address_literal)),
        CRLF,
    ));

    let (remaining, (_, _, data, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Ehlo {
            fqdn_or_address_literal: data.into(),
        },
    ))
}

/// mail = "MAIL FROM:" Reverse-path [SP Mail-parameters] CRLF
pub fn mail(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((
        tag_no_case(b"MAIL FROM:"),
        opt(SP), // Out-of-Spec, but Outlook does it ...
        Reverse_path,
        opt(preceded(SP, Mail_parameters)),
        CRLF,
    ));

    let (remaining, (_, _, data, maybe_params, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Mail {
            reverse_path: data.into(),
            parameters: maybe_params.map(|params| params.into()),
        },
    ))
}

/// rcpt = "RCPT TO:" ( "<Postmaster@" Domain ">" / "<Postmaster>" / Forward-path ) [SP Rcpt-parameters] CRLF
///
/// Note that, in a departure from the usual rules for
/// local-parts, the "Postmaster" string shown above is
/// treated as case-insensitive.
pub fn rcpt(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((
        tag_no_case(b"RCPT TO:"),
        opt(SP), // Out-of-Spec, but Outlook does it ...
        alt((
            recognize(tuple((tag_no_case(b"<Postmaster@"), Domain, tag(b">")))),
            tag_no_case(b"<Postmaster>"),
            Forward_path,
        )),
        opt(preceded(SP, Rcpt_parameters)),
        CRLF,
    ));

    let (remaining, (_, _, data, maybe_params, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Rcpt {
            forward_path: data.into(),
            parameters: maybe_params.map(|params| params.into()),
        },
    ))
}

/// data = "DATA" CRLF
pub fn data(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"DATA"), CRLF));

    let (remaining, _) = parser(input)?;

    Ok((remaining, Command::Data))
}

/// rset = "RSET" CRLF
pub fn rset(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"RSET"), CRLF));

    let (remaining, _) = parser(input)?;

    Ok((remaining, Command::Rset))
}

/// vrfy = "VRFY" SP String CRLF
pub fn vrfy(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"VRFY"), SP, String, CRLF));

    let (remaining, (_, _, data, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Vrfy {
            user_or_mailbox: data.into(),
        },
    ))
}

/// expn = "EXPN" SP String CRLF
pub fn expn(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"EXPN"), SP, String, CRLF));

    let (remaining, (_, _, data, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Expn {
            mailing_list: data.into(),
        },
    ))
}

/// help = "HELP" [ SP String ] CRLF
pub fn help(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"HELP"), opt(preceded(SP, String)), CRLF));

    let (remaining, (_, maybe_data, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Help {
            argument: maybe_data.map(|data| data.into()),
        },
    ))
}

/// noop = "NOOP" [ SP String ] CRLF
pub fn noop(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"NOOP"), opt(preceded(SP, String)), CRLF));

    let (remaining, (_, maybe_data, _)) = parser(input)?;

    Ok((
        remaining,
        Command::Noop {
            argument: maybe_data.map(|data| data.into()),
        },
    ))
}

/// quit = "QUIT" CRLF
pub fn quit(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"QUIT"), CRLF));

    let (remaining, _) = parser(input)?;

    Ok((remaining, Command::Quit))
}

pub fn starttls(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((tag_no_case(b"STARTTLS"), CRLF));

    let (remaining, _) = parser(input)?;

    Ok((remaining, Command::StartTLS))
}

/// https://interoperability.blob.core.windows.net/files/MS-XLOGIN/[MS-XLOGIN].pdf
///
/// username = 1*CHAR ; Base64-encoded username
/// password = 1*CHAR ; Base64-encoded password
///
/// auth_login_command = "AUTH LOGIN" [SP username] CRLF
///
/// auth_login_username_challenge = "334 VXNlcm5hbWU6" CRLF
/// auth_login_username_response  = username CRLF
/// auth_login_password_challenge = "334 UGFzc3dvcmQ6" CRLF
/// auth_login_password_response  = password CRLF
pub fn auth_login(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((
        tag_no_case(b"AUTH"),
        SP,
        tag_no_case("LOGIN"),
        opt(preceded(SP, base64)),
        CRLF,
    ));

    let (remaining, (_, _, _, maybe_username_b64, _)) = parser(input)?;

    Ok((
        remaining,
        Command::AuthLogin(maybe_username_b64.map(|i| i.to_owned())),
    ))
}

pub fn auth_plain(input: &[u8]) -> IResult<&[u8], Command> {
    let mut parser = tuple((
        tag_no_case(b"AUTH"),
        SP,
        tag_no_case("PLAIN"),
        opt(preceded(SP, base64)),
        CRLF,
    ));

    let (remaining, (_, _, _, maybe_credentials_b64, _)) = parser(input)?;

    Ok((
        remaining,
        Command::AuthPlain(maybe_credentials_b64.map(|i| i.to_owned())),
    ))
}

// ----- 4.1.2.  Command Argument Syntax (RFC 5321) -----

/// Reverse-path = Path / "<>"
pub fn Reverse_path(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = alt((Path, tag(b"<>")));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Forward-path = Path
pub fn Forward_path(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = Path;

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

// Path = "<" [ A-d-l ":" ] Mailbox ">"
pub fn Path(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((
        tag(b"<"),
        opt(tuple((A_d_l, tag(b":")))),
        Mailbox,
        tag(b">"),
    ));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// A-d-l = At-domain *( "," At-domain )
///          ; Note that this form, the so-called "source
///          ; route", MUST BE accepted, SHOULD NOT be
///          ; generated, and SHOULD be ignored.
pub fn A_d_l(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((At_domain, many0(tuple((tag(b","), At_domain)))));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// At-domain = "@" Domain
pub fn At_domain(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((tag(b"@"), Domain));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Mail-parameters = esmtp-param *(SP esmtp-param)
pub fn Mail_parameters(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((esmtp_param, many0(tuple((SP, esmtp_param)))));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Rcpt-parameters = esmtp-param *(SP esmtp-param)
pub fn Rcpt_parameters(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((esmtp_param, many0(tuple((SP, esmtp_param)))));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// esmtp-param = esmtp-keyword ["=" esmtp-value]
pub fn esmtp_param(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((esmtp_keyword, opt(tuple((tag(b"="), esmtp_value)))));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// esmtp-keyword = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")
pub fn esmtp_keyword(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((
        take_while_m_n(1, 1, |byte| is_ALPHA(byte) || is_DIGIT(byte)),
        take_while(|byte| is_ALPHA(byte) || is_DIGIT(byte) || byte == b'-'),
    ));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Any CHAR excluding "=", SP, and control characters.
/// If this string is an email address, i.e., a Mailbox,
/// then the "xtext" syntax [32] SHOULD be used.
///
/// esmtp-value = 1*(%d33-60 / %d62-126)
pub fn esmtp_value(input: &[u8]) -> IResult<&[u8], &[u8]> {
    fn is_value_character(byte: u8) -> bool {
        matches!(byte, 33..=60 | 62..=126)
    }

    take_while1(is_value_character)(input)
}

/// Keyword = Ldh-str
pub fn Keyword(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = Ldh_str;

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Argument = Atom
pub fn Argument(input: &[u8]) -> IResult<&[u8], &[u8]> {
    Atom(input)
}

/// Domain = sub-domain *("." sub-domain)
pub fn Domain(input: &[u8]) -> IResult<&[u8], &str> {
    let parser = tuple((sub_domain, many0(tuple((tag(b"."), sub_domain)))));

    let (remaining, parsed) = map_res(recognize(parser), std::str::from_utf8)(input)?;

    Ok((remaining, parsed))
}

/// sub-domain = Let-dig [Ldh-str]
pub fn sub_domain(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((take_while_m_n(1, 1, is_Let_dig), opt(Ldh_str)));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Let-dig = ALPHA / DIGIT
pub fn is_Let_dig(byte: u8) -> bool {
    is_ALPHA(byte) || is_DIGIT(byte)
}

/// Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
pub fn Ldh_str(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = many0(alt((
        take_while_m_n(1, 1, is_ALPHA),
        take_while_m_n(1, 1, is_DIGIT),
        recognize(tuple((tag(b"-"), take_while_m_n(1, 1, is_Let_dig)))),
    )));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// address-literal = "[" (
///                       IPv4-address-literal /
///                       IPv6-address-literal /
///                       General-address-literal
///                   ) "]"
///                     ; See Section 4.1.3
pub fn address_literal(input: &[u8]) -> IResult<&[u8], &str> {
    let mut parser = delimited(
        tag(b"["),
        map_res(
            alt((
                IPv4_address_literal,
                IPv6_address_literal,
                General_address_literal,
            )),
            std::str::from_utf8,
        ),
        tag(b"]"),
    );

    let (remaining, parsed) = parser(input)?;

    Ok((remaining, parsed))
}

/// Mailbox = Local-part "@" ( Domain / address-literal )
pub fn Mailbox(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((Local_part, tag(b"@"), alt((Domain, address_literal))));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Local-part = Dot-string / Quoted-string
///               ; MAY be case-sensitive
pub fn Local_part(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = alt((Dot_string, Quoted_string));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Dot-string = Atom *("."  Atom)
pub fn Dot_string(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = tuple((Atom, many0(tuple((tag(b"."), Atom)))));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Atom = 1*atext
pub fn Atom(input: &[u8]) -> IResult<&[u8], &[u8]> {
    take_while1(is_atext)(input)
}

/// Quoted-string = DQUOTE *QcontentSMTP DQUOTE
pub fn Quoted_string(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = delimited(DQUOTE, many0(QcontentSMTP), DQUOTE);

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// QcontentSMTP = qtextSMTP / quoted-pairSMTP
pub fn QcontentSMTP(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = alt((take_while_m_n(1, 1, is_qtextSMTP), quoted_pairSMTP));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Backslash followed by any ASCII graphic (including itself) or SPace
///
/// quoted-pairSMTP = %d92 %d32-126
pub fn quoted_pairSMTP(input: &[u8]) -> IResult<&[u8], &[u8]> {
    fn is_ascii_bs_or_sp(byte: u8) -> bool {
        matches!(byte, 32..=126)
    }

    let parser = tuple((tag("\\"), take_while_m_n(1, 1, is_ascii_bs_or_sp)));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

/// Within a quoted string, any ASCII graphic or space is permitted
/// without blackslash-quoting except double-quote and the backslash itself.
///
/// qtextSMTP = %d32-33 / %d35-91 / %d93-126
pub fn is_qtextSMTP(byte: u8) -> bool {
    matches!(byte, 32..=33 | 35..=91 | 93..=126)
}

/// String = Atom / Quoted-string
pub fn String(input: &[u8]) -> IResult<&[u8], &[u8]> {
    let parser = alt((Atom, Quoted_string));

    let (remaining, parsed) = recognize(parser)(input)?;

    Ok((remaining, parsed))
}

#[cfg(test)]
mod test {
    use super::{ehlo, helo, mail, sub_domain};
    use crate::types::Command;

    #[test]
    fn test_subdomain() {
        let (rem, parsed) = sub_domain(b"example???").unwrap();
        assert_eq!(parsed, b"example");
        assert_eq!(rem, b"???");
    }

    #[test]
    fn test_ehlo() {
        let (rem, parsed) = ehlo(b"EHLO [123.123.123.123]\r\n???").unwrap();
        assert_eq!(
            parsed,
            Command::Ehlo {
                fqdn_or_address_literal: b"123.123.123.123".to_vec()
            }
        );
        assert_eq!(rem, b"???");
    }

    #[test]
    fn test_helo() {
        let (rem, parsed) = helo(b"HELO example.com\r\n???").unwrap();
        assert_eq!(
            parsed,
            Command::Helo {
                fqdn_or_address_literal: b"example.com".to_vec()
            }
        );
        assert_eq!(rem, b"???");
    }

    #[test]
    fn test_mail() {
        let (rem, parsed) = mail(b"MAIL FROM:<userx@y.foo.org>\r\n???").unwrap();
        assert_eq!(
            parsed,
            Command::Mail {
                reverse_path: b"<userx@y.foo.org>".to_vec(),
                parameters: None
            }
        );
        assert_eq!(rem, b"???");
    }
}