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
use std::str::from_utf8;

use abnf_core::streaming::{CRLF_relaxed as CRLF, SP};
use nom::{
    branch::alt,
    bytes::streaming::{tag, tag_no_case, take_while1},
    combinator::{map, map_res, opt, value},
    multi::{many1, separated_list1},
    sequence::{delimited, preceded, terminated, tuple},
    IResult,
};

use crate::{
    parse::{
        algorithm, auth_type,
        core::{atom, base64, charset, is_text_char, nz_number, tag_imap, text},
        flag::flag_perm,
        mailbox::mailbox_data,
        message::message_data,
    },
    types::{
        core::txt,
        response::{Capability, Code, Continuation, Data, Response, Status},
    },
};

// ----- greeting -----

/// greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
pub fn greeting(input: &[u8]) -> IResult<&[u8], Response> {
    let mut parser = tuple((
        tag(b"*"),
        SP,
        alt((
            map(
                resp_cond_auth,
                |(raw_status, (maybe_code, comment))| match raw_status.to_lowercase().as_ref() {
                    "ok" => Status::Ok {
                        tag: None,
                        code: maybe_code,
                        text: comment.to_owned(),
                    },
                    "preauth" => Status::PreAuth {
                        code: maybe_code,
                        text: comment.to_owned(),
                    },
                    _ => unreachable!(),
                },
            ),
            map(resp_cond_bye, |(maybe_code, comment)| Status::Bye {
                code: maybe_code,
                text: comment.to_owned(),
            }),
        )),
        CRLF,
    ));

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

    Ok((remaining, Response::Status(status)))
}

/// Authentication condition
///
/// resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
fn resp_cond_auth(input: &[u8]) -> IResult<&[u8], (&str, (Option<Code>, txt))> {
    let mut parser = tuple((
        map_res(
            alt((tag_no_case(b"OK"), tag_no_case(b"PREAUTH"))),
            from_utf8, // FIXME(perf): use from_utf8_unchecked
        ),
        SP,
        resp_text,
    ));

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

    Ok((remaining, (raw_status, resp_text)))
}

/// resp-text = ["[" resp-text-code "]" SP] text
fn resp_text(input: &[u8]) -> IResult<&[u8], (Option<Code>, txt)> {
    tuple((
        opt(terminated(
            delimited(tag(b"["), resp_text_code, tag(b"]")),
            SP,
        )),
        text,
    ))(input)
}

/// ; errata id: 261
/// resp-text-code = "ALERT" /
///                  "BADCHARSET" [SP "(" charset *(SP charset) ")" ] /
///                  capability-data /
///                  "PARSE" /
///                  "PERMANENTFLAGS" SP "(" [flag-perm *(SP flag-perm)] ")" /
///                  "READ-ONLY" /
///                  "READ-WRITE" /
///                  "TRYCREATE" /
///                  "UIDNEXT" SP nz-number /
///                  "UIDVALIDITY" SP nz-number /
///                  "UNSEEN" SP nz-number /
///                  "COMPRESSIONACTIVE" ; RFC 4978
///                  atom [SP 1*<any TEXT-CHAR except "]">]
fn resp_text_code(input: &[u8]) -> IResult<&[u8], Code> {
    alt((
        value(Code::Alert, tag_no_case(b"ALERT")),
        map(
            tuple((
                tag_no_case(b"BADCHARSET"),
                opt(preceded(
                    SP,
                    delimited(tag(b"("), separated_list1(SP, charset), tag(b")")),
                )),
            )),
            |(_, maybe_charsets)| Code::BadCharset(maybe_charsets.unwrap_or_default()),
        ),
        map(capability_data, Code::Capability),
        value(Code::Parse, tag_no_case(b"PARSE")),
        map(
            tuple((
                tag_no_case(b"PERMANENTFLAGS"),
                SP,
                delimited(
                    tag(b"("),
                    map(opt(separated_list1(SP, flag_perm)), |maybe_flags| {
                        maybe_flags.unwrap_or_default()
                    }),
                    tag(b")"),
                ),
            )),
            |(_, _, flags)| Code::PermanentFlags(flags),
        ),
        value(Code::ReadOnly, tag_no_case(b"READ-ONLY")),
        value(Code::ReadWrite, tag_no_case(b"READ-WRITE")),
        value(Code::TryCreate, tag_no_case(b"TRYCREATE")),
        map(
            tuple((tag_no_case(b"UIDNEXT"), SP, nz_number)),
            |(_, _, num)| Code::UidNext(num),
        ),
        map(
            tuple((tag_no_case(b"UIDVALIDITY"), SP, nz_number)),
            |(_, _, num)| Code::UidValidity(num),
        ),
        map(
            tuple((tag_no_case(b"UNSEEN"), SP, nz_number)),
            |(_, _, num)| Code::Unseen(num),
        ),
        value(Code::CompressionActive, tag_no_case(b"COMPRESSIONACTIVE")),
        map(
            tuple((
                atom,
                opt(preceded(
                    SP,
                    map_res(
                        take_while1(|byte| is_text_char(byte) && byte != b'"'),
                        from_utf8, // FIXME(perf): use from_utf8_unchecked
                    ),
                )),
            )),
            |(atom, maybe_params)| {
                Code::Other(atom.to_owned(), maybe_params.map(|inner| inner.to_owned()))
            },
        ),
    ))(input)
}

/// capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1" *(SP capability)
///
/// Servers MUST implement the STARTTLS, AUTH=PLAIN, and LOGINDISABLED capabilities
/// Servers which offer RFC 1730 compatibility MUST list "IMAP4" as the first capability.
fn capability_data(input: &[u8]) -> IResult<&[u8], Vec<Capability>> {
    let mut parser = tuple((
        tag_no_case("CAPABILITY"),
        SP,
        separated_list1(SP, capability),
    ));

    let (rem, (_, _, caps)) = parser(input)?;

    Ok((rem, caps))
}

/// capability = ("AUTH=" auth-type) /
///              "COMPRESS=" algorithm / ; RFC 4978
///              atom
pub fn capability(input: &[u8]) -> IResult<&[u8], Capability> {
    alt((
        map(
            tuple((tag_no_case(b"AUTH="), auth_type)),
            |(_, mechanism)| Capability::Auth(mechanism),
        ),
        map(
            tuple((tag_no_case(b"COMPRESS="), algorithm)),
            |(_, algorithm)| Capability::Compress { algorithm },
        ),
        map(atom, |atom| {
            match atom.to_lowercase().as_ref() {
                "imap4rev1" => Capability::Imap4Rev1,
                "logindisabled" => Capability::LoginDisabled,
                "starttls" => Capability::StartTls,
                // RFC 2177 IMAP4 IDLE command
                "idle" => Capability::Idle,
                // RFC 2193 IMAP4 Mailbox Referrals
                "mailbox-referrals" => Capability::MailboxReferrals,
                // RFC 2221 IMAP4 Login Referrals
                "login-referrals" => Capability::LoginReferrals,
                // RFC 4959 IMAP Extension for SASL Initial Client Response
                "sasl-ir" => Capability::SaslIr,
                // RFC 5161 The IMAP ENABLE Extension
                "enable" => Capability::Enable,
                _ => Capability::Other(atom.to_owned()),
            }
        }),
    ))(input)
}

/// resp-cond-bye = "BYE" SP resp-text
fn resp_cond_bye(input: &[u8]) -> IResult<&[u8], (Option<Code>, txt)> {
    let mut parser = tuple((tag_no_case(b"BYE"), SP, resp_text));

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

    Ok((remaining, resp_text))
}

// ----- response -----

/// response = *(continue-req / response-data) response-done
pub fn response(input: &[u8]) -> IResult<&[u8], Response> {
    // Divert from standard here for better usability.
    // response_data already contains the bye response, thus
    // response_done could also be response_tagged.
    //
    // However, I will keep it as it is for now.
    alt((
        map(continue_req, Response::Continuation),
        response_data,
        map(response_done, Response::Status),
    ))(input)
}

