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