summaryrefslogtreecommitdiff
path: root/src/rfc822.rs
blob: a8fa5c3e34c14dac2880381eca1415df9f599db0 (plain)
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
use chrono::DateTime;
use maildir::MailEntryError;
use mailparse::{
    addrparse_header, body::Body, dateparse, DispositionType, MailParseError, ParsedMail,
};

use crate::de_jmhoffmann_jwebmail_mailstorage::MIMEHeader_content_dispo as CD;
use crate::de_jmhoffmann_jwebmail_mailstorage::*;

fn parse_mail_addrs(
    inp: &mailparse::MailHeader,
) -> std::result::Result<Vec<MailAddr>, MailParseError> {
    let mut mal = addrparse_header(inp)?;

    Ok(mal
        .drain(..)
        .flat_map(|mail_addr| match mail_addr {
            mailparse::MailAddr::Group(mut g) => g
                .addrs
                .drain(..)
                .map(|s| MailAddr {
                    name: Some(s.display_name.unwrap_or_default()),
                    address: s.addr,
                })
                .collect(),
            mailparse::MailAddr::Single(s) => {
                let addr = MailAddr {
                    name: Some(s.display_name.unwrap_or_default()),
                    address: s.addr,
                };
                vec![addr]
            }
        })
        .collect())
}

// ----------------

fn get_received(me: &mut maildir::MailEntry) -> i64 {
    me.received().unwrap_or_else(|_| {
        let mut id = me.id();
        id = &id[..id.find('.').unwrap()];
        id.parse().unwrap_or_default()
    })
}

pub fn me_to_lmh(
    mut me: maildir::MailEntry,
) -> std::result::Result<ListMailHeader, MailEntryError> {
    let lmh = ListMailHeader {
        byte_size: me.path().metadata()?.len() as i64,
        unread: !me.is_seen(),
        rec_date: DateTime::from_timestamp(get_received(&mut me), 0)
            .unwrap()
            .to_rfc3339(),
        mid: me.id().to_owned(),
        header: parse_mail_header(&me.parsed()?)?,
    };

    Ok(lmh)
}

pub fn parse_mail_content(v: &ParsedMail) -> MIMEHeader {
    let mut val = v.ctype.mimetype.clone();
    if let Some(i) = val.find(';') {
        val.truncate(i);
    }
    let j = val.find('/').unwrap();
    let subtype = val.split_off(j + 1);
    val.pop();
    let maintype = val;

    let mut file_name = None;

    let cd = match v.get_content_disposition().disposition {
        DispositionType::Inline => CD::inline,
        DispositionType::Attachment => {
            if let Some(fname) = v.get_content_disposition().params.remove("filename") {
                file_name = Some(fname);
            }
            CD::attachment
        }
        _ => CD::none,
    };

    for h in &v.headers {
        let mut key = h.get_key();
        let val = h.get_value();

        key.make_ascii_lowercase();

        if key == "filename" {
            file_name = Some(val);
        }
    }

    MIMEHeader {
        mime_type: MIMEHeader_mime_type {
            main_type: maintype,
            sub_type: subtype,
        },
        content_dispo: cd,
        file_name,
    }
}

fn parse_mail_header(pm: &ParsedMail) -> std::result::Result<MailHeader, MailParseError> {
    let v = &pm.headers;

    let mut val = pm.ctype.mimetype.clone();
    if let Some(i) = val.find(';') {
        val.truncate(i);
    }
    let j = val.find('/').unwrap();
    let sub_type = val.split_off(j + 1);
    val.pop();
    let main_type = val;

    let mut file_name = None;
    let mut content_dispo = CD::none;
    let mut cc = vec![];
    let mut bcc = vec![];
    let mut comments = vec![];
    let mut keywords = vec![];
    let mut reply_to = vec![];
    let mut written_from = vec![];
    let mut send_to = vec![];
    let mut subject = String::new();
    let mut sender = None;
    let mut send_date = String::new();

    let mut key = String::new();

    for y in v {
        key.push_str(&y.get_key_ref());
        let mut val = y.get_value();

        key.make_ascii_lowercase();

        match key.as_str() {
            "date" => {
                send_date = DateTime::from_timestamp(dateparse(&val)?, 0)
                    .unwrap()
                    .to_rfc3339()
            }
            "from" => {
                if !written_from.is_empty() {
                    const FROM_MULTIPLE_TIMES_ERROR: &str = "from already set";
                    return Err(MailParseError::Generic(FROM_MULTIPLE_TIMES_ERROR));
                }
                written_from = parse_mail_addrs(y)?
            }
            "sender" => sender = parse_mail_addrs(y)?.drain(0..1).next(),
            "reply-to" => reply_to = parse_mail_addrs(y)?,
            "to" => send_to = parse_mail_addrs(y)?,
            "cc" => cc = parse_mail_addrs(y)?,
            "bcc" => bcc = parse_mail_addrs(y)?,
            "subject" => {
                subject = val;
            }
            "comments" => {
                comments.push(val);
            }
            "keywords" => {
                keywords.push(val);
            }
            "mime-version" => {
                strip_comments(&mut val);
                if val.trim() != "1.0" {
                    const UNKNOWN_MIME_VERSION_ERROR: &str = "unknown mime version";
                    return Err(MailParseError::Generic(UNKNOWN_MIME_VERSION_ERROR));
                }
            }
            "content-disposition" => {
                let cd = val.to_ascii_lowercase();
                match cd.as_ref() {
                    "inline" => content_dispo = CD::inline,
                    "attachment" => content_dispo = CD::attachment,
                    _ => {}
                };
            }
            "filename" => {
                file_name = Some(val);
            }
            _ => {}
        };

        key.clear();
    }
    Ok(MailHeader {
        written_from,
        sender,
        send_to,
        cc,
        bcc,
        reply_to,
        subject,
        send_date,
        keywords,
        comments,
        mime: MIMEHeader {
            mime_type: MIMEHeader_mime_type {
                main_type,
                sub_type,
            },
            content_dispo,
            file_name,
        },
    })
}