/// continue-req = "+" SP (resp-text / base64) CRLF
fn continue_req(input: &[u8]) -> IResult<&[u8], Continuation> {
    let mut parser = tuple((
        tag(b"+"),
        SP,
        alt((
            map(resp_text, |(code, text)| Continuation::Basic {
                code,
                text: text.to_owned(),
            }),
            map(base64, |str| Continuation::Base64(str.to_owned())),
        )),
        CRLF,
    ));

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

    Ok((remaining, continuation))
}

/// response-data = "*" SP (
///                 resp-cond-state /
///                 resp-cond-bye /
///                 mailbox-data /
///                 message-data /
///                 capability-data
///                 ) CRLF
fn response_data(input: &[u8]) -> IResult<&[u8], Response> {
    let mut parser = tuple((
        tag(b"*"),
        SP,
        alt((
            map(resp_cond_state, |(raw_status, code, text)| {
                let status = match raw_status.to_lowercase().as_ref() {
                    "ok" => Status::Ok {
                        tag: None,
                        code,
                        text: text.to_owned(),
                    },
                    "no" => Status::No {
                        tag: None,
                        code,
                        text: text.to_owned(),
                    },
                    "bad" => Status::Bad {
                        tag: None,
                        code,
                        text: text.to_owned(),
                    },
                    _ => unreachable!(),
                };

                Response::Status(status)
            }),
            map(resp_cond_bye, |(code, text)| {
                Response::Status({
                    Status::Bye {
                        code,
                        text: text.to_owned(),
                    }
                })
            }),
            map(mailbox_data, Response::Data),
            map(message_data, Response::Data),
            map(capability_data, |caps| {
                Response::Data(Data::Capability(caps))
            }),
            // RFC 5161
            // response-data =/ "*" SP enable-data CRLF
            map(enable_data, Response::Data),
        )),
        CRLF,
    ));

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

    Ok((remaining, response))
}

/// Status condition
///
/// resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
fn resp_cond_state(input: &[u8]) -> IResult<&[u8], (&str, Option<Code>, txt)> {
    let mut parser = tuple((
        alt((tag_no_case("OK"), tag_no_case("NO"), tag_no_case("BAD"))),
        SP,
        resp_text,
    ));

    let (remaining, (raw_status, _, (maybe_code, text))) = parser(input)?;

    Ok((
        remaining,
        (from_utf8(raw_status).expect("can't fail"), maybe_code, text), // FIXME(perf): use from_utf8_unchecked
    ))
}

/// response-done = response-tagged / response-fatal
fn response_done(input: &[u8]) -> IResult<&[u8], Status> {
    alt((response_tagged, response_fatal))(input)
}

/// response-tagged = tag SP resp-cond-state CRLF
fn response_tagged(input: &[u8]) -> IResult<&[u8], Status> {
    let mut parser = tuple((tag_imap, SP, resp_cond_state, CRLF));

    let (remaining, (tag, _, (raw_status, maybe_code, text), _)) = parser(input)?;

    let status = match raw_status.to_lowercase().as_ref() {
        "ok" => Status::Ok {
            tag: Some(tag),
            code: maybe_code,
            text: text.to_owned(),
        },
        "no" => Status::No {
            tag: Some(tag),
            code: maybe_code,
            text: text.to_owned(),
        },
        "bad" => Status::Bad {
            tag: Some(tag),
            code: maybe_code,
            text: text.to_owned(),
        },
        _ => unreachable!(),
    };

    Ok((remaining, status))
}

/// Server closes connection immediately
///
/// response-fatal = "*" SP resp-cond-bye CRLF
fn response_fatal(input: &[u8]) -> IResult<&[u8], Status> {
    let mut parser = tuple((tag(b"*"), SP, resp_cond_bye, CRLF));

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

    Ok((remaining, {
        Status::Bye {
            code: maybe_code,
            text: text.to_owned(),
        }
    }))
}

// ----- EXTENSIONS -----

/// enable-data = "ENABLED" *(SP capability)
fn enable_data(input: &[u8]) -> IResult<&[u8], Data> {
    let mut parser = tuple((tag_no_case(b"ENABLED"), many1(preceded(SP, capability))));

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

    Ok((remaining, { Data::Enabled { capabilities } }))
}