Skip to main content

deltachat/
mimeparser.rs

1//! # MIME message parsing module.
2
3use std::cmp::min;
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::path::Path;
6use std::str;
7use std::str::FromStr;
8
9use anyhow::{Context as _, Result, bail, ensure};
10use deltachat_contact_tools::{addr_cmp, addr_normalize, sanitize_bidi_characters};
11use deltachat_derive::{FromSql, ToSql};
12use format_flowed::unformat_flowed;
13use mailparse::{DispositionType, MailHeader, MailHeaderMap, SingleInfo, addrparse_header};
14use mime::Mime;
15
16use crate::aheader::Aheader;
17use crate::blob::BlobObject;
18use crate::chat::{Chat, ChatId};
19use crate::config::Config;
20use crate::constants;
21use crate::contact::{ContactId, import_public_key};
22use crate::context::Context;
23use crate::decrypt::{self, validate_detached_signature};
24use crate::dehtml::dehtml;
25use crate::download::PostMsgMetadata;
26use crate::events::EventType;
27use crate::headerdef::{HeaderDef, HeaderDefMap};
28use crate::key::{self, DcKey, Fingerprint, SignedPublicKey};
29use crate::log::warn;
30use crate::message::{self, Message, MsgId, Viewtype, get_vcard_summary, set_msg_failed};
31use crate::param::{Param, Params};
32use crate::simplify::{SimplifiedText, simplify};
33use crate::sync::SyncItems;
34use crate::tools::{get_filemeta, parse_receive_headers, time, truncate_msg_text, validate_id};
35use crate::{chatlist_events, location, tools};
36
37/// Public key extracted from `Autocrypt-Gossip`
38/// header with associated information.
39#[derive(Debug)]
40pub struct GossipedKey {
41    /// Public key extracted from `keydata` attribute.
42    pub public_key: SignedPublicKey,
43
44    /// True if `Autocrypt-Gossip` has a `_verified` attribute.
45    pub verified: bool,
46}
47
48/// A parsed MIME message.
49///
50/// This represents the relevant information of a parsed MIME message
51/// for deltachat.  The original MIME message might have had more
52/// information but this representation should contain everything
53/// needed for deltachat's purposes.
54///
55/// It is created by parsing the raw data of an actual MIME message
56/// using the [MimeMessage::from_bytes] constructor.
57#[derive(Debug)]
58pub(crate) struct MimeMessage {
59    /// Parsed MIME parts.
60    pub parts: Vec<Part>,
61
62    /// Message headers.
63    headers: HashMap<String, String>,
64
65    #[cfg(test)]
66    /// Names of removed (ignored) headers. Used by `header_exists()` needed for tests.
67    headers_removed: HashSet<String>,
68
69    /// List of addresses from the `To` and `Cc` headers.
70    ///
71    /// Addresses are normalized and lowercase.
72    pub recipients: Vec<SingleInfo>,
73
74    /// List of addresses from the `Chat-Group-Past-Members` header.
75    pub past_members: Vec<SingleInfo>,
76
77    /// `From:` address.
78    pub from: SingleInfo,
79
80    /// Whether the message is incoming or outgoing (self-sent).
81    pub incoming: bool,
82    /// The List-Post address is only set for mailing lists. Users can send
83    /// messages to this address to post them to the list.
84    pub list_post: Option<String>,
85    pub chat_disposition_notification_to: Option<SingleInfo>,
86
87    /// Decryption error if decryption of the message has failed.
88    pub decryption_error: Option<String>,
89
90    /// Valid signature fingerprint if a message is an
91    /// Autocrypt encrypted and signed message and corresponding intended recipient fingerprints
92    /// (<https://www.rfc-editor.org/rfc/rfc9580.html#name-intended-recipient-fingerpr>) if any.
93    ///
94    /// If a message is not encrypted or the signature is not valid,
95    /// this is `None`.
96    pub signature: Option<(Fingerprint, HashSet<Fingerprint>)>,
97
98    /// The addresses for which there was a gossip header
99    /// and their respective gossiped keys.
100    pub gossiped_keys: BTreeMap<String, GossipedKey>,
101
102    /// Fingerprint of the key in the Autocrypt header.
103    ///
104    /// It is not verified that the sender can use this key.
105    pub autocrypt_fingerprint: Option<String>,
106
107    /// True if the message is a forwarded message.
108    pub is_forwarded: bool,
109    pub is_system_message: SystemMessage,
110    pub location_kml: Option<location::Kml>,
111    pub message_kml: Option<location::Kml>,
112    pub(crate) sync_items: Option<SyncItems>,
113    pub(crate) webxdc_status_update: Option<String>,
114    pub(crate) user_avatar: Option<AvatarAction>,
115    pub(crate) group_avatar: Option<AvatarAction>,
116    pub(crate) mdn_reports: Vec<Report>,
117    pub(crate) delivery_report: Option<DeliveryReport>,
118
119    /// Standard USENET signature, if any.
120    ///
121    /// `None` means no text part was received, empty string means a text part without a footer is
122    /// received.
123    pub(crate) footer: Option<String>,
124
125    /// If set, this is a modified MIME message; clients should offer a way to view the original
126    /// MIME message in this case.
127    pub is_mime_modified: bool,
128
129    /// Decrypted raw MIME structure.
130    pub decoded_data: Vec<u8>,
131
132    /// Hop info for debugging.
133    pub(crate) hop_info: String,
134
135    /// Whether the message is auto-generated.
136    ///
137    /// If chat message (with `Chat-Version` header) is auto-generated,
138    /// the contact sending this should be marked as bot.
139    ///
140    /// If non-chat message is auto-generated,
141    /// it could be a holiday notice auto-reply,
142    /// in which case the message should be marked as bot-generated,
143    /// but the contact should not be.
144    pub(crate) is_bot: Option<bool>,
145
146    /// When the message was received, in secs since epoch.
147    pub(crate) timestamp_rcvd: i64,
148    /// Sender timestamp in secs since epoch. Allowed to be in the future due to unsynchronized
149    /// clocks, but not too much.
150    pub(crate) timestamp_sent: i64,
151
152    pub(crate) pre_message: PreMessageMode,
153}
154
155#[derive(Debug, Clone, PartialEq)]
156pub(crate) enum PreMessageMode {
157    /// This is a post-message.
158    /// It replaces its pre-message attachment if it exists already,
159    /// and if the pre-message does not exist, it is treated as a normal message.
160    Post,
161    /// This is a Pre-Message,
162    /// it adds a message preview for a Post-Message
163    /// and it is ignored if the Post-Message was downloaded already
164    Pre {
165        post_msg_rfc724_mid: String,
166        metadata: Option<PostMsgMetadata>,
167    },
168    /// Atomic ("normal") message.
169    None,
170}
171
172#[derive(Debug, PartialEq)]
173pub(crate) enum AvatarAction {
174    Delete,
175    Change(String),
176}
177
178/// System message type.
179#[derive(
180    Debug, Default, Display, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive, ToSql, FromSql,
181)]
182#[repr(u32)]
183pub enum SystemMessage {
184    /// Unknown type of system message.
185    #[default]
186    Unknown = 0,
187
188    /// Group or broadcast channel name changed.
189    GroupNameChanged = 2,
190
191    /// Group or broadcast channel avatar changed.
192    GroupImageChanged = 3,
193
194    /// Member was added to the group.
195    MemberAddedToGroup = 4,
196
197    /// Member was removed from the group.
198    MemberRemovedFromGroup = 5,
199
200    /// Autocrypt Setup Message.
201    ///
202    /// Deprecated as of 2026-03-15, such messages should not be created
203    /// but may exist in the database.
204    AutocryptSetupMessage = 6,
205
206    /// Secure-join message.
207    SecurejoinMessage = 7,
208
209    /// Location streaming is enabled.
210    LocationStreamingEnabled = 8,
211
212    /// Location-only message.
213    LocationOnly = 9,
214
215    /// Chat ephemeral message timer is changed.
216    EphemeralTimerChanged = 10,
217
218    /// "Messages are end-to-end encrypted."
219    ChatProtectionEnabled = 11,
220
221    /// "%1$s sent a message from another device.", deprecated 2025-07
222    ChatProtectionDisabled = 12,
223
224    /// Message can't be sent because of `Invalid unencrypted mail to <>`
225    /// which is sent by chatmail servers.
226    InvalidUnencryptedMail = 13,
227
228    /// 1:1 chats info message telling that SecureJoin has started and the user should wait for it
229    /// to complete.
230    SecurejoinWait = 14,
231
232    /// 1:1 chats info message telling that SecureJoin is still running, but the user may already
233    /// send messages.
234    SecurejoinWaitTimeout = 15,
235
236    /// Self-sent-message that contains only json used for multi-device-sync;
237    /// if possible, we attach that to other messages as for locations.
238    MultiDeviceSync = 20,
239
240    /// Sync message that contains a json payload
241    /// sent to the other webxdc instances
242    /// These messages are not shown in the chat.
243    WebxdcStatusUpdate = 30,
244
245    /// Webxdc info added with `info` set in `send_webxdc_status_update()`.
246    WebxdcInfoMessage = 32,
247
248    /// This message contains a users iroh node address.
249    IrohNodeAddr = 40,
250
251    /// "Messages are end-to-end encrypted."
252    ChatE2ee = 50,
253
254    /// Message indicating that a call was accepted.
255    CallAccepted = 66,
256
257    /// Message indicating that a call was ended.
258    CallEnded = 67,
259
260    /// Group or broadcast channel description changed.
261    GroupDescriptionChanged = 70,
262}
263
264impl MimeMessage {
265    /// Parse a mime message.
266    ///
267    /// This method has some side-effects,
268    /// such as saving blobs and saving found public keys to the database.
269    pub(crate) async fn from_bytes(context: &Context, body: &[u8]) -> Result<Self> {
270        let mail = mailparse::parse_mail(body)?;
271
272        let timestamp_rcvd = time();
273        let mut timestamp_sent =
274            Self::get_timestamp_sent(&mail.headers, timestamp_rcvd, timestamp_rcvd);
275        let hop_info = parse_receive_headers(&mail.get_headers());
276
277        let mut headers = Default::default();
278        let mut headers_removed = HashSet::<String>::new();
279        let mut recipients = Default::default();
280        let mut past_members = Default::default();
281        let mut from = Default::default();
282        let mut list_post = Default::default();
283        let mut chat_disposition_notification_to = None;
284
285        // Parse IMF headers.
286        MimeMessage::merge_headers(
287            context,
288            &mut headers,
289            &mut headers_removed,
290            &mut recipients,
291            &mut past_members,
292            &mut from,
293            &mut list_post,
294            &mut chat_disposition_notification_to,
295            &mail,
296        );
297        headers_removed.extend(
298            headers
299                .extract_if(|k, _v| is_hidden(k))
300                .map(|(k, _v)| k.to_string()),
301        );
302
303        // Parse hidden headers.
304        let mimetype = mail.ctype.mimetype.parse::<Mime>()?;
305        if mimetype.type_() == mime::MULTIPART
306            && mimetype.subtype().as_str() == "mixed"
307            && let Some(part) = mail.subparts.first()
308        {
309            for field in &part.headers {
310                let key = field.get_key().to_lowercase();
311                if !headers.contains_key(&key) && is_hidden(&key) || key == "message-id" {
312                    headers.insert(key.to_string(), field.get_value());
313                }
314            }
315        }
316
317        // Overwrite Message-ID with X-Microsoft-Original-Message-ID.
318        // However if we later find Message-ID in the protected part,
319        // it will overwrite both.
320        if let Some(microsoft_message_id) = remove_header(
321            &mut headers,
322            HeaderDef::XMicrosoftOriginalMessageId.get_headername(),
323            &mut headers_removed,
324        ) {
325            headers.insert(
326                HeaderDef::MessageId.get_headername().to_string(),
327                microsoft_message_id,
328            );
329        }
330
331        // Remove headers that are allowed _only_ in the encrypted+signed part
332        let encrypted = false;
333        Self::remove_secured_headers(&mut headers, &mut headers_removed, encrypted);
334
335        let mut from = from.context("No from in message")?;
336
337        let mut gossiped_keys = Default::default();
338
339        let from_is_not_self_addr = !context.is_self_addr(&from.addr).await?;
340
341        let mut aheader_values = mail.headers.get_all_values(HeaderDef::Autocrypt.into());
342
343        let mut pre_message = if mail
344            .headers
345            .get_header_value(HeaderDef::ChatIsPostMessage)
346            .is_some()
347        {
348            PreMessageMode::Post
349        } else {
350            PreMessageMode::None
351        };
352
353        let mail_raw; // Memory location for a possible decrypted message.
354        let decrypted_msg; // Decrypted signed OpenPGP message.
355        let expected_sender_fingerprint: Option<String>;
356
357        let (mail, is_encrypted) = match Box::pin(decrypt::decrypt(context, &mail)).await {
358            Ok(Some((mut msg, expected_sender_fp))) => {
359                mail_raw = msg.as_data_vec().unwrap_or_default();
360
361                let decrypted_mail = mailparse::parse_mail(&mail_raw)?;
362                if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {
363                    info!(
364                        context,
365                        "decrypted message mime-body:\n{}",
366                        String::from_utf8_lossy(&mail_raw),
367                    );
368                }
369
370                decrypted_msg = Some(msg);
371
372                timestamp_sent = Self::get_timestamp_sent(
373                    &decrypted_mail.headers,
374                    timestamp_sent,
375                    timestamp_rcvd,
376                );
377
378                let protected_aheader_values = decrypted_mail
379                    .headers
380                    .get_all_values(HeaderDef::Autocrypt.into());
381                if !protected_aheader_values.is_empty() {
382                    aheader_values = protected_aheader_values;
383                }
384
385                expected_sender_fingerprint = expected_sender_fp;
386                (Ok(decrypted_mail), true)
387            }
388            Ok(None) => {
389                mail_raw = Vec::new();
390                decrypted_msg = None;
391                expected_sender_fingerprint = None;
392                (Ok(mail), false)
393            }
394            Err(err) => {
395                mail_raw = Vec::new();
396                decrypted_msg = None;
397                expected_sender_fingerprint = None;
398                warn!(context, "decryption failed: {:#}", err);
399                (Err(err), false)
400            }
401        };
402
403        let mut autocrypt_header = None;
404        if from_is_not_self_addr {
405            // See `get_all_addresses_from_header()` for why we take the last valid header.
406            for val in aheader_values.iter().rev() {
407                autocrypt_header = match Aheader::from_str(val) {
408                    Ok(header) if addr_cmp(&header.addr, &from.addr) => Some(header),
409                    Ok(header) => {
410                        warn!(
411                            context,
412                            "Autocrypt header address {:?} is not {:?}.", header.addr, from.addr
413                        );
414                        continue;
415                    }
416                    Err(err) => {
417                        warn!(context, "Failed to parse Autocrypt header: {:#}.", err);
418                        continue;
419                    }
420                };
421                break;
422            }
423        }
424
425        let autocrypt_fingerprint = if let Some(autocrypt_header) = &autocrypt_header {
426            let fingerprint = autocrypt_header.public_key.dc_fingerprint().hex();
427            import_public_key(context, &autocrypt_header.public_key)
428                .await
429                .context("Failed to import public key from the Autocrypt header")?;
430            Some(fingerprint)
431        } else {
432            None
433        };
434
435        let mut public_keyring = if from_is_not_self_addr {
436            if let Some(autocrypt_header) = autocrypt_header {
437                vec![autocrypt_header.public_key]
438            } else {
439                vec![]
440            }
441        } else {
442            key::load_self_public_keyring(context).await?
443        };
444
445        if let Some(signature) = match &decrypted_msg {
446            Some(pgp::composed::Message::Literal { .. }) => None,
447            Some(pgp::composed::Message::Compressed { .. }) => {
448                // One layer of compression should already be handled by now.
449                // We don't decompress messages compressed multiple times.
450                None
451            }
452            Some(pgp::composed::Message::Signed { reader, .. }) => reader.signature(0),
453            Some(pgp::composed::Message::Encrypted { .. }) => {
454                // The message is already decrypted once.
455                None
456            }
457            None => None,
458        } {
459            for issuer_fingerprint in signature.issuer_fingerprint() {
460                let issuer_fingerprint =
461                    crate::key::Fingerprint::from(issuer_fingerprint.clone()).hex();
462                if let Some(public_key_bytes) = context
463                    .sql
464                    .query_row_optional(
465                        "SELECT public_key
466                         FROM public_keys
467                         WHERE fingerprint=?",
468                        (&issuer_fingerprint,),
469                        |row| {
470                            let bytes: Vec<u8> = row.get(0)?;
471                            Ok(bytes)
472                        },
473                    )
474                    .await?
475                {
476                    let public_key = SignedPublicKey::from_slice(&public_key_bytes)?;
477                    public_keyring.push(public_key)
478                }
479            }
480        }
481
482        let mut signatures = if let Some(ref decrypted_msg) = decrypted_msg {
483            crate::pgp::valid_signature_fingerprints(decrypted_msg, &public_keyring)
484        } else {
485            HashMap::new()
486        };
487
488        let mail = mail.as_ref().map(|mail| {
489            let (content, signatures_detached) = validate_detached_signature(mail, &public_keyring)
490                .unwrap_or((mail, Default::default()));
491            if is_encrypted {
492                let signatures_detached = signatures_detached
493                    .into_iter()
494                    .map(|fp| (fp, Vec::new()))
495                    .collect::<HashMap<_, _>>();
496                signatures.extend(signatures_detached);
497            }
498            content
499        });
500
501        if let Some(expected_sender_fingerprint) = expected_sender_fingerprint {
502            ensure!(
503                !signatures.is_empty(),
504                "Unsigned message is not allowed to be encrypted with this shared secret"
505            );
506            ensure!(
507                signatures.len() == 1,
508                "Too many signatures on symm-encrypted message"
509            );
510            ensure!(
511                signatures.contains_key(&expected_sender_fingerprint.parse()?),
512                "This sender is not allowed to encrypt with this secret key"
513            );
514        }
515
516        if let (Ok(mail), true) = (mail, is_encrypted) {
517            if !signatures.is_empty() {
518                // Unsigned "Subject" mustn't be prepended to messages shown as encrypted
519                // (<https://github.com/deltachat/deltachat-core-rust/issues/1790>).
520                // Other headers are removed by `MimeMessage::merge_headers()` except for "List-ID".
521                remove_header(&mut headers, "subject", &mut headers_removed);
522                remove_header(&mut headers, "list-id", &mut headers_removed);
523            }
524
525            // let known protected headers from the decrypted
526            // part override the unencrypted top-level
527
528            // Signature was checked for original From, so we
529            // do not allow overriding it.
530            let mut inner_from = None;
531
532            MimeMessage::merge_headers(
533                context,
534                &mut headers,
535                &mut headers_removed,
536                &mut recipients,
537                &mut past_members,
538                &mut inner_from,
539                &mut list_post,
540                &mut chat_disposition_notification_to,
541                mail,
542            );
543
544            if !signatures.is_empty() {
545                // Handle any gossip headers if the mail was encrypted. See section
546                // "3.6 Key Gossip" of <https://autocrypt.org/autocrypt-spec-1.1.0.pdf>
547                // but only if the mail was correctly signed. Probably it's ok to not require
548                // encryption here, but let's follow the standard.
549                let gossip_headers = mail.headers.get_all_values("Autocrypt-Gossip");
550                gossiped_keys =
551                    parse_gossip_headers(context, &from.addr, &recipients, gossip_headers).await?;
552            }
553
554            if let Some(inner_from) = inner_from {
555                if !addr_cmp(&inner_from.addr, &from.addr) {
556                    // There is a From: header in the encrypted
557                    // part, but it doesn't match the outer one.
558                    // This _might_ be because the sender's mail server
559                    // replaced the sending address, e.g. in a mailing list.
560                    // Or it's because someone is doing some replay attack.
561                    // Resending encrypted messages via mailing lists
562                    // without reencrypting is not useful anyway,
563                    // so we return an error below.
564                    warn!(
565                        context,
566                        "From header in encrypted part doesn't match the outer one",
567                    );
568
569                    // Return an error from the parser.
570                    // This will result in creating a tombstone
571                    // and no further message processing
572                    // as if the MIME structure is broken.
573                    bail!("From header is forged");
574                }
575                from = inner_from;
576            }
577        }
578        if signatures.is_empty() {
579            Self::remove_secured_headers(&mut headers, &mut headers_removed, is_encrypted);
580        }
581        if !is_encrypted {
582            signatures.clear();
583        }
584
585        if let (Ok(mail), true) = (mail, is_encrypted)
586            && let Some(post_msg_rfc724_mid) =
587                mail.headers.get_header_value(HeaderDef::ChatPostMessageId)
588        {
589            let post_msg_rfc724_mid = parse_message_id(&post_msg_rfc724_mid)?;
590            let metadata = if let Some(value) = mail
591                .headers
592                .get_header_value(HeaderDef::ChatPostMessageMetadata)
593            {
594                match PostMsgMetadata::try_from_header_value(&value) {
595                    Ok(metadata) => Some(metadata),
596                    Err(error) => {
597                        error!(
598                            context,
599                            "Failed to parse metadata header in pre-message for {post_msg_rfc724_mid}: {error:#}."
600                        );
601                        None
602                    }
603                }
604            } else {
605                warn!(
606                    context,
607                    "Expected pre-message for {post_msg_rfc724_mid} to have metadata header."
608                );
609                None
610            };
611
612            pre_message = PreMessageMode::Pre {
613                post_msg_rfc724_mid,
614                metadata,
615            };
616        }
617
618        let signature = signatures
619            .into_iter()
620            .last()
621            .map(|(fp, recipient_fps)| (fp, recipient_fps.into_iter().collect::<HashSet<_>>()));
622
623        let incoming = if let Some((ref sig_fp, _)) = signature {
624            sig_fp.hex() != key::self_fingerprint(context).await?
625        } else {
626            // rare case of getting a cleartext message
627            // so we determine 'incoming' flag by From-address
628            from_is_not_self_addr
629        };
630
631        let mut parser = MimeMessage {
632            parts: Vec::new(),
633            headers,
634            #[cfg(test)]
635            headers_removed,
636
637            recipients,
638            past_members,
639            list_post,
640            from,
641            incoming,
642            chat_disposition_notification_to,
643            decryption_error: mail.err().map(|err| format!("{err:#}")),
644
645            // only non-empty if it was a valid autocrypt message
646            signature,
647            autocrypt_fingerprint,
648            gossiped_keys,
649            is_forwarded: false,
650            mdn_reports: Vec::new(),
651            is_system_message: SystemMessage::Unknown,
652            location_kml: None,
653            message_kml: None,
654            sync_items: None,
655            webxdc_status_update: None,
656            user_avatar: None,
657            group_avatar: None,
658            delivery_report: None,
659            footer: None,
660            is_mime_modified: false,
661            decoded_data: Vec::new(),
662            hop_info,
663            is_bot: None,
664            timestamp_rcvd,
665            timestamp_sent,
666            pre_message,
667        };
668
669        match mail {
670            Ok(mail) => {
671                parser.parse_mime_recursive(context, mail, false).await?;
672            }
673            Err(err) => {
674                let txt = "[This message cannot be decrypted.\n\n• It might already help to simply reply to this message and ask the sender to send the message again.\n\n• If you just re-installed Delta Chat then it is best if you re-setup Delta Chat now and choose \"Add as second device\" or import a backup.]";
675
676                let part = Part {
677                    typ: Viewtype::Text,
678                    msg_raw: Some(txt.to_string()),
679                    msg: txt.to_string(),
680                    // Don't change the error prefix for now,
681                    // receive_imf.rs:lookup_chat_by_reply() checks it.
682                    error: Some(format!("Decrypting failed: {err:#}")),
683                    ..Default::default()
684                };
685                parser.do_add_single_part(part);
686            }
687        };
688
689        let is_location_only = parser.location_kml.is_some() && parser.parts.is_empty();
690        if parser.mdn_reports.is_empty()
691            && !is_location_only
692            && parser.sync_items.is_none()
693            && parser.webxdc_status_update.is_none()
694        {
695            let is_bot =
696                parser.headers.get("auto-submitted") == Some(&"auto-generated".to_string());
697            parser.is_bot = Some(is_bot);
698        }
699        parser.maybe_remove_bad_parts();
700        parser.maybe_remove_inline_mailinglist_footer();
701        parser.heuristically_parse_ndn(context).await;
702        parser.parse_headers(context).await?;
703        parser.decoded_data = mail_raw;
704
705        Ok(parser)
706    }
707
708    #[expect(clippy::arithmetic_side_effects)]
709    fn get_timestamp_sent(
710        hdrs: &[mailparse::MailHeader<'_>],
711        default: i64,
712        timestamp_rcvd: i64,
713    ) -> i64 {
714        hdrs.get_header_value(HeaderDef::Date)
715            .and_then(|v| mailparse::dateparse(&v).ok())
716            .map_or(default, |value| {
717                min(value, timestamp_rcvd + constants::TIMESTAMP_SENT_TOLERANCE)
718            })
719    }
720
721    /// Parses system messages.
722    fn parse_system_message_headers(&mut self) {
723        if let Some(value) = self.get_header(HeaderDef::ChatContent) {
724            if value == "location-streaming-enabled" {
725                self.is_system_message = SystemMessage::LocationStreamingEnabled;
726            } else if value == "ephemeral-timer-changed" {
727                self.is_system_message = SystemMessage::EphemeralTimerChanged;
728            } else if value == "protection-enabled" {
729                self.is_system_message = SystemMessage::ChatProtectionEnabled;
730            } else if value == "protection-disabled" {
731                self.is_system_message = SystemMessage::ChatProtectionDisabled;
732            } else if value == "group-avatar-changed" {
733                self.is_system_message = SystemMessage::GroupImageChanged;
734            } else if value == "call-accepted" {
735                self.is_system_message = SystemMessage::CallAccepted;
736            } else if value == "call-ended" {
737                self.is_system_message = SystemMessage::CallEnded;
738            }
739        } else if self.get_header(HeaderDef::ChatGroupMemberRemoved).is_some() {
740            self.is_system_message = SystemMessage::MemberRemovedFromGroup;
741        } else if self.get_header(HeaderDef::ChatGroupMemberAdded).is_some() {
742            self.is_system_message = SystemMessage::MemberAddedToGroup;
743        } else if self.get_header(HeaderDef::ChatGroupNameChanged).is_some() {
744            self.is_system_message = SystemMessage::GroupNameChanged;
745        } else if self
746            .get_header(HeaderDef::ChatGroupDescriptionChanged)
747            .is_some()
748        {
749            self.is_system_message = SystemMessage::GroupDescriptionChanged;
750        }
751    }
752
753    /// Parses avatar action headers.
754    fn parse_avatar_headers(&mut self, context: &Context) -> Result<()> {
755        if let Some(header_value) = self.get_header(HeaderDef::ChatGroupAvatar) {
756            self.group_avatar =
757                self.avatar_action_from_header(context, header_value.to_string())?;
758        }
759
760        if let Some(header_value) = self.get_header(HeaderDef::ChatUserAvatar) {
761            self.user_avatar = self.avatar_action_from_header(context, header_value.to_string())?;
762        }
763        Ok(())
764    }
765
766    fn parse_videochat_headers(&mut self) {
767        let content = self
768            .get_header(HeaderDef::ChatContent)
769            .unwrap_or_default()
770            .to_string();
771        let room = self
772            .get_header(HeaderDef::ChatWebrtcRoom)
773            .map(|s| s.to_string());
774        let accepted = self
775            .get_header(HeaderDef::ChatWebrtcAccepted)
776            .map(|s| s.to_string());
777        let has_video = self
778            .get_header(HeaderDef::ChatWebrtcHasVideoInitially)
779            .map(|s| s.to_string());
780        if let Some(part) = self.parts.first_mut() {
781            if let Some(room) = room {
782                if content == "call" {
783                    part.typ = Viewtype::Call;
784                    part.param.set(Param::WebrtcRoom, room);
785                }
786            } else if let Some(accepted) = accepted {
787                part.param.set(Param::WebrtcAccepted, accepted);
788            }
789            if let Some(has_video) = has_video {
790                part.param.set(Param::WebrtcHasVideoInitially, has_video);
791            }
792        }
793    }
794
795    /// Squashes mutitpart chat messages with attachment into single-part messages.
796    ///
797    /// Delta Chat sends attachments, such as images, in two-part messages, with the first message
798    /// containing a description. If such a message is detected, text from the first part can be
799    /// moved to the second part, and the first part dropped.
800    fn squash_attachment_parts(&mut self) {
801        if self.parts.len() == 2
802            && self.parts.first().map(|textpart| textpart.typ) == Some(Viewtype::Text)
803            && self
804                .parts
805                .get(1)
806                .is_some_and(|filepart| match filepart.typ {
807                    Viewtype::Image
808                    | Viewtype::Gif
809                    | Viewtype::Sticker
810                    | Viewtype::Audio
811                    | Viewtype::Voice
812                    | Viewtype::Video
813                    | Viewtype::Vcard
814                    | Viewtype::File
815                    | Viewtype::Webxdc => true,
816                    Viewtype::Unknown | Viewtype::Text | Viewtype::Call => false,
817                })
818        {
819            let mut parts = std::mem::take(&mut self.parts);
820            let Some(mut filepart) = parts.pop() else {
821                // Should never happen.
822                return;
823            };
824            let Some(textpart) = parts.pop() else {
825                // Should never happen.
826                return;
827            };
828
829            filepart.msg.clone_from(&textpart.msg);
830            if let Some(quote) = textpart.param.get(Param::Quote) {
831                filepart.param.set(Param::Quote, quote);
832            }
833
834            self.parts = vec![filepart];
835        }
836    }
837
838    /// Processes chat messages with attachments.
839    fn parse_attachments(&mut self) {
840        // Attachment messages should be squashed into a single part
841        // before calling this function.
842        if self.parts.len() != 1 {
843            return;
844        }
845
846        if let Some(mut part) = self.parts.pop() {
847            if part.typ == Viewtype::Audio && self.get_header(HeaderDef::ChatVoiceMessage).is_some()
848            {
849                part.typ = Viewtype::Voice;
850            }
851            if (part.typ == Viewtype::Image || part.typ == Viewtype::Gif)
852                && let Some(value) = self.get_header(HeaderDef::ChatContent)
853                && value == "sticker"
854            {
855                part.typ = Viewtype::Sticker;
856            }
857            if (part.typ == Viewtype::Audio
858                || part.typ == Viewtype::Voice
859                || part.typ == Viewtype::Video)
860                && let Some(field_0) = self.get_header(HeaderDef::ChatDuration)
861            {
862                let duration_ms = field_0.parse().unwrap_or_default();
863                if duration_ms > 0 && duration_ms < 24 * 60 * 60 * 1000 {
864                    part.param.set_int(Param::Duration, duration_ms);
865                }
866            }
867
868            self.parts.push(part);
869        }
870    }
871
872    async fn parse_headers(&mut self, context: &Context) -> Result<()> {
873        self.parse_system_message_headers();
874        self.parse_avatar_headers(context)?;
875        self.parse_videochat_headers();
876        if self.delivery_report.is_none() {
877            self.squash_attachment_parts();
878        }
879
880        if !context.get_config_bool(Config::Bot).await?
881            && let Some(ref subject) = self.get_subject()
882        {
883            let mut prepend_subject = true;
884            if self.decryption_error.is_none() {
885                let colon = subject.find(':');
886                if colon == Some(2)
887                    || colon == Some(3)
888                    || self.has_chat_version()
889                    || subject.contains("Chat:")
890                {
891                    prepend_subject = false
892                }
893            }
894
895            // For mailing lists, always add the subject because sometimes there are different topics
896            // and otherwise it might be hard to keep track:
897            if self.is_mailinglist_message() && !self.has_chat_version() {
898                prepend_subject = true;
899            }
900
901            if prepend_subject && !subject.is_empty() {
902                let part_with_text = self
903                    .parts
904                    .iter_mut()
905                    .find(|part| !part.msg.is_empty() && !part.is_reaction);
906                if let Some(part) = part_with_text {
907                    // Message bubbles are small, so we use en dash to save space. In some
908                    // languages there may be em dashes in the message text added by the author,
909                    // they may look stronger than Subject separation, this is a known thing.
910                    // Anyway, classic email support isn't a priority as of 2025.
911                    part.msg = format!("{} – {}", subject, part.msg);
912                }
913            }
914        }
915
916        if self.is_forwarded {
917            for part in &mut self.parts {
918                part.param.set_int(Param::Forwarded, 1);
919            }
920        }
921
922        self.parse_attachments();
923
924        // See if an MDN is requested from the other side
925        if self.decryption_error.is_none()
926            && !self.parts.is_empty()
927            && let Some(ref dn_to) = self.chat_disposition_notification_to
928        {
929            // Check that the message is not outgoing.
930            let from = &self.from.addr;
931            if !context.is_self_addr(from).await? {
932                if from.to_lowercase() == dn_to.addr.to_lowercase() {
933                    if let Some(part) = self.parts.last_mut() {
934                        part.param.set_int(Param::WantsMdn, 1);
935                    }
936                } else {
937                    warn!(
938                        context,
939                        "{} requested a read receipt to {}, ignoring", from, dn_to.addr
940                    );
941                }
942            }
943        }
944
945        // If there were no parts, especially a non-DC mail user may
946        // just have send a message in the subject with an empty body.
947        // Besides, we want to show something in case our incoming-processing
948        // failed to properly handle an incoming message.
949        if self.parts.is_empty() && self.mdn_reports.is_empty() {
950            let mut part = Part {
951                typ: Viewtype::Text,
952                ..Default::default()
953            };
954
955            if let Some(ref subject) = self.get_subject()
956                && !self.has_chat_version()
957                && self.webxdc_status_update.is_none()
958            {
959                part.msg = subject.to_string();
960            }
961
962            self.do_add_single_part(part);
963        }
964
965        if self.is_bot == Some(true) {
966            for part in &mut self.parts {
967                part.param.set(Param::Bot, "1");
968            }
969        }
970
971        Ok(())
972    }
973
974    #[expect(clippy::arithmetic_side_effects)]
975    fn avatar_action_from_header(
976        &mut self,
977        context: &Context,
978        header_value: String,
979    ) -> Result<Option<AvatarAction>> {
980        let res = if header_value == "0" {
981            Some(AvatarAction::Delete)
982        } else if let Some(base64) = header_value
983            .split_ascii_whitespace()
984            .collect::<String>()
985            .strip_prefix("base64:")
986        {
987            match BlobObject::store_from_base64(context, base64)? {
988                Some(path) => Some(AvatarAction::Change(path)),
989                None => {
990                    warn!(context, "Could not decode avatar base64");
991                    None
992                }
993            }
994        } else {
995            // Avatar sent in attachment, as previous versions of Delta Chat did.
996
997            let mut i = 0;
998            while let Some(part) = self.parts.get_mut(i) {
999                if let Some(part_filename) = &part.org_filename
1000                    && part_filename == &header_value
1001                {
1002                    if let Some(blob) = part.param.get(Param::File) {
1003                        let res = Some(AvatarAction::Change(blob.to_string()));
1004                        self.parts.remove(i);
1005                        return Ok(res);
1006                    }
1007                    break;
1008                }
1009                i += 1;
1010            }
1011            None
1012        };
1013        Ok(res)
1014    }
1015
1016    /// Returns true if the message was encrypted as defined in
1017    /// Autocrypt standard.
1018    ///
1019    /// This means the message was both encrypted and signed with a
1020    /// valid signature.
1021    pub fn was_encrypted(&self) -> bool {
1022        self.signature.is_some()
1023    }
1024
1025    /// Returns whether the email contains a `chat-version` header.
1026    /// This indicates that the email is a DC-email.
1027    pub(crate) fn has_chat_version(&self) -> bool {
1028        self.headers.contains_key("chat-version")
1029    }
1030
1031    pub(crate) fn get_subject(&self) -> Option<String> {
1032        self.get_header(HeaderDef::Subject)
1033            .map(|s| s.trim_start())
1034            .filter(|s| !s.is_empty())
1035            .map(|s| s.to_string())
1036    }
1037
1038    pub fn get_header(&self, headerdef: HeaderDef) -> Option<&str> {
1039        self.headers
1040            .get(headerdef.get_headername())
1041            .map(|s| s.as_str())
1042    }
1043
1044    #[cfg(test)]
1045    /// Returns whether the header exists in any part of the parsed message.
1046    ///
1047    /// Use this to check for header absense. Header presense should be checked using
1048    /// `get_header(...).is_some()` as it also checks that the header isn't ignored.
1049    pub(crate) fn header_exists(&self, headerdef: HeaderDef) -> bool {
1050        let hname = headerdef.get_headername();
1051        self.headers.contains_key(hname) || self.headers_removed.contains(hname)
1052    }
1053
1054    #[cfg(test)]
1055    /// Returns whether the decrypted data contains the given `&str`.
1056    pub(crate) fn decoded_data_contains(&self, s: &str) -> bool {
1057        assert!(self.decryption_error.is_none());
1058        let decoded_str = str::from_utf8(&self.decoded_data).unwrap();
1059        decoded_str.contains(s)
1060    }
1061
1062    /// Returns `Chat-Group-ID` header value if it is a valid group ID.
1063    pub fn get_chat_group_id(&self) -> Option<&str> {
1064        self.get_header(HeaderDef::ChatGroupId)
1065            .filter(|s| validate_id(s))
1066    }
1067
1068    async fn parse_mime_recursive<'a>(
1069        &'a mut self,
1070        context: &'a Context,
1071        mail: &'a mailparse::ParsedMail<'a>,
1072        is_related: bool,
1073    ) -> Result<bool> {
1074        enum MimeS {
1075            Multiple,
1076            Single,
1077            Message,
1078        }
1079
1080        let mimetype = mail.ctype.mimetype.to_lowercase();
1081
1082        let m = if mimetype.starts_with("multipart") {
1083            if mail.ctype.params.contains_key("boundary") {
1084                MimeS::Multiple
1085            } else {
1086                MimeS::Single
1087            }
1088        } else if mimetype.starts_with("message") {
1089            if mimetype == "message/rfc822" && !is_attachment_disposition(mail) {
1090                MimeS::Message
1091            } else {
1092                MimeS::Single
1093            }
1094        } else {
1095            MimeS::Single
1096        };
1097
1098        let is_related = is_related || mimetype == "multipart/related";
1099        match m {
1100            MimeS::Multiple => Box::pin(self.handle_multiple(context, mail, is_related)).await,
1101            MimeS::Message => {
1102                let raw = mail.get_body_raw()?;
1103                if raw.is_empty() {
1104                    return Ok(false);
1105                }
1106                let mail = mailparse::parse_mail(&raw).context("failed to parse mail")?;
1107
1108                Box::pin(self.parse_mime_recursive(context, &mail, is_related)).await
1109            }
1110            MimeS::Single => {
1111                self.add_single_part_if_known(context, mail, is_related)
1112                    .await
1113            }
1114        }
1115    }
1116
1117    async fn handle_multiple(
1118        &mut self,
1119        context: &Context,
1120        mail: &mailparse::ParsedMail<'_>,
1121        is_related: bool,
1122    ) -> Result<bool> {
1123        let mut any_part_added = false;
1124        let mimetype = get_mime_type(
1125            mail,
1126            &get_attachment_filename(context, mail)?,
1127            self.has_chat_version(),
1128        )?
1129        .0;
1130        match (mimetype.type_(), mimetype.subtype().as_str()) {
1131            (mime::MULTIPART, "alternative") => {
1132                // multipart/alternative is described in
1133                // <https://datatracker.ietf.org/doc/html/rfc2046#section-5.1.4>.
1134                // Specification says that last part should be preferred,
1135                // so we iterate over parts in reverse order.
1136
1137                // Search for plain text or multipart part.
1138                //
1139                // If we find a multipart inside multipart/alternative
1140                // and it has usable subparts, we only parse multipart.
1141                // This happens e.g. in Apple Mail:
1142                // "plaintext" as an alternative to "html+PDF attachment".
1143                for cur_data in mail.subparts.iter().rev() {
1144                    let (mime_type, _viewtype) = get_mime_type(
1145                        cur_data,
1146                        &get_attachment_filename(context, cur_data)?,
1147                        self.has_chat_version(),
1148                    )?;
1149
1150                    if mime_type == mime::TEXT_PLAIN || mime_type.type_() == mime::MULTIPART {
1151                        any_part_added = self
1152                            .parse_mime_recursive(context, cur_data, is_related)
1153                            .await?;
1154                        break;
1155                    }
1156                }
1157
1158                // Explicitly look for a `text/calendar` part.
1159                // Messages conforming to <https://datatracker.ietf.org/doc/html/rfc6047>
1160                // contain `text/calendar` part as an alternative
1161                // to the text or HTML representation.
1162                //
1163                // While we cannot display `text/calendar` and therefore do not prefer it,
1164                // we still make it available by presenting as an attachment
1165                // with a generic filename.
1166                for cur_data in mail.subparts.iter().rev() {
1167                    let mimetype = cur_data.ctype.mimetype.parse::<Mime>()?;
1168                    if mimetype.type_() == mime::TEXT && mimetype.subtype() == "calendar" {
1169                        let filename = get_attachment_filename(context, cur_data)?
1170                            .unwrap_or_else(|| "calendar.ics".to_string());
1171                        self.do_add_single_file_part(
1172                            context,
1173                            Viewtype::File,
1174                            mimetype,
1175                            &mail.ctype.mimetype.to_lowercase(),
1176                            &mail.get_body_raw()?,
1177                            &filename,
1178                            is_related,
1179                        )
1180                        .await?;
1181                    }
1182                }
1183
1184                if !any_part_added {
1185                    for cur_part in mail.subparts.iter().rev() {
1186                        if self
1187                            .parse_mime_recursive(context, cur_part, is_related)
1188                            .await?
1189                        {
1190                            any_part_added = true;
1191                            break;
1192                        }
1193                    }
1194                }
1195                if any_part_added && mail.subparts.len() > 1 {
1196                    // there are other alternative parts, likely HTML,
1197                    // so we might have missed some content on simplifying.
1198                    // set mime-modified to force the ui to display a show-message button.
1199                    self.is_mime_modified = true;
1200                }
1201            }
1202            (mime::MULTIPART, "signed") => {
1203                /* RFC 1847: "The multipart/signed content type
1204                contains exactly two body parts.  The first body
1205                part is the body part over which the digital signature was created [...]
1206                The second body part contains the control information necessary to
1207                verify the digital signature." We simply take the first body part and
1208                skip the rest.  (see
1209                <https://k9mail.app/2016/11/24/OpenPGP-Considerations-Part-I.html>
1210                for background information why we use encrypted+signed) */
1211                if let Some(first) = mail.subparts.first() {
1212                    any_part_added = self
1213                        .parse_mime_recursive(context, first, is_related)
1214                        .await?;
1215                }
1216            }
1217            (mime::MULTIPART, "report") => {
1218                /* RFC 6522: the first part is for humans, the second for machines */
1219                if mail.subparts.len() >= 2 {
1220                    match mail.ctype.params.get("report-type").map(|s| s as &str) {
1221                        Some("disposition-notification") => {
1222                            if let Some(report) = self.process_report(context, mail)? {
1223                                self.mdn_reports.push(report);
1224                            }
1225
1226                            // Add MDN part so we can track it, avoid
1227                            // downloading the message again and
1228                            // delete if automatic message deletion is
1229                            // enabled.
1230                            let part = Part {
1231                                typ: Viewtype::Unknown,
1232                                ..Default::default()
1233                            };
1234                            self.parts.push(part);
1235
1236                            any_part_added = true;
1237                        }
1238                        // Some providers, e.g. Tiscali, forget to set the report-type. So, if it's None, assume that it might be delivery-status
1239                        Some("delivery-status") | None => {
1240                            if let Some(report) = self.process_delivery_status(context, mail)? {
1241                                self.delivery_report = Some(report);
1242                            }
1243
1244                            // Add all parts (we need another part, preferably text/plain, to show as an error message)
1245                            for cur_data in &mail.subparts {
1246                                if self
1247                                    .parse_mime_recursive(context, cur_data, is_related)
1248                                    .await?
1249                                {
1250                                    any_part_added = true;
1251                                }
1252                            }
1253                        }
1254                        Some("multi-device-sync") => {
1255                            if let Some(second) = mail.subparts.get(1) {
1256                                self.add_single_part_if_known(context, second, is_related)
1257                                    .await?;
1258                            }
1259                        }
1260                        Some("status-update") => {
1261                            if let Some(second) = mail.subparts.get(1) {
1262                                self.add_single_part_if_known(context, second, is_related)
1263                                    .await?;
1264                            }
1265                        }
1266                        Some(_) => {
1267                            for cur_data in &mail.subparts {
1268                                if self
1269                                    .parse_mime_recursive(context, cur_data, is_related)
1270                                    .await?
1271                                {
1272                                    any_part_added = true;
1273                                }
1274                            }
1275                        }
1276                    }
1277                }
1278            }
1279            _ => {
1280                // Add all parts (in fact, AddSinglePartIfKnown() later check if
1281                // the parts are really supported)
1282                for cur_data in &mail.subparts {
1283                    if self
1284                        .parse_mime_recursive(context, cur_data, is_related)
1285                        .await?
1286                    {
1287                        any_part_added = true;
1288                    }
1289                }
1290            }
1291        }
1292
1293        Ok(any_part_added)
1294    }
1295
1296    /// Returns true if any part was added, false otherwise.
1297    async fn add_single_part_if_known(
1298        &mut self,
1299        context: &Context,
1300        mail: &mailparse::ParsedMail<'_>,
1301        is_related: bool,
1302    ) -> Result<bool> {
1303        // return true if a part was added
1304        let filename = get_attachment_filename(context, mail)?;
1305        let (mime_type, msg_type) = get_mime_type(mail, &filename, self.has_chat_version())?;
1306        let raw_mime = mail.ctype.mimetype.to_lowercase();
1307
1308        let old_part_count = self.parts.len();
1309
1310        match filename {
1311            Some(filename) => {
1312                self.do_add_single_file_part(
1313                    context,
1314                    msg_type,
1315                    mime_type,
1316                    &raw_mime,
1317                    &mail.get_body_raw()?,
1318                    &filename,
1319                    is_related,
1320                )
1321                .await?;
1322            }
1323            None => {
1324                match mime_type.type_() {
1325                    mime::IMAGE | mime::AUDIO | mime::VIDEO | mime::APPLICATION => {
1326                        warn!(context, "Missing attachment");
1327                        return Ok(false);
1328                    }
1329                    mime::TEXT
1330                        if mail.get_content_disposition().disposition
1331                            == DispositionType::Extension("reaction".to_string()) =>
1332                    {
1333                        // Reaction.
1334                        let decoded_data = match mail.get_body() {
1335                            Ok(decoded_data) => decoded_data,
1336                            Err(err) => {
1337                                warn!(context, "Invalid body parsed {:#}", err);
1338                                // Note that it's not always an error - might be no data
1339                                return Ok(false);
1340                            }
1341                        };
1342
1343                        let part = Part {
1344                            typ: Viewtype::Text,
1345                            mimetype: Some(mime_type),
1346                            msg: decoded_data,
1347                            is_reaction: true,
1348                            ..Default::default()
1349                        };
1350                        self.do_add_single_part(part);
1351                        return Ok(true);
1352                    }
1353                    mime::TEXT | mime::HTML => {
1354                        let decoded_data = match mail.get_body() {
1355                            Ok(decoded_data) => decoded_data,
1356                            Err(err) => {
1357                                warn!(context, "Invalid body parsed {:#}", err);
1358                                // Note that it's not always an error - might be no data
1359                                return Ok(false);
1360                            }
1361                        };
1362
1363                        let is_plaintext = mime_type == mime::TEXT_PLAIN;
1364                        let mut dehtml_failed = false;
1365
1366                        let SimplifiedText {
1367                            text: simplified_txt,
1368                            is_forwarded,
1369                            is_cut,
1370                            top_quote,
1371                            footer,
1372                        } = if decoded_data.is_empty() {
1373                            Default::default()
1374                        } else {
1375                            let is_html = mime_type == mime::TEXT_HTML;
1376                            if is_html {
1377                                self.is_mime_modified = true;
1378                                // NB: This unconditionally removes Legacy Display Elements (see
1379                                // <https://www.rfc-editor.org/rfc/rfc9788.html#section-4.5.3.3>). We
1380                                // don't check for the "hp-legacy-display" Content-Type parameter
1381                                // for simplicity.
1382                                if let Some(text) = dehtml(&decoded_data) {
1383                                    text
1384                                } else {
1385                                    dehtml_failed = true;
1386                                    SimplifiedText {
1387                                        text: decoded_data.clone(),
1388                                        ..Default::default()
1389                                    }
1390                                }
1391                            } else {
1392                                simplify(decoded_data.clone(), self.has_chat_version())
1393                            }
1394                        };
1395
1396                        self.is_mime_modified = self.is_mime_modified
1397                            || ((is_forwarded || is_cut || top_quote.is_some())
1398                                && !self.has_chat_version());
1399
1400                        let is_format_flowed = if let Some(format) = mail.ctype.params.get("format")
1401                        {
1402                            format.as_str().eq_ignore_ascii_case("flowed")
1403                        } else {
1404                            false
1405                        };
1406
1407                        let (simplified_txt, simplified_quote) = if mime_type.type_() == mime::TEXT
1408                            && mime_type.subtype() == mime::PLAIN
1409                        {
1410                            // Don't check that we're inside an encrypted or signed part for
1411                            // simplicity.
1412                            let simplified_txt = match mail
1413                                .ctype
1414                                .params
1415                                .get("hp-legacy-display")
1416                                .is_some_and(|v| v == "1")
1417                            {
1418                                false => simplified_txt,
1419                                true => rm_legacy_display_elements(&simplified_txt),
1420                            };
1421                            if is_format_flowed {
1422                                let delsp = if let Some(delsp) = mail.ctype.params.get("delsp") {
1423                                    delsp.as_str().eq_ignore_ascii_case("yes")
1424                                } else {
1425                                    false
1426                                };
1427                                let unflowed_text = unformat_flowed(&simplified_txt, delsp);
1428                                let unflowed_quote = top_quote.map(|q| unformat_flowed(&q, delsp));
1429                                (unflowed_text, unflowed_quote)
1430                            } else {
1431                                (simplified_txt, top_quote)
1432                            }
1433                        } else {
1434                            (simplified_txt, top_quote)
1435                        };
1436
1437                        let (simplified_txt, was_truncated) =
1438                            truncate_msg_text(context, simplified_txt).await?;
1439                        if was_truncated {
1440                            self.is_mime_modified = was_truncated;
1441                        }
1442
1443                        if !simplified_txt.is_empty() || simplified_quote.is_some() {
1444                            let mut part = Part {
1445                                dehtml_failed,
1446                                typ: Viewtype::Text,
1447                                mimetype: Some(mime_type),
1448                                msg: simplified_txt,
1449                                ..Default::default()
1450                            };
1451                            if let Some(quote) = simplified_quote {
1452                                part.param.set(Param::Quote, quote);
1453                            }
1454                            part.msg_raw = Some(decoded_data);
1455                            self.do_add_single_part(part);
1456                        }
1457
1458                        if is_forwarded {
1459                            self.is_forwarded = true;
1460                        }
1461
1462                        if self.footer.is_none() && is_plaintext {
1463                            self.footer = Some(footer.unwrap_or_default());
1464                        }
1465                    }
1466                    _ => {}
1467                }
1468            }
1469        }
1470
1471        // add object? (we do not add all objects, eg. signatures etc. are ignored)
1472        Ok(self.parts.len() > old_part_count)
1473    }
1474
1475    #[expect(clippy::too_many_arguments)]
1476    #[expect(clippy::arithmetic_side_effects)]
1477    async fn do_add_single_file_part(
1478        &mut self,
1479        context: &Context,
1480        msg_type: Viewtype,
1481        mime_type: Mime,
1482        raw_mime: &str,
1483        decoded_data: &[u8],
1484        filename: &str,
1485        is_related: bool,
1486    ) -> Result<()> {
1487        // Process attached PGP keys.
1488        if mime_type.type_() == mime::APPLICATION
1489            && mime_type.subtype().as_str() == "pgp-keys"
1490            && Self::try_set_peer_key_from_file_part(context, decoded_data).await?
1491        {
1492            return Ok(());
1493        }
1494        let mut part = Part::default();
1495        let msg_type = if context
1496            .is_webxdc_file(filename, decoded_data)
1497            .await
1498            .unwrap_or(false)
1499        {
1500            Viewtype::Webxdc
1501        } else if filename.ends_with(".kml") {
1502            // XXX what if somebody sends eg an "location-highlights.kml"
1503            // attachment unrelated to location streaming?
1504            if filename.starts_with("location") || filename.starts_with("message") {
1505                let parsed = location::Kml::parse(decoded_data)
1506                    .map_err(|err| {
1507                        warn!(context, "failed to parse kml part: {:#}", err);
1508                    })
1509                    .ok();
1510                if filename.starts_with("location") {
1511                    self.location_kml = parsed;
1512                } else {
1513                    self.message_kml = parsed;
1514                }
1515                return Ok(());
1516            }
1517            msg_type
1518        } else if filename == "multi-device-sync.json" {
1519            if !context.get_config_bool(Config::SyncMsgs).await? {
1520                return Ok(());
1521            }
1522            let serialized = String::from_utf8_lossy(decoded_data)
1523                .parse()
1524                .unwrap_or_default();
1525            self.sync_items = context
1526                .parse_sync_items(serialized)
1527                .map_err(|err| {
1528                    warn!(context, "failed to parse sync data: {:#}", err);
1529                })
1530                .ok();
1531            return Ok(());
1532        } else if filename == "status-update.json" {
1533            let serialized = String::from_utf8_lossy(decoded_data)
1534                .parse()
1535                .unwrap_or_default();
1536            self.webxdc_status_update = Some(serialized);
1537            return Ok(());
1538        } else if msg_type == Viewtype::Vcard {
1539            if let Some(summary) = get_vcard_summary(decoded_data) {
1540                part.param.set(Param::Summary1, summary);
1541                msg_type
1542            } else {
1543                Viewtype::File
1544            }
1545        } else if msg_type == Viewtype::Image
1546            || msg_type == Viewtype::Gif
1547            || msg_type == Viewtype::Sticker
1548        {
1549            match get_filemeta(decoded_data) {
1550                // image size is known, not too big, keep msg_type:
1551                Ok((width, height)) if width * height <= constants::MAX_RCVD_IMAGE_PIXELS => {
1552                    part.param.set_i64(Param::Width, width.into());
1553                    part.param.set_i64(Param::Height, height.into());
1554                    msg_type
1555                }
1556                // image is too big or size is unknown, display as file:
1557                _ => Viewtype::File,
1558            }
1559        } else {
1560            msg_type
1561        };
1562
1563        /* we have a regular file attachment,
1564        write decoded data to new blob object */
1565
1566        let blob =
1567            match BlobObject::create_and_deduplicate_from_bytes(context, decoded_data, filename) {
1568                Ok(blob) => blob,
1569                Err(err) => {
1570                    error!(
1571                        context,
1572                        "Could not add blob for mime part {}, error {:#}", filename, err
1573                    );
1574                    return Ok(());
1575                }
1576            };
1577        info!(context, "added blobfile: {:?}", blob.as_name());
1578
1579        part.typ = msg_type;
1580        part.org_filename = Some(filename.to_string());
1581        part.mimetype = Some(mime_type);
1582        part.bytes = decoded_data.len();
1583        part.param.set(Param::File, blob.as_name());
1584        part.param.set(Param::Filename, filename);
1585        part.param.set(Param::MimeType, raw_mime);
1586        part.is_related = is_related;
1587
1588        self.do_add_single_part(part);
1589        Ok(())
1590    }
1591
1592    /// Returns whether a key from the attachment was saved.
1593    async fn try_set_peer_key_from_file_part(
1594        context: &Context,
1595        decoded_data: &[u8],
1596    ) -> Result<bool> {
1597        let key = match str::from_utf8(decoded_data) {
1598            Err(err) => {
1599                warn!(context, "PGP key attachment is not a UTF-8 file: {}", err);
1600                return Ok(false);
1601            }
1602            Ok(key) => key,
1603        };
1604        let key = match SignedPublicKey::from_asc(key) {
1605            Err(err) => {
1606                warn!(
1607                    context,
1608                    "PGP key attachment is not an ASCII-armored file: {err:#}."
1609                );
1610                return Ok(false);
1611            }
1612            Ok(key) => key,
1613        };
1614        if let Err(err) = import_public_key(context, &key).await {
1615            warn!(context, "Attached PGP key import failed: {err:#}.");
1616            return Ok(false);
1617        }
1618
1619        info!(context, "Imported PGP key from attachment.");
1620        Ok(true)
1621    }
1622
1623    pub(crate) fn do_add_single_part(&mut self, mut part: Part) {
1624        if self.was_encrypted() {
1625            part.param.set_int(Param::GuaranteeE2ee, 1);
1626        }
1627        self.parts.push(part);
1628    }
1629
1630    pub(crate) fn get_mailinglist_header(&self) -> Option<&str> {
1631        if let Some(list_id) = self.get_header(HeaderDef::ListId) {
1632            // The message belongs to a mailing list and has a `ListId:`-header
1633            // that should be used to get a unique id.
1634            return Some(list_id);
1635        } else if let Some(chat_list_id) = self.get_header(HeaderDef::ChatListId) {
1636            return Some(chat_list_id);
1637        } else if let Some(sender) = self.get_header(HeaderDef::Sender) {
1638            // the `Sender:`-header alone is no indicator for mailing list
1639            // as also used for bot-impersonation via `set_override_sender_name()`
1640            if let Some(precedence) = self.get_header(HeaderDef::Precedence)
1641                && (precedence == "list" || precedence == "bulk")
1642            {
1643                // The message belongs to a mailing list, but there is no `ListId:`-header;
1644                // `Sender:`-header is be used to get a unique id.
1645                // This method is used by implementations as Majordomo.
1646                return Some(sender);
1647            }
1648        }
1649        None
1650    }
1651
1652    pub(crate) fn is_mailinglist_message(&self) -> bool {
1653        self.get_mailinglist_header().is_some()
1654    }
1655
1656    /// Detects Schleuder mailing list by List-Help header.
1657    pub(crate) fn is_schleuder_message(&self) -> bool {
1658        if let Some(list_help) = self.get_header(HeaderDef::ListHelp) {
1659            list_help == "<https://schleuder.org/>"
1660        } else {
1661            false
1662        }
1663    }
1664
1665    /// Check if a message is a call.
1666    pub(crate) fn is_call(&self) -> bool {
1667        self.parts
1668            .first()
1669            .is_some_and(|part| part.typ == Viewtype::Call)
1670    }
1671
1672    pub(crate) fn get_rfc724_mid(&self) -> Option<String> {
1673        self.get_header(HeaderDef::MessageId)
1674            .and_then(|msgid| parse_message_id(msgid).ok())
1675    }
1676
1677    /// Remove headers that are not allowed in unsigned / unencrypted messages.
1678    ///
1679    /// Pass `encrypted=true` parameter for an encrypted, but unsigned message.
1680    /// Pass `encrypted=false` parameter for an unencrypted message.
1681    /// Don't call this function if the message was encrypted and signed.
1682    fn remove_secured_headers(
1683        headers: &mut HashMap<String, String>,
1684        removed: &mut HashSet<String>,
1685        encrypted: bool,
1686    ) {
1687        remove_header(headers, "secure-join-fingerprint", removed);
1688        remove_header(headers, "chat-verified", removed);
1689        remove_header(headers, "autocrypt-gossip", removed);
1690
1691        if headers.get("secure-join") == Some(&"vc-request-pubkey".to_string()) && encrypted {
1692            // vc-request-pubkey message is encrypted, but unsigned,
1693            // and contains a Secure-Join-Auth header.
1694            //
1695            // It is unsigned in order not to leak Bob's identity to a server operator
1696            // that scraped the AUTH token somewhere from the web,
1697            // and because Alice anyways couldn't verify his signature at this step,
1698            // because she doesn't know his public key yet.
1699        } else {
1700            remove_header(headers, "secure-join-auth", removed);
1701
1702            // Secure-Join is secured unless it is an initial "vc-request"/"vg-request".
1703            if let Some(secure_join) = remove_header(headers, "secure-join", removed)
1704                && (secure_join == "vc-request" || secure_join == "vg-request")
1705            {
1706                headers.insert("secure-join".to_string(), secure_join);
1707            }
1708        }
1709    }
1710
1711    /// Merges headers from the email `part` into `headers` respecting header protection.
1712    /// Should only be called with nonempty `headers` if `part` is a root of the Cryptographic
1713    /// Payload as defined in <https://www.rfc-editor.org/rfc/rfc9788.html> "Header Protection for
1714    /// Cryptographically Protected Email", otherwise this may unnecessarily discard headers from
1715    /// outer parts.
1716    #[allow(clippy::too_many_arguments)]
1717    fn merge_headers(
1718        context: &Context,
1719        headers: &mut HashMap<String, String>,
1720        headers_removed: &mut HashSet<String>,
1721        recipients: &mut Vec<SingleInfo>,
1722        past_members: &mut Vec<SingleInfo>,
1723        from: &mut Option<SingleInfo>,
1724        list_post: &mut Option<String>,
1725        chat_disposition_notification_to: &mut Option<SingleInfo>,
1726        part: &mailparse::ParsedMail,
1727    ) {
1728        let fields = &part.headers;
1729        // See <https://www.rfc-editor.org/rfc/rfc9788.html>.
1730        let has_header_protection = part.ctype.params.contains_key("hp");
1731
1732        headers_removed.extend(
1733            headers
1734                .extract_if(|k, _v| has_header_protection || is_protected(k))
1735                .map(|(k, _v)| k.to_string()),
1736        );
1737        for field in fields {
1738            // lowercasing all headers is technically not correct, but makes things work better
1739            let key = field.get_key().to_lowercase();
1740            if key == HeaderDef::ChatDispositionNotificationTo.get_headername() {
1741                match addrparse_header(field) {
1742                    Ok(addrlist) => {
1743                        *chat_disposition_notification_to = addrlist.extract_single_info();
1744                    }
1745                    Err(e) => warn!(context, "Could not read {} address: {}", key, e),
1746                }
1747            } else {
1748                let value = field.get_value();
1749                headers.insert(key.to_string(), value);
1750            }
1751        }
1752        let recipients_new = get_recipients(fields);
1753        if !recipients_new.is_empty() {
1754            *recipients = recipients_new;
1755        }
1756        let past_members_addresses =
1757            get_all_addresses_from_header(fields, "chat-group-past-members");
1758        if !past_members_addresses.is_empty() {
1759            *past_members = past_members_addresses;
1760        }
1761        let from_new = get_from(fields);
1762        if from_new.is_some() {
1763            *from = from_new;
1764        }
1765        let list_post_new = get_list_post(fields);
1766        if list_post_new.is_some() {
1767            *list_post = list_post_new;
1768        }
1769    }
1770
1771    fn process_report(
1772        &self,
1773        context: &Context,
1774        report: &mailparse::ParsedMail<'_>,
1775    ) -> Result<Option<Report>> {
1776        // parse as mailheaders
1777        let report_body = if let Some(subpart) = report.subparts.get(1) {
1778            subpart.get_body_raw()?
1779        } else {
1780            bail!("Report does not have second MIME part");
1781        };
1782        let (report_fields, _) = mailparse::parse_headers(&report_body)?;
1783
1784        // must be present
1785        if report_fields
1786            .get_header_value(HeaderDef::Disposition)
1787            .is_none()
1788        {
1789            warn!(
1790                context,
1791                "Ignoring unknown disposition-notification, Message-Id: {:?}.",
1792                report_fields.get_header_value(HeaderDef::MessageId)
1793            );
1794            return Ok(None);
1795        };
1796
1797        let original_message_id = report_fields
1798            .get_header_value(HeaderDef::OriginalMessageId)
1799            // MS Exchange doesn't add an Original-Message-Id header. Instead, they put
1800            // the original message id into the In-Reply-To header:
1801            .or_else(|| report.headers.get_header_value(HeaderDef::InReplyTo))
1802            .and_then(|v| parse_message_id(&v).ok());
1803        let additional_message_ids = report_fields
1804            .get_header_value(HeaderDef::AdditionalMessageIds)
1805            .map_or_else(Vec::new, |v| {
1806                v.split(' ')
1807                    .filter_map(|s| parse_message_id(s).ok())
1808                    .collect()
1809            });
1810
1811        Ok(Some(Report {
1812            original_message_id,
1813            additional_message_ids,
1814        }))
1815    }
1816
1817    fn process_delivery_status(
1818        &self,
1819        context: &Context,
1820        report: &mailparse::ParsedMail<'_>,
1821    ) -> Result<Option<DeliveryReport>> {
1822        // Assume failure.
1823        let mut failure = true;
1824
1825        if let Some(status_part) = report.subparts.get(1) {
1826            // RFC 3464 defines `message/delivery-status`
1827            // RFC 6533 defines `message/global-delivery-status`
1828            if status_part.ctype.mimetype != "message/delivery-status"
1829                && status_part.ctype.mimetype != "message/global-delivery-status"
1830            {
1831                warn!(
1832                    context,
1833                    "Second part of Delivery Status Notification is not message/delivery-status or message/global-delivery-status, ignoring"
1834                );
1835                return Ok(None);
1836            }
1837
1838            let status_body = status_part.get_body_raw()?;
1839
1840            // Skip per-message fields.
1841            let (_, sz) = mailparse::parse_headers(&status_body)?;
1842
1843            // Parse first set of per-recipient fields
1844            if let Some(status_body) = status_body.get(sz..) {
1845                let (status_fields, _) = mailparse::parse_headers(status_body)?;
1846                if let Some(action) = status_fields.get_first_value("action") {
1847                    if action != "failed" {
1848                        info!(context, "DSN with {:?} action", action);
1849                        failure = false;
1850                    }
1851                } else {
1852                    warn!(context, "DSN without action");
1853                }
1854            } else {
1855                warn!(context, "DSN without per-recipient fields");
1856            }
1857        } else {
1858            // No message/delivery-status part.
1859            return Ok(None);
1860        }
1861
1862        // parse as mailheaders
1863        if let Some(original_msg) = report.subparts.get(2).filter(|p| {
1864            p.ctype.mimetype.contains("rfc822")
1865                || p.ctype.mimetype == "message/global"
1866                || p.ctype.mimetype == "message/global-headers"
1867        }) {
1868            let report_body = original_msg.get_body_raw()?;
1869            let (report_fields, _) = mailparse::parse_headers(&report_body)?;
1870
1871            if let Some(original_message_id) = report_fields
1872                .get_header_value(HeaderDef::MessageId)
1873                .and_then(|v| parse_message_id(&v).ok())
1874            {
1875                return Ok(Some(DeliveryReport {
1876                    rfc724_mid: original_message_id,
1877                    failure,
1878                }));
1879            }
1880
1881            warn!(
1882                context,
1883                "ignoring unknown ndn-notification, Message-Id: {:?}",
1884                report_fields.get_header_value(HeaderDef::MessageId)
1885            );
1886        }
1887
1888        Ok(None)
1889    }
1890
1891    fn maybe_remove_bad_parts(&mut self) {
1892        let good_parts = self.parts.iter().filter(|p| !p.dehtml_failed).count();
1893        if good_parts == 0 {
1894            // We have no good part but show at least one bad part in order to show anything at all
1895            self.parts.truncate(1);
1896        } else if good_parts < self.parts.len() {
1897            self.parts.retain(|p| !p.dehtml_failed);
1898        }
1899
1900        // remove images that are descendants of multipart/related but the first one:
1901        // - for newsletters or so, that is often the logo
1902        // - for user-generated html-mails, that may be some drag'n'drop photo,
1903        //   so, the recipient sees at least the first image directly
1904        // - all other images can be accessed by "show full message"
1905        // - to ensure, there is such a button, we do removal only if
1906        //   `is_mime_modified` is set
1907        if !self.has_chat_version() && self.is_mime_modified {
1908            fn is_related_image(p: &&Part) -> bool {
1909                (p.typ == Viewtype::Image || p.typ == Viewtype::Gif) && p.is_related
1910            }
1911            let related_image_cnt = self.parts.iter().filter(is_related_image).count();
1912            if related_image_cnt > 1 {
1913                let mut is_first_image = true;
1914                self.parts.retain(|p| {
1915                    let retain = is_first_image || !is_related_image(&p);
1916                    if p.typ == Viewtype::Image || p.typ == Viewtype::Gif {
1917                        is_first_image = false;
1918                    }
1919                    retain
1920                });
1921            }
1922        }
1923    }
1924
1925    /// Remove unwanted, additional text parts used for mailing list footer.
1926    /// Some mailinglist software add footers as separate mimeparts
1927    /// eg. when the user-edited-content is html.
1928    /// As these footers would appear as repeated, separate text-bubbles,
1929    /// we remove them.
1930    ///
1931    /// We make an exception for Schleuder mailing lists
1932    /// because they typically create messages with two text parts,
1933    /// one for headers and one for the actual contents.
1934    fn maybe_remove_inline_mailinglist_footer(&mut self) {
1935        if self.is_mailinglist_message() && !self.is_schleuder_message() {
1936            let text_part_cnt = self
1937                .parts
1938                .iter()
1939                .filter(|p| p.typ == Viewtype::Text)
1940                .count();
1941            if text_part_cnt == 2
1942                && let Some(last_part) = self.parts.last()
1943                && last_part.typ == Viewtype::Text
1944            {
1945                self.parts.pop();
1946            }
1947        }
1948    }
1949
1950    /// Some providers like GMX and Yahoo do not send standard NDNs (Non Delivery notifications).
1951    /// If you improve heuristics here you might also have to change prefetch_should_download() in imap/mod.rs.
1952    /// Also you should add a test in receive_imf.rs (there already are lots of test_parse_ndn_* tests).
1953    async fn heuristically_parse_ndn(&mut self, context: &Context) {
1954        let maybe_ndn = if let Some(from) = self.get_header(HeaderDef::From_) {
1955            let from = from.to_ascii_lowercase();
1956            from.contains("mailer-daemon") || from.contains("mail-daemon")
1957        } else {
1958            false
1959        };
1960        if maybe_ndn && self.delivery_report.is_none() {
1961            for original_message_id in self
1962                .parts
1963                .iter()
1964                .filter_map(|part| part.msg_raw.as_ref())
1965                .flat_map(|part| part.lines())
1966                .filter_map(|line| line.split_once("Message-ID:"))
1967                .filter_map(|(_, message_id)| parse_message_id(message_id).ok())
1968            {
1969                if let Ok(Some(_)) = message::rfc724_mid_exists(context, &original_message_id).await
1970                {
1971                    self.delivery_report = Some(DeliveryReport {
1972                        rfc724_mid: original_message_id,
1973                        failure: true,
1974                    })
1975                }
1976            }
1977        }
1978    }
1979
1980    /// Handle reports
1981    /// (MDNs = Message Disposition Notification, the message was read
1982    /// and NDNs = Non delivery notification, the message could not be delivered)
1983    pub async fn handle_reports(&self, context: &Context, from_id: ContactId, parts: &[Part]) {
1984        for report in &self.mdn_reports {
1985            for original_message_id in report
1986                .original_message_id
1987                .iter()
1988                .chain(&report.additional_message_ids)
1989            {
1990                if let Err(err) =
1991                    handle_mdn(context, from_id, original_message_id, self.timestamp_sent).await
1992                {
1993                    warn!(context, "Could not handle MDN: {err:#}.");
1994                }
1995            }
1996        }
1997
1998        if let Some(delivery_report) = &self.delivery_report
1999            && delivery_report.failure
2000        {
2001            let error = parts
2002                .iter()
2003                .find(|p| p.typ == Viewtype::Text)
2004                .map(|p| p.msg.clone());
2005            if let Err(err) = handle_ndn(context, delivery_report, error).await {
2006                warn!(context, "Could not handle NDN: {err:#}.");
2007            }
2008        }
2009    }
2010
2011    /// Returns timestamp of the parent message.
2012    ///
2013    /// If there is no parent message or it is not found in the
2014    /// database, returns None.
2015    pub async fn get_parent_timestamp(&self, context: &Context) -> Result<Option<i64>> {
2016        let parent_timestamp = if let Some(field) = self
2017            .get_header(HeaderDef::InReplyTo)
2018            .and_then(|msgid| parse_message_id(msgid).ok())
2019        {
2020            context
2021                .sql
2022                .query_get_value("SELECT timestamp FROM msgs WHERE rfc724_mid=?", (field,))
2023                .await?
2024        } else {
2025            None
2026        };
2027        Ok(parent_timestamp)
2028    }
2029
2030    /// Returns parsed `Chat-Group-Member-Timestamps` header contents.
2031    ///
2032    /// Returns `None` if there is no such header.
2033    #[expect(clippy::arithmetic_side_effects)]
2034    pub fn chat_group_member_timestamps(&self) -> Option<Vec<i64>> {
2035        let now = time() + constants::TIMESTAMP_SENT_TOLERANCE;
2036        self.get_header(HeaderDef::ChatGroupMemberTimestamps)
2037            .map(|h| {
2038                h.split_ascii_whitespace()
2039                    .filter_map(|ts| ts.parse::<i64>().ok())
2040                    .map(|ts| std::cmp::min(now, ts))
2041                    .collect()
2042            })
2043    }
2044
2045    /// Returns list of fingerprints from
2046    /// `Chat-Group-Member-Fpr` header.
2047    pub fn chat_group_member_fingerprints(&self) -> Vec<Fingerprint> {
2048        if let Some(header) = self.get_header(HeaderDef::ChatGroupMemberFpr) {
2049            header
2050                .split_ascii_whitespace()
2051                .filter_map(|fpr| Fingerprint::from_str(fpr).ok())
2052                .collect()
2053        } else {
2054            Vec::new()
2055        }
2056    }
2057}
2058
2059fn rm_legacy_display_elements(text: &str) -> String {
2060    let mut res = None;
2061    for l in text.lines() {
2062        res = res.map(|r: String| match r.is_empty() {
2063            true => l.to_string(),
2064            false => r + "\r\n" + l,
2065        });
2066        if l.is_empty() {
2067            res = Some(String::new());
2068        }
2069    }
2070    res.unwrap_or_default()
2071}
2072
2073fn remove_header(
2074    headers: &mut HashMap<String, String>,
2075    key: &str,
2076    removed: &mut HashSet<String>,
2077) -> Option<String> {
2078    if let Some((k, v)) = headers.remove_entry(key) {
2079        removed.insert(k);
2080        Some(v)
2081    } else {
2082        None
2083    }
2084}
2085
2086/// Parses `Autocrypt-Gossip` headers from the email,
2087/// saves the keys into the `public_keys` table,
2088/// and returns them in a HashMap<address, public key>.
2089///
2090/// * `from`: The address which sent the message currently being parsed
2091async fn parse_gossip_headers(
2092    context: &Context,
2093    from: &str,
2094    recipients: &[SingleInfo],
2095    gossip_headers: Vec<String>,
2096) -> Result<BTreeMap<String, GossipedKey>> {
2097    // XXX split the parsing from the modification part
2098    let mut gossiped_keys: BTreeMap<String, GossipedKey> = Default::default();
2099
2100    for value in &gossip_headers {
2101        let header = match Aheader::from_str(value) {
2102            Ok(header) => header,
2103            Err(err) => {
2104                warn!(context, "Failed parsing Autocrypt-Gossip header: {}", err);
2105                continue;
2106            }
2107        };
2108
2109        if !recipients
2110            .iter()
2111            .any(|info| addr_cmp(&info.addr, &header.addr))
2112        {
2113            warn!(
2114                context,
2115                "Ignoring gossiped \"{}\" as the address is not in To/Cc list.", &header.addr,
2116            );
2117            continue;
2118        }
2119        if addr_cmp(from, &header.addr) {
2120            // Non-standard, might not be necessary to have this check here
2121            warn!(
2122                context,
2123                "Ignoring gossiped \"{}\" as it equals the From address", &header.addr,
2124            );
2125            continue;
2126        }
2127
2128        import_public_key(context, &header.public_key)
2129            .await
2130            .context("Failed to import Autocrypt-Gossip key")?;
2131
2132        let gossiped_key = GossipedKey {
2133            public_key: header.public_key,
2134
2135            verified: header.verified,
2136        };
2137        gossiped_keys.insert(header.addr.to_lowercase(), gossiped_key);
2138    }
2139
2140    Ok(gossiped_keys)
2141}
2142
2143/// Message Disposition Notification (RFC 8098)
2144#[derive(Debug)]
2145pub(crate) struct Report {
2146    /// Original-Message-ID header
2147    ///
2148    /// It MUST be present if the original message has a Message-ID according to RFC 8098.
2149    /// In case we can't find it (shouldn't happen), this is None.
2150    pub original_message_id: Option<String>,
2151    /// Additional-Message-IDs
2152    pub additional_message_ids: Vec<String>,
2153}
2154
2155/// Delivery Status Notification (RFC 3464, RFC 6533)
2156#[derive(Debug)]
2157pub(crate) struct DeliveryReport {
2158    pub rfc724_mid: String,
2159    pub failure: bool,
2160}
2161
2162pub(crate) fn parse_message_ids(ids: &str) -> Vec<String> {
2163    // take care with mailparse::msgidparse() that is pretty untolerant eg. wrt missing `<` or `>`
2164    let mut msgids = Vec::new();
2165    for id in ids.split_whitespace() {
2166        let mut id = id.to_string();
2167        if let Some(id_without_prefix) = id.strip_prefix('<') {
2168            id = id_without_prefix.to_string();
2169        };
2170        if let Some(id_without_suffix) = id.strip_suffix('>') {
2171            id = id_without_suffix.to_string();
2172        };
2173        if !id.is_empty() {
2174            msgids.push(id);
2175        }
2176    }
2177    msgids
2178}
2179
2180pub(crate) fn parse_message_id(ids: &str) -> Result<String> {
2181    if let Some(id) = parse_message_ids(ids).first() {
2182        Ok(id.to_string())
2183    } else {
2184        bail!("could not parse message_id: {ids}");
2185    }
2186}
2187
2188/// Returns whether the outer header value must be ignored if the message contains a signed (and
2189/// optionally encrypted) part. This is independent from the modern Header Protection defined in
2190/// <https://www.rfc-editor.org/rfc/rfc9788.html>.
2191fn is_protected(key: &str) -> bool {
2192    key.starts_with("chat-")
2193        || matches!(
2194            key,
2195            "return-path"
2196                | "auto-submitted"
2197                | "autocrypt-setup-message"
2198                | "date"
2199                | "from"
2200                | "sender"
2201                | "reply-to"
2202                | "to"
2203                | "cc"
2204                | "bcc"
2205                | "message-id"
2206                | "in-reply-to"
2207                | "references"
2208                | "secure-join"
2209        )
2210}
2211
2212/// Returns if the header is hidden and must be ignored in the IMF section.
2213pub(crate) fn is_hidden(key: &str) -> bool {
2214    matches!(
2215        key,
2216        "chat-user-avatar" | "chat-group-avatar" | "chat-delete" | "chat-edit"
2217    )
2218}
2219
2220/// Parsed MIME part.
2221#[derive(Debug, Default, Clone)]
2222pub struct Part {
2223    /// Type of the MIME part determining how it should be displayed.
2224    pub typ: Viewtype,
2225
2226    /// MIME type.
2227    pub mimetype: Option<Mime>,
2228
2229    /// Message text to be displayed in the chat.
2230    pub msg: String,
2231
2232    /// Message text to be displayed in message info.
2233    pub msg_raw: Option<String>,
2234
2235    /// Size of the MIME part in bytes.
2236    pub bytes: usize,
2237
2238    /// Parameters.
2239    pub param: Params,
2240
2241    /// Attachment filename.
2242    pub(crate) org_filename: Option<String>,
2243
2244    /// An error detected during parsing.
2245    pub error: Option<String>,
2246
2247    /// True if conversion from HTML to plaintext failed.
2248    pub(crate) dehtml_failed: bool,
2249
2250    /// the part is a child or a descendant of multipart/related.
2251    /// typically, these are images that are referenced from text/html part
2252    /// and should not displayed inside chat.
2253    ///
2254    /// note that multipart/related may contain further multipart nestings
2255    /// and all of them needs to be marked with `is_related`.
2256    pub(crate) is_related: bool,
2257
2258    /// Part is an RFC 9078 reaction.
2259    pub(crate) is_reaction: bool,
2260}
2261
2262/// Returns the mimetype and viewtype for a parsed mail.
2263///
2264/// This only looks at the metadata, not at the content;
2265/// the viewtype may later be corrected in `do_add_single_file_part()`.
2266fn get_mime_type(
2267    mail: &mailparse::ParsedMail<'_>,
2268    filename: &Option<String>,
2269    is_chat_msg: bool,
2270) -> Result<(Mime, Viewtype)> {
2271    let mimetype = mail.ctype.mimetype.parse::<Mime>()?;
2272
2273    let viewtype = match mimetype.type_() {
2274        mime::TEXT => match mimetype.subtype() {
2275            mime::VCARD => Viewtype::Vcard,
2276            mime::PLAIN | mime::HTML if !is_attachment_disposition(mail) => Viewtype::Text,
2277            _ => Viewtype::File,
2278        },
2279        mime::IMAGE => match mimetype.subtype() {
2280            mime::GIF => Viewtype::Gif,
2281            mime::SVG => Viewtype::File,
2282            _ => Viewtype::Image,
2283        },
2284        mime::AUDIO => Viewtype::Audio,
2285        mime::VIDEO => Viewtype::Video,
2286        mime::MULTIPART => Viewtype::Unknown,
2287        mime::MESSAGE => {
2288            if is_attachment_disposition(mail) {
2289                Viewtype::File
2290            } else {
2291                // Enacapsulated messages, see <https://www.w3.org/Protocols/rfc1341/7_3_Message.html>
2292                // Also used as part "message/disposition-notification" of "multipart/report", which, however, will
2293                // be handled separately.
2294                // I've not seen any messages using this, so we do not attach these parts (maybe they're used to attach replies,
2295                // which are unwanted at all).
2296                // For now, we skip these parts at all; if desired, we could return DcMimeType::File/DC_MSG_File
2297                // for selected and known subparts.
2298                Viewtype::Unknown
2299            }
2300        }
2301        mime::APPLICATION => match mimetype.subtype() {
2302            mime::OCTET_STREAM => match filename {
2303                Some(filename) if !is_chat_msg => {
2304                    match message::guess_msgtype_from_path_suffix(Path::new(&filename)) {
2305                        Some((viewtype, _)) => viewtype,
2306                        None => Viewtype::File,
2307                    }
2308                }
2309                _ => Viewtype::File,
2310            },
2311            _ => Viewtype::File,
2312        },
2313        _ => Viewtype::Unknown,
2314    };
2315
2316    Ok((mimetype, viewtype))
2317}
2318
2319fn is_attachment_disposition(mail: &mailparse::ParsedMail<'_>) -> bool {
2320    let ct = mail.get_content_disposition();
2321    ct.disposition == DispositionType::Attachment
2322        && ct
2323            .params
2324            .iter()
2325            .any(|(key, _value)| key.starts_with("filename"))
2326}
2327
2328/// Tries to get attachment filename.
2329///
2330/// If filename is explicitly specified in Content-Disposition, it is
2331/// returned. If Content-Disposition is "attachment" but filename is
2332/// not specified, filename is guessed. If Content-Disposition cannot
2333/// be parsed, returns an error.
2334fn get_attachment_filename(
2335    context: &Context,
2336    mail: &mailparse::ParsedMail,
2337) -> Result<Option<String>> {
2338    let ct = mail.get_content_disposition();
2339
2340    // try to get file name as "encoded-words" from
2341    // `Content-Disposition: ... filename=...`
2342    let mut desired_filename = ct.params.get("filename").map(|s| s.to_string());
2343
2344    if desired_filename.is_none()
2345        && let Some(name) = ct.params.get("filename*").map(|s| s.to_string())
2346    {
2347        // be graceful and just use the original name.
2348        // some MUA, including Delta Chat up to core1.50,
2349        // use `filename*` mistakenly for simple encoded-words without following rfc2231
2350        warn!(context, "apostrophed encoding invalid: {}", name);
2351        desired_filename = Some(name);
2352    }
2353
2354    // if no filename is set, try `Content-Disposition: ... name=...`
2355    if desired_filename.is_none() {
2356        desired_filename = ct.params.get("name").map(|s| s.to_string());
2357    }
2358
2359    // MS Outlook is known to specify filename in the "name" attribute of
2360    // Content-Type and omit Content-Disposition.
2361    if desired_filename.is_none() {
2362        desired_filename = mail.ctype.params.get("name").map(|s| s.to_string());
2363    }
2364
2365    // If there is no filename, but part is an attachment, guess filename
2366    if desired_filename.is_none() && ct.disposition == DispositionType::Attachment {
2367        if let Some(subtype) = mail.ctype.mimetype.split('/').nth(1) {
2368            desired_filename = Some(format!("file.{subtype}",));
2369        } else {
2370            bail!(
2371                "could not determine attachment filename: {:?}",
2372                ct.disposition
2373            );
2374        };
2375    }
2376
2377    let desired_filename = desired_filename.map(|filename| sanitize_bidi_characters(&filename));
2378
2379    Ok(desired_filename)
2380}
2381
2382/// Returned addresses are normalized and lowercased.
2383pub(crate) fn get_recipients(headers: &[MailHeader]) -> Vec<SingleInfo> {
2384    let to_addresses = get_all_addresses_from_header(headers, "to");
2385    let cc_addresses = get_all_addresses_from_header(headers, "cc");
2386
2387    let mut res = to_addresses;
2388    res.extend(cc_addresses);
2389    res
2390}
2391
2392/// Returned addresses are normalized and lowercased.
2393pub(crate) fn get_from(headers: &[MailHeader]) -> Option<SingleInfo> {
2394    let all = get_all_addresses_from_header(headers, "from");
2395    tools::single_value(all)
2396}
2397
2398/// Returned addresses are normalized and lowercased.
2399pub(crate) fn get_list_post(headers: &[MailHeader]) -> Option<String> {
2400    get_all_addresses_from_header(headers, "list-post")
2401        .into_iter()
2402        .next()
2403        .map(|s| s.addr)
2404}
2405
2406/// Extracts all addresses from the header named `header`.
2407///
2408/// If multiple headers with the same name are present,
2409/// the last one is taken.
2410/// This is because DKIM-Signatures apply to the last
2411/// headers, and more headers may be added
2412/// to the beginning of the messages
2413/// without invalidating the signature
2414/// unless the header is "oversigned",
2415/// i.e. included in the signature more times
2416/// than it appears in the mail.
2417fn get_all_addresses_from_header(headers: &[MailHeader], header: &str) -> Vec<SingleInfo> {
2418    let mut result: Vec<SingleInfo> = Default::default();
2419
2420    if let Some(header) = headers
2421        .iter()
2422        .rev()
2423        .find(|h| h.get_key().to_lowercase() == header)
2424        && let Ok(addrs) = mailparse::addrparse_header(header)
2425    {
2426        for addr in addrs.iter() {
2427            match addr {
2428                mailparse::MailAddr::Single(info) => {
2429                    result.push(SingleInfo {
2430                        addr: addr_normalize(&info.addr).to_lowercase(),
2431                        display_name: info.display_name.clone(),
2432                    });
2433                }
2434                mailparse::MailAddr::Group(infos) => {
2435                    for info in &infos.addrs {
2436                        result.push(SingleInfo {
2437                            addr: addr_normalize(&info.addr).to_lowercase(),
2438                            display_name: info.display_name.clone(),
2439                        });
2440                    }
2441                }
2442            }
2443        }
2444    }
2445
2446    result
2447}
2448
2449async fn handle_mdn(
2450    context: &Context,
2451    from_id: ContactId,
2452    rfc724_mid: &str,
2453    timestamp_sent: i64,
2454) -> Result<()> {
2455    if from_id == ContactId::SELF {
2456        // MDNs to self are handled in receive_imf_inner().
2457        return Ok(());
2458    }
2459
2460    let Some((msg_id, chat_id, has_mdns, is_dup)) = context
2461        .sql
2462        .query_row_optional(
2463            "SELECT
2464                m.id AS msg_id,
2465                c.id AS chat_id,
2466                mdns.contact_id AS mdn_contact
2467             FROM msgs m 
2468             LEFT JOIN chats c ON m.chat_id=c.id
2469             LEFT JOIN msgs_mdns mdns ON mdns.msg_id=m.id
2470             WHERE rfc724_mid=? AND from_id=1
2471             ORDER BY msg_id DESC, mdn_contact=? DESC
2472             LIMIT 1",
2473            (&rfc724_mid, from_id),
2474            |row| {
2475                let msg_id: MsgId = row.get("msg_id")?;
2476                let chat_id: ChatId = row.get("chat_id")?;
2477                let mdn_contact: Option<ContactId> = row.get("mdn_contact")?;
2478                Ok((
2479                    msg_id,
2480                    chat_id,
2481                    mdn_contact.is_some(),
2482                    mdn_contact == Some(from_id),
2483                ))
2484            },
2485        )
2486        .await?
2487    else {
2488        info!(
2489            context,
2490            "Ignoring MDN, found no message with Message-ID {rfc724_mid:?} sent by us in the database.",
2491        );
2492        return Ok(());
2493    };
2494
2495    if is_dup {
2496        return Ok(());
2497    }
2498    context
2499        .sql
2500        .execute(
2501            "INSERT INTO msgs_mdns (msg_id, contact_id, timestamp_sent) VALUES (?, ?, ?)",
2502            (msg_id, from_id, timestamp_sent),
2503        )
2504        .await?;
2505    if !has_mdns {
2506        context.emit_event(EventType::MsgRead { chat_id, msg_id });
2507        // note(treefit): only matters if it is the last message in chat (but probably too expensive to check, debounce also solves it)
2508        chatlist_events::emit_chatlist_item_changed(context, chat_id);
2509    }
2510    Ok(())
2511}
2512
2513/// Marks a message as failed after an ndn (non-delivery-notification) arrived.
2514/// Where appropriate, also adds an info message telling the user which of the recipients of a group message failed.
2515async fn handle_ndn(
2516    context: &Context,
2517    failed: &DeliveryReport,
2518    error: Option<String>,
2519) -> Result<()> {
2520    if failed.rfc724_mid.is_empty() {
2521        return Ok(());
2522    }
2523
2524    // The NDN might be for a message-id that had attachments and was sent from a non-Delta Chat client.
2525    // In this case we need to mark multiple "msgids" as failed that all refer to the same message-id.
2526    let msg_ids = context
2527        .sql
2528        .query_map_vec(
2529            "SELECT id FROM msgs
2530                WHERE rfc724_mid=? AND from_id=1",
2531            (&failed.rfc724_mid,),
2532            |row| {
2533                let msg_id: MsgId = row.get(0)?;
2534                Ok(msg_id)
2535            },
2536        )
2537        .await?;
2538
2539    let error = if let Some(error) = error {
2540        error
2541    } else {
2542        "Delivery to at least one recipient failed.".to_string()
2543    };
2544    let err_msg = &error;
2545
2546    for msg_id in msg_ids {
2547        let mut message = Message::load_from_db(context, msg_id).await?;
2548        let chat = Chat::load_from_db(context, message.chat_id).await?;
2549        if chat.typ == constants::Chattype::OutBroadcast {
2550            continue;
2551        }
2552        let aggregated_error = message
2553            .error
2554            .as_ref()
2555            .map(|err| format!("{err}\n\n{err_msg}"));
2556        set_msg_failed(
2557            context,
2558            &mut message,
2559            aggregated_error.as_ref().unwrap_or(err_msg),
2560        )
2561        .await?;
2562    }
2563
2564    Ok(())
2565}
2566
2567#[cfg(test)]
2568mod mimeparser_tests;
2569#[cfg(test)]
2570mod shared_secret_decryption_tests;