fn parse_mail_body(pm: &ParsedMail) -> std::result::Result<MailBody, MailParseError> {
    let body = if pm.ctype.mimetype.starts_with("message/") {
        MailBody {
            mail: Some(Box::new(parsed_mail_to_mail(mailparse::parse_mail(
                pm.get_body()?.as_ref(),
            )?)?)),
            discrete: None,
            multipart: None,
        }
    } else if pm.subparts.is_empty() && pm.ctype.mimetype.starts_with("text/") {
        MailBody {
            discrete: Some(pm.get_body()?),
            multipart: None,
            mail: None,
        }
    } else if pm.subparts.is_empty() {
        MailBody {
            discrete: Some(match pm.get_body_encoded() {
                Body::Base64(eb) => {
                    let db = eb.get_raw();
                    if db.len() < 512 * 1024 {
                        String::from_utf8_lossy(db).into_owned()
                    } else {
                        String::new()
                    }
                }
                Body::SevenBit(eb) => eb.get_as_string()?,
                Body::QuotedPrintable(eb) => eb.get_decoded_as_string()?,
                _ => todo!(),
            }),
            multipart: None,
            mail: None,
        }
    } else {
        let mp = Multipart {
            parts: pm
                .subparts
                .iter()
                .map(|part| -> std::result::Result<MIMEPart, MailParseError> {
                    Ok(MIMEPart {
                        mime_header: parse_mail_content(part),
                        body: parse_mail_body(part)?,
                    })
                })
                .filter_map(|p| p.ok())
                .collect(),
            preamble: None,
            epilogue: None,
        };
        MailBody {
            multipart: Some(mp),
            discrete: None,
            mail: None,
        }
    };
    Ok(body)
}

enum FindMatchParen {
    Open,
    Close,
}

impl FindMatchParen {
    fn value(&self) -> char {
        match self {
            FindMatchParen::Open => '(',
            FindMatchParen::Close => ')',
        }
    }

    fn len(&self) -> usize {
        1
    }

    fn of_char(c: char) -> Option<Self> {
        match c {
            '(' => Some(FindMatchParen::Open),
            ')' => Some(FindMatchParen::Close),
            _ => None,
        }
    }
}

fn find_in_header(s: &str, f: FindMatchParen) -> Option<usize> {
    let mut in_q = false;
    let mut q_pair = false;
    let mut open_p = 0;

    for (i, c) in s.char_indices() {
        if q_pair {
            q_pair = false;
            continue;
        }
        match c {
            '\\' => {
                q_pair = true;
            }
            '"' => {
                in_q = !in_q;
            }
            _ if !in_q => {
                if open_p == 0 {
                    if c == f.value() {
                        return Some(i);
                    }
                    if c == FindMatchParen::Open.value() {
                        open_p += 1;
                    }
                } else {
                    match FindMatchParen::of_char(c) {
                        Some(FindMatchParen::Open) => open_p += 1,
                        Some(FindMatchParen::Close) => open_p -= 1,
                        None => {}
                    }
                }
            }
            _ => {}
        };
    }
    None
}

fn find_pair(offset: usize, s: &str) -> Option<std::ops::Range<usize>> {
    if let Some(open) = find_in_header(s, FindMatchParen::Open) {
        if let Some(mut close) = find_in_header(
            &s[open + FindMatchParen::Open.len()..],
            FindMatchParen::Close,
        ) {
            close += open + FindMatchParen::Open.len();
            Some(offset + open..offset + close + FindMatchParen::Close.len())
        } else {
            find_pair(
                offset + open + FindMatchParen::Open.len(),
                &s[open + FindMatchParen::Open.len()..],
            )
        }
    } else {
        None
    }
}

fn strip_comments(s: &mut String) {
    let mut off = 0;

    while let Some(r) = find_pair(off, &s[off..]) {
        s.drain(r.clone());
        off = r.start;
    }
}

pub fn parsed_mail_to_mail(pm: ParsedMail) -> std::result::Result<Mail, MailParseError> {
    Ok(Mail {
        head: parse_mail_header(&pm)?,
        body: parse_mail_body(&pm)?,
    })
}