deltachat/
mimefactory.rs

1//! # MIME message production.
2
3use std::collections::{BTreeSet, HashSet};
4use std::io::Cursor;
5
6use anyhow::{Context as _, Result, bail, ensure};
7use base64::Engine as _;
8use deltachat_contact_tools::sanitize_bidi_characters;
9use mail_builder::headers::HeaderType;
10use mail_builder::headers::address::{Address, EmailAddress};
11use mail_builder::mime::MimePart;
12use tokio::fs;
13
14use crate::aheader::{Aheader, EncryptPreference};
15use crate::blob::BlobObject;
16use crate::chat::{self, Chat};
17use crate::config::Config;
18use crate::constants::ASM_SUBJECT;
19use crate::constants::{Chattype, DC_FROM_HANDSHAKE};
20use crate::contact::{Contact, ContactId, Origin};
21use crate::context::Context;
22use crate::e2ee::EncryptHelper;
23use crate::ephemeral::Timer as EphemeralTimer;
24use crate::key::self_fingerprint;
25use crate::key::{DcKey, SignedPublicKey};
26use crate::location;
27use crate::log::{info, warn};
28use crate::message::{Message, MsgId, Viewtype};
29use crate::mimeparser::{SystemMessage, is_hidden};
30use crate::param::Param;
31use crate::peer_channels::create_iroh_header;
32use crate::simplify::escape_message_footer_marks;
33use crate::stock_str;
34use crate::tools::{
35    IsNoneOrEmpty, create_outgoing_rfc724_mid, create_smeared_timestamp, remove_subject_prefix,
36    time,
37};
38use crate::webxdc::StatusUpdateSerial;
39
40// attachments of 25 mb brutto should work on the majority of providers
41// (brutto examples: web.de=50, 1&1=40, t-online.de=32, gmail=25, posteo=50, yahoo=25, all-inkl=100).
42// to get the netto sizes, we subtract 1 mb header-overhead and the base64-overhead.
43pub const RECOMMENDED_FILE_SIZE: u64 = 24 * 1024 * 1024 / 4 * 3;
44
45#[derive(Debug, Clone)]
46#[expect(clippy::large_enum_variant)]
47pub enum Loaded {
48    Message {
49        chat: Chat,
50        msg: Message,
51    },
52    Mdn {
53        rfc724_mid: String,
54        additional_msg_ids: Vec<String>,
55    },
56}
57
58/// Helper to construct mime messages.
59#[derive(Debug, Clone)]
60pub struct MimeFactory {
61    from_addr: String,
62    from_displayname: String,
63
64    /// Goes to the `Sender:`-header, if set.
65    /// For overridden names, `sender_displayname` is set to the
66    /// config-name while `from_displayname` is set to the overridden name.
67    /// From the perspective of the receiver,
68    /// a set `Sender:`-header is used as an indicator that the name is overridden;
69    /// names are alsways read from the `From:`-header.
70    sender_displayname: Option<String>,
71
72    selfstatus: String,
73
74    /// Vector of actual recipient addresses.
75    ///
76    /// This is the list of addresses the message should be sent to.
77    /// It is not the same as the `To` header,
78    /// because in case of "member removed" message
79    /// removed member is in the recipient list,
80    /// but not in the `To` header.
81    /// In case of broadcast channels there are multiple recipients,
82    /// but the `To` header has no members.
83    ///
84    /// If `bcc_self` configuration is enabled,
85    /// this list will be extended with own address later,
86    /// but `MimeFactory` is not responsible for this.
87    recipients: Vec<String>,
88
89    /// Vector of pairs of recipient
90    /// addresses and OpenPGP keys
91    /// to use for encryption.
92    ///
93    /// `None` if the message is not encrypted.
94    encryption_keys: Option<Vec<(String, SignedPublicKey)>>,
95
96    /// Vector of pairs of recipient name and address that goes into the `To` field.
97    ///
98    /// The list of actual message recipient addresses may be different,
99    /// e.g. if members are hidden for broadcast channels
100    /// or if the keys for some recipients are missing
101    /// and encrypted message cannot be sent to them.
102    to: Vec<(String, String)>,
103
104    /// Vector of pairs of past group member names and addresses.
105    past_members: Vec<(String, String)>,
106
107    /// Fingerprints of the members in the same order as in the `to`
108    /// followed by `past_members`.
109    ///
110    /// If this is not empty, its length
111    /// should be the sum of `to` and `past_members` length.
112    member_fingerprints: Vec<String>,
113
114    /// Timestamps of the members in the same order as in the `to`
115    /// followed by `past_members`.
116    ///
117    /// If this is not empty, its length
118    /// should be the sum of `to` and `past_members` length.
119    member_timestamps: Vec<i64>,
120
121    timestamp: i64,
122    loaded: Loaded,
123    in_reply_to: String,
124
125    /// List of Message-IDs for `References` header.
126    references: Vec<String>,
127
128    /// True if the message requests Message Disposition Notification
129    /// using `Chat-Disposition-Notification-To` header.
130    req_mdn: bool,
131
132    last_added_location_id: Option<u32>,
133
134    /// If the created mime-structure contains sync-items,
135    /// the IDs of these items are listed here.
136    /// The IDs are returned via `RenderedEmail`
137    /// and must be deleted if the message is actually queued for sending.
138    sync_ids_to_delete: Option<String>,
139
140    /// True if the avatar should be attached.
141    pub attach_selfavatar: bool,
142}
143
144/// Result of rendering a message, ready to be submitted to a send job.
145#[derive(Debug, Clone)]
146pub struct RenderedEmail {
147    pub message: String,
148    // pub envelope: Envelope,
149    pub is_encrypted: bool,
150    pub last_added_location_id: Option<u32>,
151
152    /// A comma-separated string of sync-IDs that are used by the rendered email and must be deleted
153    /// from `multi_device_sync` once the message is actually queued for sending.
154    pub sync_ids_to_delete: Option<String>,
155
156    /// Message ID (Message in the sense of Email)
157    pub rfc724_mid: String,
158
159    /// Message subject.
160    pub subject: String,
161}
162
163fn new_address_with_name(name: &str, address: String) -> Address<'static> {
164    Address::new_address(
165        if name == address || name.is_empty() {
166            None
167        } else {
168            Some(name.to_string())
169        },
170        address,
171    )
172}
173
174impl MimeFactory {
175    pub async fn from_msg(context: &Context, msg: Message) -> Result<MimeFactory> {
176        let now = time();
177        let chat = Chat::load_from_db(context, msg.chat_id).await?;
178        let attach_profile_data = Self::should_attach_profile_data(&msg);
179        let undisclosed_recipients = chat.typ == Chattype::OutBroadcast;
180
181        let from_addr = context.get_primary_self_addr().await?;
182        let config_displayname = context
183            .get_config(Config::Displayname)
184            .await?
185            .unwrap_or_default();
186        let (from_displayname, sender_displayname) =
187            if let Some(override_name) = msg.param.get(Param::OverrideSenderDisplayname) {
188                (override_name.to_string(), Some(config_displayname))
189            } else {
190                let name = match attach_profile_data {
191                    true => config_displayname,
192                    false => "".to_string(),
193                };
194                (name, None)
195            };
196
197        let mut recipients = Vec::new();
198        let mut to = Vec::new();
199        let mut past_members = Vec::new();
200        let mut member_fingerprints = Vec::new();
201        let mut member_timestamps = Vec::new();
202        let mut recipient_ids = HashSet::new();
203        let mut req_mdn = false;
204
205        let encryption_keys;
206
207        let self_fingerprint = self_fingerprint(context).await?;
208
209        if chat.is_self_talk() {
210            to.push((from_displayname.to_string(), from_addr.to_string()));
211
212            encryption_keys = if msg.param.get_bool(Param::ForcePlaintext).unwrap_or(false) {
213                None
214            } else {
215                // Encrypt, but only to self.
216                Some(Vec::new())
217            };
218        } else if chat.is_mailing_list() {
219            let list_post = chat
220                .param
221                .get(Param::ListPost)
222                .context("Can't write to mailinglist without ListPost param")?;
223            to.push(("".to_string(), list_post.to_string()));
224            recipients.push(list_post.to_string());
225
226            // Do not encrypt messages to mailing lists.
227            encryption_keys = None;
228        } else {
229            let email_to_remove = if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
230                msg.param.get(Param::Arg)
231            } else {
232                None
233            };
234
235            let is_encrypted = if msg
236                .param
237                .get_bool(Param::ForcePlaintext)
238                .unwrap_or_default()
239            {
240                false
241            } else {
242                msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
243                    || chat.is_encrypted(context).await?
244            };
245
246            let mut keys = Vec::new();
247            let mut missing_key_addresses = BTreeSet::new();
248            context
249                .sql
250                .query_map(
251                    "SELECT
252                     c.authname,
253                     c.addr,
254                     c.fingerprint,
255                     c.id,
256                     cc.add_timestamp,
257                     cc.remove_timestamp,
258                     k.public_key
259                     FROM chats_contacts cc
260                     LEFT JOIN contacts c ON cc.contact_id=c.id
261                     LEFT JOIN public_keys k ON k.fingerprint=c.fingerprint
262                     WHERE cc.chat_id=?
263                     AND (cc.contact_id>9 OR (cc.contact_id=1 AND ?))",
264                    (msg.chat_id, chat.typ == Chattype::Group),
265                    |row| {
266                        let authname: String = row.get(0)?;
267                        let addr: String = row.get(1)?;
268                        let fingerprint: String = row.get(2)?;
269                        let id: ContactId = row.get(3)?;
270                        let add_timestamp: i64 = row.get(4)?;
271                        let remove_timestamp: i64 = row.get(5)?;
272                        let public_key_bytes_opt: Option<Vec<u8>> = row.get(6)?;
273                        Ok((authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt))
274                    },
275                    |rows| {
276                        let mut past_member_timestamps = Vec::new();
277                        let mut past_member_fingerprints = Vec::new();
278
279                        for row in rows {
280                            let (authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt) = row?;
281
282                            let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
283                                Some(SignedPublicKey::from_slice(public_key_bytes)?)
284                            } else {
285                                None
286                            };
287
288                            let addr = if id == ContactId::SELF {
289                                from_addr.to_string()
290                            } else {
291                                addr
292                            };
293                            let name = match attach_profile_data {
294                                true => authname,
295                                false => "".to_string(),
296                            };
297                            if add_timestamp >= remove_timestamp {
298                                if !recipients_contain_addr(&to, &addr) {
299                                    if id != ContactId::SELF {
300                                        recipients.push(addr.clone());
301                                    }
302                                    if !undisclosed_recipients {
303                                        to.push((name, addr.clone()));
304
305                                        if is_encrypted {
306                                            if !fingerprint.is_empty() {
307                                                member_fingerprints.push(fingerprint);
308                                            } else if id == ContactId::SELF {
309                                                member_fingerprints.push(self_fingerprint.to_string());
310                                            } else {
311                                                debug_assert!(member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
312                                            }
313                                        }
314                                        member_timestamps.push(add_timestamp);
315                                    }
316                                }
317                                recipient_ids.insert(id);
318
319                                if let Some(public_key) = public_key_opt {
320                                    keys.push((addr.clone(), public_key))
321                                } else if id != ContactId::SELF {
322                                    missing_key_addresses.insert(addr.clone());
323                                    if is_encrypted {
324                                        warn!(context, "Missing key for {addr}");
325                                    }
326                                }
327                            } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
328                                // Row is a tombstone,
329                                // member is not actually part of the group.
330                                if !recipients_contain_addr(&past_members, &addr) {
331                                    if let Some(email_to_remove) = email_to_remove {
332                                        if email_to_remove == addr {
333                                            // This is a "member removed" message,
334                                            // we need to notify removed member
335                                            // that it was removed.
336                                            if id != ContactId::SELF {
337                                                recipients.push(addr.clone());
338                                            }
339
340                                            if let Some(public_key) = public_key_opt {
341                                                keys.push((addr.clone(), public_key))
342                                            } else if id != ContactId::SELF {
343                                                missing_key_addresses.insert(addr.clone());
344                                                if is_encrypted {
345                                                    warn!(context, "Missing key for {addr}");
346                                                }
347                                            }
348                                        }
349                                    }
350                                    if !undisclosed_recipients {
351                                        past_members.push((name, addr.clone()));
352                                        past_member_timestamps.push(remove_timestamp);
353
354                                        if is_encrypted {
355                                            if !fingerprint.is_empty() {
356                                                past_member_fingerprints.push(fingerprint);
357                                            } else if id == ContactId::SELF {
358                                                // It's fine to have self in past members
359                                                // if we are leaving the group.
360                                                past_member_fingerprints.push(self_fingerprint.to_string());
361                                            } else {
362                                                debug_assert!(past_member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
363                                            }
364                                        }
365                                    }
366                                }
367                            }
368                        }
369
370                        debug_assert!(member_timestamps.len() >= to.len());
371                        debug_assert!(member_fingerprints.is_empty() || member_fingerprints.len() >= to.len());
372
373                        if to.len() > 1 {
374                            if let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
375                                to.remove(position);
376                                member_timestamps.remove(position);
377                                if is_encrypted {
378                                    member_fingerprints.remove(position);
379                                }
380                            }
381                        }
382
383                        member_timestamps.extend(past_member_timestamps);
384                        if is_encrypted {
385                            member_fingerprints.extend(past_member_fingerprints);
386                        }
387                        Ok(())
388                    },
389                )
390                .await?;
391            let recipient_ids: Vec<_> = recipient_ids.into_iter().collect();
392            ContactId::scaleup_origin(context, &recipient_ids, Origin::OutgoingTo).await?;
393
394            if !msg.is_system_message()
395                && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
396                && context.should_request_mdns().await?
397            {
398                req_mdn = true;
399            }
400
401            encryption_keys = if !is_encrypted {
402                None
403            } else {
404                if keys.is_empty() && !recipients.is_empty() {
405                    bail!(
406                        "No recipient keys are available, cannot encrypt to {:?}.",
407                        recipients
408                    );
409                }
410
411                // Remove recipients for which the key is missing.
412                if !missing_key_addresses.is_empty() {
413                    recipients.retain(|addr| !missing_key_addresses.contains(addr));
414                }
415
416                Some(keys)
417            };
418        }
419
420        let (in_reply_to, references) = context
421            .sql
422            .query_row(
423                "SELECT mime_in_reply_to, IFNULL(mime_references, '')
424                 FROM msgs WHERE id=?",
425                (msg.id,),
426                |row| {
427                    let in_reply_to: String = row.get(0)?;
428                    let references: String = row.get(1)?;
429
430                    Ok((in_reply_to, references))
431                },
432            )
433            .await?;
434        let references: Vec<String> = references
435            .trim()
436            .split_ascii_whitespace()
437            .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
438            .collect();
439        let selfstatus = match attach_profile_data {
440            true => context
441                .get_config(Config::Selfstatus)
442                .await?
443                .unwrap_or_default(),
444            false => "".to_string(),
445        };
446        let attach_selfavatar = Self::should_attach_selfavatar(context, &msg).await;
447
448        debug_assert!(
449            member_timestamps.is_empty()
450                || to.len() + past_members.len() == member_timestamps.len()
451        );
452
453        let factory = MimeFactory {
454            from_addr,
455            from_displayname,
456            sender_displayname,
457            selfstatus,
458            recipients,
459            encryption_keys,
460            to,
461            past_members,
462            member_fingerprints,
463            member_timestamps,
464            timestamp: msg.timestamp_sort,
465            loaded: Loaded::Message { msg, chat },
466            in_reply_to,
467            references,
468            req_mdn,
469            last_added_location_id: None,
470            sync_ids_to_delete: None,
471            attach_selfavatar,
472        };
473        Ok(factory)
474    }
475
476    pub async fn from_mdn(
477        context: &Context,
478        from_id: ContactId,
479        rfc724_mid: String,
480        additional_msg_ids: Vec<String>,
481    ) -> Result<MimeFactory> {
482        let contact = Contact::get_by_id(context, from_id).await?;
483        let from_addr = context.get_primary_self_addr().await?;
484        let timestamp = create_smeared_timestamp(context);
485
486        let addr = contact.get_addr().to_string();
487        let encryption_keys = if contact.is_key_contact() {
488            if let Some(key) = contact.public_key(context).await? {
489                Some(vec![(addr.clone(), key)])
490            } else {
491                Some(Vec::new())
492            }
493        } else {
494            None
495        };
496
497        let res = MimeFactory {
498            from_addr,
499            from_displayname: "".to_string(),
500            sender_displayname: None,
501            selfstatus: "".to_string(),
502            recipients: vec![addr],
503            encryption_keys,
504            to: vec![("".to_string(), contact.get_addr().to_string())],
505            past_members: vec![],
506            member_fingerprints: vec![],
507            member_timestamps: vec![],
508            timestamp,
509            loaded: Loaded::Mdn {
510                rfc724_mid,
511                additional_msg_ids,
512            },
513            in_reply_to: String::default(),
514            references: Vec::new(),
515            req_mdn: false,
516            last_added_location_id: None,
517            sync_ids_to_delete: None,
518            attach_selfavatar: false,
519        };
520
521        Ok(res)
522    }
523
524    fn should_skip_autocrypt(&self) -> bool {
525        match &self.loaded {
526            Loaded::Message { msg, .. } => {
527                msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
528            }
529            Loaded::Mdn { .. } => false,
530        }
531    }
532
533    fn should_attach_profile_data(msg: &Message) -> bool {
534        msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
535            let step = msg.param.get(Param::Arg).unwrap_or_default();
536            // Don't attach profile data at the earlier SecureJoin steps:
537            // - The corresponding messages, i.e. "v{c,g}-request" and "v{c,g}-auth-required" are
538            //   deleted right after processing, so other devices won't see the avatar etc.
539            // - It's also good for privacy because the contact isn't yet verified and these
540            //   messages are auto-sent unlike usual unencrypted messages.
541            step == "vg-request-with-auth"
542                || step == "vc-request-with-auth"
543                || step == "vg-member-added"
544                || step == "vc-contact-confirm"
545        }
546    }
547
548    async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
549        Self::should_attach_profile_data(msg)
550            && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
551                Ok(should) => should,
552                Err(err) => {
553                    warn!(
554                        context,
555                        "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
556                    );
557                    false
558                }
559            }
560    }
561
562    fn grpimage(&self) -> Option<String> {
563        match &self.loaded {
564            Loaded::Message { chat, msg } => {
565                let cmd = msg.param.get_cmd();
566
567                match cmd {
568                    SystemMessage::MemberAddedToGroup => {
569                        return chat.param.get(Param::ProfileImage).map(Into::into);
570                    }
571                    SystemMessage::GroupImageChanged => {
572                        return msg.param.get(Param::Arg).map(Into::into);
573                    }
574                    _ => {}
575                }
576
577                if msg
578                    .param
579                    .get_bool(Param::AttachGroupImage)
580                    .unwrap_or_default()
581                {
582                    return chat.param.get(Param::ProfileImage).map(Into::into);
583                }
584
585                None
586            }
587            Loaded::Mdn { .. } => None,
588        }
589    }
590
591    async fn subject_str(&self, context: &Context) -> Result<String> {
592        let subject = match &self.loaded {
593            Loaded::Message { chat, msg } => {
594                let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
595
596                if !msg.subject.is_empty() {
597                    return Ok(msg.subject.clone());
598                }
599
600                if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
601                    && quoted_msg_subject.is_none_or_empty()
602                {
603                    let re = if self.in_reply_to.is_empty() {
604                        ""
605                    } else {
606                        "Re: "
607                    };
608                    return Ok(format!("{}{}", re, chat.name));
609                }
610
611                let parent_subject = if quoted_msg_subject.is_none_or_empty() {
612                    chat.param.get(Param::LastSubject)
613                } else {
614                    quoted_msg_subject.as_deref()
615                };
616                if let Some(last_subject) = parent_subject {
617                    return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
618                }
619
620                let self_name = match Self::should_attach_profile_data(msg) {
621                    true => context.get_config(Config::Displayname).await?,
622                    false => None,
623                };
624                let self_name = &match self_name {
625                    Some(name) => name,
626                    None => context.get_config(Config::Addr).await?.unwrap_or_default(),
627                };
628                stock_str::subject_for_new_contact(context, self_name).await
629            }
630            Loaded::Mdn { .. } => "Receipt Notification".to_string(), // untranslated to no reveal sender's language
631        };
632
633        Ok(subject)
634    }
635
636    pub fn recipients(&self) -> Vec<String> {
637        self.recipients.clone()
638    }
639
640    /// Consumes a `MimeFactory` and renders it into a message which is then stored in
641    /// `smtp`-table to be used by the SMTP loop
642    pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
643        let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
644
645        let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
646
647        let mut to: Vec<Address<'static>> = Vec::new();
648        for (name, addr) in &self.to {
649            to.push(Address::new_address(
650                if name.is_empty() {
651                    None
652                } else {
653                    Some(name.to_string())
654                },
655                addr.clone(),
656            ));
657        }
658
659        let mut past_members: Vec<Address<'static>> = Vec::new(); // Contents of `Chat-Group-Past-Members` header.
660        for (name, addr) in &self.past_members {
661            past_members.push(Address::new_address(
662                if name.is_empty() {
663                    None
664                } else {
665                    Some(name.to_string())
666                },
667                addr.clone(),
668            ));
669        }
670
671        debug_assert!(
672            self.member_timestamps.is_empty()
673                || to.len() + past_members.len() == self.member_timestamps.len()
674        );
675        if to.is_empty() {
676            to.push(hidden_recipients());
677        }
678
679        // Start with Internet Message Format headers in the order of the standard example
680        // <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.1.1>.
681        headers.push(("From", from.into()));
682
683        if let Some(sender_displayname) = &self.sender_displayname {
684            let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
685            headers.push(("Sender", sender.into()));
686        }
687        headers.push((
688            "To",
689            mail_builder::headers::address::Address::new_list(to.clone()).into(),
690        ));
691        if !past_members.is_empty() {
692            headers.push((
693                "Chat-Group-Past-Members",
694                mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
695            ));
696        }
697
698        if let Loaded::Message { chat, .. } = &self.loaded {
699            if chat.typ == Chattype::Group {
700                if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await?
701                {
702                    headers.push((
703                        "Chat-Group-Member-Timestamps",
704                        mail_builder::headers::raw::Raw::new(
705                            self.member_timestamps
706                                .iter()
707                                .map(|ts| ts.to_string())
708                                .collect::<Vec<String>>()
709                                .join(" "),
710                        )
711                        .into(),
712                    ));
713                }
714
715                if !self.member_fingerprints.is_empty() {
716                    headers.push((
717                        "Chat-Group-Member-Fpr",
718                        mail_builder::headers::raw::Raw::new(
719                            self.member_fingerprints
720                                .iter()
721                                .map(|fp| fp.to_string())
722                                .collect::<Vec<String>>()
723                                .join(" "),
724                        )
725                        .into(),
726                    ));
727                }
728            }
729        }
730
731        let subject_str = self.subject_str(context).await?;
732        headers.push((
733            "Subject",
734            mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
735        ));
736
737        let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
738            .unwrap()
739            .to_rfc2822();
740        headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
741
742        let rfc724_mid = match &self.loaded {
743            Loaded::Message { msg, .. } => msg.rfc724_mid.clone(),
744            Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
745        };
746        headers.push((
747            "Message-ID",
748            mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
749        ));
750
751        // Reply headers as in <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.2>.
752        if !self.in_reply_to.is_empty() {
753            headers.push((
754                "In-Reply-To",
755                mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
756            ));
757        }
758        if !self.references.is_empty() {
759            headers.push((
760                "References",
761                mail_builder::headers::message_id::MessageId::<'static>::new_list(
762                    self.references.iter().map(|s| s.to_string()),
763                )
764                .into(),
765            ));
766        }
767
768        // Automatic Response headers <https://www.rfc-editor.org/rfc/rfc3834>
769        if let Loaded::Mdn { .. } = self.loaded {
770            headers.push((
771                "Auto-Submitted",
772                mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
773            ));
774        } else if context.get_config_bool(Config::Bot).await? {
775            headers.push((
776                "Auto-Submitted",
777                mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
778            ));
779        } else if let Loaded::Message { msg, .. } = &self.loaded {
780            if msg.param.get_cmd() == SystemMessage::SecurejoinMessage {
781                let step = msg.param.get(Param::Arg).unwrap_or_default();
782                if step != "vg-request" && step != "vc-request" {
783                    headers.push((
784                        "Auto-Submitted",
785                        mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
786                    ));
787                }
788            }
789        }
790
791        if let Loaded::Message { chat, .. } = &self.loaded {
792            if chat.typ == Chattype::OutBroadcast {
793                headers.push((
794                    "List-ID",
795                    mail_builder::headers::text::Text::new(format!(
796                        "{} <{}>",
797                        chat.name, chat.grpid
798                    ))
799                    .into(),
800                ));
801            }
802        }
803
804        if let Loaded::Message { msg, .. } = &self.loaded {
805            if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
806                headers.push((
807                    "Chat-Edit",
808                    mail_builder::headers::message_id::MessageId::new(
809                        original_rfc724_mid.to_string(),
810                    )
811                    .into(),
812                ));
813            } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
814                headers.push((
815                    "Chat-Delete",
816                    mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
817                        .into(),
818                ));
819            }
820        }
821
822        // Non-standard headers.
823        headers.push((
824            "Chat-Version",
825            mail_builder::headers::raw::Raw::new("1.0").into(),
826        ));
827
828        if self.req_mdn {
829            // we use "Chat-Disposition-Notification-To"
830            // because replies to "Disposition-Notification-To" are weird in many cases
831            // eg. are just freetext and/or do not follow any standard.
832            headers.push((
833                "Chat-Disposition-Notification-To",
834                mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
835            ));
836        }
837
838        let grpimage = self.grpimage();
839        let skip_autocrypt = self.should_skip_autocrypt();
840        let encrypt_helper = EncryptHelper::new(context).await?;
841
842        if !skip_autocrypt {
843            // unless determined otherwise we add the Autocrypt header
844            let aheader = encrypt_helper.get_aheader().to_string();
845            headers.push((
846                "Autocrypt",
847                mail_builder::headers::raw::Raw::new(aheader).into(),
848            ));
849        }
850
851        let is_encrypted = self.encryption_keys.is_some();
852
853        // Add ephemeral timer for non-MDN messages.
854        // For MDNs it does not matter because they are not visible
855        // and ignored by the receiver.
856        if let Loaded::Message { msg, .. } = &self.loaded {
857            let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
858            if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
859                headers.push((
860                    "Ephemeral-Timer",
861                    mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
862                ));
863            }
864        }
865
866        let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
867            msg.param.get_cmd() == SystemMessage::SecurejoinMessage
868        } else {
869            false
870        };
871
872        let message: MimePart<'static> = match &self.loaded {
873            Loaded::Message { msg, .. } => {
874                let msg = msg.clone();
875                let (main_part, mut parts) = self
876                    .render_message(context, &mut headers, &grpimage, is_encrypted)
877                    .await?;
878                if parts.is_empty() {
879                    // Single part, render as regular message.
880                    main_part
881                } else {
882                    parts.insert(0, main_part);
883
884                    // Multiple parts, render as multipart.
885                    if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
886                        MimePart::new("multipart/report; report-type=multi-device-sync", parts)
887                    } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
888                        MimePart::new("multipart/report; report-type=status-update", parts)
889                    } else {
890                        MimePart::new("multipart/mixed", parts)
891                    }
892                }
893            }
894            Loaded::Mdn { .. } => self.render_mdn()?,
895        };
896
897        // Split headers based on header confidentiality policy.
898
899        // Headers that must go into IMF header section.
900        //
901        // These are standard headers such as Date, In-Reply-To, References, which cannot be placed
902        // anywhere else according to the standard. Placing headers here also allows them to be fetched
903        // individually over IMAP without downloading the message body. This is why Chat-Version is
904        // placed here.
905        let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
906
907        // Headers that MUST NOT (only) go into IMF header section:
908        // - Large headers which may hit the header section size limit on the server, such as
909        //   Chat-User-Avatar with a base64-encoded image inside.
910        // - Headers duplicated here that servers mess up with in the IMF header section, like
911        //   Message-ID.
912        // - Nonstandard headers that should be DKIM-protected because e.g. OpenDKIM only signs
913        //   known headers.
914        //
915        // The header should be hidden from MTA
916        // by moving it either into protected part
917        // in case of encrypted mails
918        // or unprotected MIME preamble in case of unencrypted mails.
919        let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
920
921        // Opportunistically protected headers.
922        //
923        // These headers are placed into encrypted part *if* the message is encrypted. Place headers
924        // which are not needed before decryption (e.g. Chat-Group-Name) or are not interesting if the
925        // message cannot be decrypted (e.g. Chat-Disposition-Notification-To) here.
926        //
927        // If the message is not encrypted, these headers are placed into IMF header section, so make
928        // sure that the message will be encrypted if you place any sensitive information here.
929        let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
930
931        // MIME header <https://datatracker.ietf.org/doc/html/rfc2045>.
932        unprotected_headers.push((
933            "MIME-Version",
934            mail_builder::headers::raw::Raw::new("1.0").into(),
935        ));
936        for header @ (original_header_name, _header_value) in &headers {
937            let header_name = original_header_name.to_lowercase();
938            if header_name == "message-id" {
939                unprotected_headers.push(header.clone());
940                hidden_headers.push(header.clone());
941            } else if is_hidden(&header_name) {
942                hidden_headers.push(header.clone());
943            } else if header_name == "autocrypt"
944                && !context.get_config_bool(Config::ProtectAutocrypt).await?
945            {
946                unprotected_headers.push(header.clone());
947            } else if header_name == "from" {
948                // Unencrypted securejoin messages should _not_ include the display name:
949                if is_encrypted || !is_securejoin_message {
950                    protected_headers.push(header.clone());
951                }
952
953                unprotected_headers.push((
954                    original_header_name,
955                    Address::new_address(None::<&'static str>, self.from_addr.clone()).into(),
956                ));
957            } else if header_name == "to" {
958                protected_headers.push(header.clone());
959                if is_encrypted {
960                    let mut to_without_names = to
961                        .clone()
962                        .into_iter()
963                        .filter_map(|header| match header {
964                            Address::Address(mb) => Some(Address::Address(EmailAddress {
965                                name: None,
966                                email: mb.email,
967                            })),
968                            _ => None,
969                        })
970                        .collect::<Vec<_>>();
971                    if to_without_names.is_empty() {
972                        to_without_names.push(hidden_recipients());
973                    }
974                    unprotected_headers.push((
975                        original_header_name,
976                        Address::new_list(to_without_names).into(),
977                    ));
978                } else {
979                    unprotected_headers.push(header.clone());
980                }
981            } else if is_encrypted {
982                protected_headers.push(header.clone());
983
984                match header_name.as_str() {
985                    "subject" => {
986                        unprotected_headers.push((
987                            "Subject",
988                            mail_builder::headers::raw::Raw::new("[...]").into(),
989                        ));
990                    }
991                    "date"
992                    | "in-reply-to"
993                    | "references"
994                    | "auto-submitted"
995                    | "chat-version"
996                    | "autocrypt-setup-message" => {
997                        unprotected_headers.push(header.clone());
998                    }
999                    _ => {
1000                        // Other headers are removed from unprotected part.
1001                    }
1002                }
1003            } else {
1004                // Copy the header to the protected headers
1005                // in case of signed-only message.
1006                // If the message is not signed, this value will not be used.
1007                protected_headers.push(header.clone());
1008                unprotected_headers.push(header.clone())
1009            }
1010        }
1011
1012        let outer_message = if let Some(encryption_keys) = self.encryption_keys {
1013            // Store protected headers in the inner message.
1014            let message = protected_headers
1015                .into_iter()
1016                .fold(message, |message, (header, value)| {
1017                    message.header(header, value)
1018                });
1019
1020            // Add hidden headers to encrypted payload.
1021            let mut message: MimePart<'static> = hidden_headers
1022                .into_iter()
1023                .fold(message, |message, (header, value)| {
1024                    message.header(header, value)
1025                });
1026
1027            // Add gossip headers in chats with multiple recipients
1028            let multiple_recipients =
1029                encryption_keys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1030
1031            let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1032            let now = time();
1033
1034            match &self.loaded {
1035                Loaded::Message { chat, msg } => {
1036                    if chat.typ != Chattype::OutBroadcast {
1037                        for (addr, key) in &encryption_keys {
1038                            let fingerprint = key.dc_fingerprint().hex();
1039                            let cmd = msg.param.get_cmd();
1040                            let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1041                                || cmd == SystemMessage::SecurejoinMessage
1042                                || multiple_recipients && {
1043                                    let gossiped_timestamp: Option<i64> = context
1044                                        .sql
1045                                        .query_get_value(
1046                                            "SELECT timestamp
1047                                         FROM gossip_timestamp
1048                                         WHERE chat_id=? AND fingerprint=?",
1049                                            (chat.id, &fingerprint),
1050                                        )
1051                                        .await?;
1052
1053                                    // `gossip_period == 0` is a special case for testing,
1054                                    // enabling gossip in every message.
1055                                    //
1056                                    // If current time is in the past compared to
1057                                    // `gossiped_timestamp`, we also gossip because
1058                                    // either the `gossiped_timestamp` or clock is wrong.
1059                                    gossip_period == 0
1060                                        || gossiped_timestamp
1061                                            .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1062                                };
1063
1064                            if !should_do_gossip {
1065                                continue;
1066                            }
1067
1068                            let header = Aheader::new(
1069                                addr.clone(),
1070                                key.clone(),
1071                                // Autocrypt 1.1.0 specification says that
1072                                // `prefer-encrypt` attribute SHOULD NOT be included.
1073                                EncryptPreference::NoPreference,
1074                            )
1075                            .to_string();
1076
1077                            message = message.header(
1078                                "Autocrypt-Gossip",
1079                                mail_builder::headers::raw::Raw::new(header),
1080                            );
1081
1082                            context
1083                                .sql
1084                                .execute(
1085                                    "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1086                                     VALUES                       (?, ?, ?)
1087                                     ON CONFLICT                  (chat_id, fingerprint)
1088                                     DO UPDATE SET timestamp=excluded.timestamp",
1089                                    (chat.id, &fingerprint, now),
1090                                )
1091                                .await?;
1092                        }
1093                    }
1094                }
1095                Loaded::Mdn { .. } => {
1096                    // Never gossip in MDNs.
1097                }
1098            }
1099
1100            // Set the appropriate Content-Type for the inner message.
1101            for (h, v) in &mut message.headers {
1102                if h == "Content-Type" {
1103                    if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1104                        *ct = ct.clone().attribute("protected-headers", "v1");
1105                    }
1106                }
1107            }
1108
1109            // Disable compression for SecureJoin to ensure
1110            // there are no compression side channels
1111            // leaking information about the tokens.
1112            let compress = match &self.loaded {
1113                Loaded::Message { msg, .. } => {
1114                    msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1115                }
1116                Loaded::Mdn { .. } => true,
1117            };
1118
1119            // Encrypt to self unconditionally,
1120            // even for a single-device setup.
1121            let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1122            encryption_keyring.extend(encryption_keys.iter().map(|(_addr, key)| (*key).clone()));
1123
1124            // XXX: additional newline is needed
1125            // to pass filtermail at
1126            // <https://github.com/deltachat/chatmail/blob/4d915f9800435bf13057d41af8d708abd34dbfa8/chatmaild/src/chatmaild/filtermail.py#L84-L86>
1127            let encrypted = encrypt_helper
1128                .encrypt(context, encryption_keyring, message, compress)
1129                .await?
1130                + "\n";
1131
1132            // Set the appropriate Content-Type for the outer message
1133            MimePart::new(
1134                "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1135                vec![
1136                    // Autocrypt part 1
1137                    MimePart::new("application/pgp-encrypted", "Version: 1\r\n").header(
1138                        "Content-Description",
1139                        mail_builder::headers::raw::Raw::new("PGP/MIME version identification"),
1140                    ),
1141                    // Autocrypt part 2
1142                    MimePart::new(
1143                        "application/octet-stream; name=\"encrypted.asc\"",
1144                        encrypted,
1145                    )
1146                    .header(
1147                        "Content-Description",
1148                        mail_builder::headers::raw::Raw::new("OpenPGP encrypted message"),
1149                    )
1150                    .header(
1151                        "Content-Disposition",
1152                        mail_builder::headers::raw::Raw::new("inline; filename=\"encrypted.asc\";"),
1153                    ),
1154                ],
1155            )
1156        } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1157            // Never add outer multipart/mixed wrapper to MDN
1158            // as multipart/report Content-Type is used to recognize MDNs
1159            // by Delta Chat receiver and Chatmail servers
1160            // allowing them to be unencrypted and not contain Autocrypt header
1161            // without resetting Autocrypt encryption or triggering Chatmail filter
1162            // that normally only allows encrypted mails.
1163
1164            // Hidden headers are dropped.
1165            message
1166        } else {
1167            let message = hidden_headers
1168                .into_iter()
1169                .fold(message, |message, (header, value)| {
1170                    message.header(header, value)
1171                });
1172            let message = MimePart::new("multipart/mixed", vec![message]);
1173            let mut message = protected_headers
1174                .iter()
1175                .fold(message, |message, (header, value)| {
1176                    message.header(*header, value.clone())
1177                });
1178
1179            if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
1180                // Deduplicate unprotected headers that also are in the protected headers:
1181                let protected: HashSet<&str> =
1182                    HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1183                unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1184
1185                message
1186            } else {
1187                for (h, v) in &mut message.headers {
1188                    if h == "Content-Type" {
1189                        if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1190                            *ct = ct.clone().attribute("protected-headers", "v1");
1191                        }
1192                    }
1193                }
1194
1195                let signature = encrypt_helper.sign(context, &message).await?;
1196                MimePart::new(
1197                    "multipart/signed; protocol=\"application/pgp-signature\"; protected",
1198                    vec![
1199                        message,
1200                        MimePart::new(
1201                            "application/pgp-signature; name=\"signature.asc\"",
1202                            signature,
1203                        )
1204                        .header(
1205                            "Content-Description",
1206                            mail_builder::headers::raw::Raw::<'static>::new(
1207                                "OpenPGP digital signature",
1208                            ),
1209                        )
1210                        .attachment("signature"),
1211                    ],
1212                )
1213            }
1214        };
1215
1216        // Store the unprotected headers on the outer message.
1217        let outer_message = unprotected_headers
1218            .into_iter()
1219            .fold(outer_message, |message, (header, value)| {
1220                message.header(header, value)
1221            });
1222
1223        let MimeFactory {
1224            last_added_location_id,
1225            ..
1226        } = self;
1227
1228        let mut buffer = Vec::new();
1229        let cursor = Cursor::new(&mut buffer);
1230        outer_message.clone().write_part(cursor).ok();
1231        let message = String::from_utf8_lossy(&buffer).to_string();
1232
1233        Ok(RenderedEmail {
1234            message,
1235            // envelope: Envelope::new,
1236            is_encrypted,
1237            last_added_location_id,
1238            sync_ids_to_delete: self.sync_ids_to_delete,
1239            rfc724_mid,
1240            subject: subject_str,
1241        })
1242    }
1243
1244    /// Returns MIME part with a `message.kml` attachment.
1245    fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1246        let Loaded::Message { msg, .. } = &self.loaded else {
1247            return None;
1248        };
1249
1250        let latitude = msg.param.get_float(Param::SetLatitude)?;
1251        let longitude = msg.param.get_float(Param::SetLongitude)?;
1252
1253        let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1254        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1255            .attachment("message.kml");
1256        Some(part)
1257    }
1258
1259    /// Returns MIME part with a `location.kml` attachment.
1260    async fn get_location_kml_part(
1261        &mut self,
1262        context: &Context,
1263    ) -> Result<Option<MimePart<'static>>> {
1264        let Loaded::Message { msg, .. } = &self.loaded else {
1265            return Ok(None);
1266        };
1267
1268        let Some((kml_content, last_added_location_id)) =
1269            location::get_kml(context, msg.chat_id).await?
1270        else {
1271            return Ok(None);
1272        };
1273
1274        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1275            .attachment("location.kml");
1276        if !msg.param.exists(Param::SetLatitude) {
1277            // otherwise, the independent location is already filed
1278            self.last_added_location_id = Some(last_added_location_id);
1279        }
1280        Ok(Some(part))
1281    }
1282
1283    async fn render_message(
1284        &mut self,
1285        context: &Context,
1286        headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1287        grpimage: &Option<String>,
1288        is_encrypted: bool,
1289    ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1290        let Loaded::Message { chat, msg } = &self.loaded else {
1291            bail!("Attempt to render MDN as a message");
1292        };
1293        let chat = chat.clone();
1294        let msg = msg.clone();
1295        let command = msg.param.get_cmd();
1296        let mut placeholdertext = None;
1297
1298        let send_verified_headers = match chat.typ {
1299            Chattype::Single => true,
1300            Chattype::Group => true,
1301            // Mailinglists and broadcast channels can actually never be verified:
1302            Chattype::Mailinglist => false,
1303            Chattype::OutBroadcast | Chattype::InBroadcast => false,
1304        };
1305        if chat.is_protected() && send_verified_headers {
1306            headers.push((
1307                "Chat-Verified",
1308                mail_builder::headers::raw::Raw::new("1").into(),
1309            ));
1310        }
1311
1312        if chat.typ == Chattype::Group {
1313            // Send group ID unless it is an ad hoc group that has no ID.
1314            if !chat.grpid.is_empty() {
1315                headers.push((
1316                    "Chat-Group-ID",
1317                    mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1318                ));
1319            }
1320        }
1321
1322        if chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast {
1323            headers.push((
1324                "Chat-Group-Name",
1325                mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1326            ));
1327            if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1328                headers.push((
1329                    "Chat-Group-Name-Timestamp",
1330                    mail_builder::headers::text::Text::new(ts.to_string()).into(),
1331                ));
1332            }
1333
1334            match command {
1335                SystemMessage::MemberRemovedFromGroup => {
1336                    ensure!(chat.typ != Chattype::OutBroadcast);
1337                    let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1338
1339                    if email_to_remove
1340                        == context
1341                            .get_config(Config::ConfiguredAddr)
1342                            .await?
1343                            .unwrap_or_default()
1344                    {
1345                        placeholdertext = Some(stock_str::msg_group_left_remote(context).await);
1346                    } else {
1347                        placeholdertext =
1348                            Some(stock_str::msg_del_member_remote(context, email_to_remove).await);
1349                    };
1350
1351                    if !email_to_remove.is_empty() {
1352                        headers.push((
1353                            "Chat-Group-Member-Removed",
1354                            mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1355                                .into(),
1356                        ));
1357                    }
1358                }
1359                SystemMessage::MemberAddedToGroup => {
1360                    ensure!(chat.typ != Chattype::OutBroadcast);
1361                    // TODO: lookup the contact by ID rather than email address.
1362                    // We are adding key-contacts, the cannot be looked up by address.
1363                    let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1364                    placeholdertext =
1365                        Some(stock_str::msg_add_member_remote(context, email_to_add).await);
1366
1367                    if !email_to_add.is_empty() {
1368                        headers.push((
1369                            "Chat-Group-Member-Added",
1370                            mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1371                        ));
1372                    }
1373                    if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1374                        info!(
1375                            context,
1376                            "Sending secure-join message {:?}.", "vg-member-added",
1377                        );
1378                        headers.push((
1379                            "Secure-Join",
1380                            mail_builder::headers::raw::Raw::new("vg-member-added".to_string())
1381                                .into(),
1382                        ));
1383                    }
1384                }
1385                SystemMessage::GroupNameChanged => {
1386                    let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1387                    headers.push((
1388                        "Chat-Group-Name-Changed",
1389                        mail_builder::headers::text::Text::new(old_name).into(),
1390                    ));
1391                }
1392                SystemMessage::GroupImageChanged => {
1393                    headers.push((
1394                        "Chat-Content",
1395                        mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1396                    ));
1397                    if grpimage.is_none() {
1398                        headers.push((
1399                            "Chat-Group-Avatar",
1400                            mail_builder::headers::raw::Raw::new("0").into(),
1401                        ));
1402                    }
1403                }
1404                _ => {}
1405            }
1406        }
1407
1408        match command {
1409            SystemMessage::LocationStreamingEnabled => {
1410                headers.push((
1411                    "Chat-Content",
1412                    mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1413                ));
1414            }
1415            SystemMessage::EphemeralTimerChanged => {
1416                headers.push((
1417                    "Chat-Content",
1418                    mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1419                ));
1420            }
1421            SystemMessage::LocationOnly
1422            | SystemMessage::MultiDeviceSync
1423            | SystemMessage::WebxdcStatusUpdate => {
1424                // This should prevent automatic replies,
1425                // such as non-delivery reports.
1426                //
1427                // See <https://tools.ietf.org/html/rfc3834>
1428                //
1429                // Adding this header without encryption leaks some
1430                // information about the message contents, but it can
1431                // already be easily guessed from message timing and size.
1432                headers.push((
1433                    "Auto-Submitted",
1434                    mail_builder::headers::raw::Raw::new("auto-generated").into(),
1435                ));
1436            }
1437            SystemMessage::AutocryptSetupMessage => {
1438                headers.push((
1439                    "Autocrypt-Setup-Message",
1440                    mail_builder::headers::raw::Raw::new("v1").into(),
1441                ));
1442
1443                placeholdertext = Some(ASM_SUBJECT.to_string());
1444            }
1445            SystemMessage::SecurejoinMessage => {
1446                let step = msg.param.get(Param::Arg).unwrap_or_default();
1447                if !step.is_empty() {
1448                    info!(context, "Sending secure-join message {step:?}.");
1449                    headers.push((
1450                        "Secure-Join",
1451                        mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1452                    ));
1453
1454                    let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1455                    if !param2.is_empty() {
1456                        headers.push((
1457                            if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1458                                "Secure-Join-Auth"
1459                            } else {
1460                                "Secure-Join-Invitenumber"
1461                            },
1462                            mail_builder::headers::text::Text::new(param2.to_string()).into(),
1463                        ));
1464                    }
1465
1466                    let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1467                    if !fingerprint.is_empty() {
1468                        headers.push((
1469                            "Secure-Join-Fingerprint",
1470                            mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1471                        ));
1472                    }
1473                    if let Some(id) = msg.param.get(Param::Arg4) {
1474                        headers.push((
1475                            "Secure-Join-Group",
1476                            mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1477                        ));
1478                    };
1479                }
1480            }
1481            SystemMessage::ChatProtectionEnabled => {
1482                headers.push((
1483                    "Chat-Content",
1484                    mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1485                ));
1486            }
1487            SystemMessage::ChatProtectionDisabled => {
1488                headers.push((
1489                    "Chat-Content",
1490                    mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1491                ));
1492            }
1493            SystemMessage::IrohNodeAddr => {
1494                headers.push((
1495                    "Iroh-Node-Addr",
1496                    mail_builder::headers::text::Text::new(serde_json::to_string(
1497                        &context
1498                            .get_or_try_init_peer_channel()
1499                            .await?
1500                            .get_node_addr()
1501                            .await?,
1502                    )?)
1503                    .into(),
1504                ));
1505            }
1506            _ => {}
1507        }
1508
1509        if let Some(grpimage) = grpimage {
1510            info!(context, "setting group image '{}'", grpimage);
1511            let avatar = build_avatar_file(context, grpimage)
1512                .await
1513                .context("Cannot attach group image")?;
1514            headers.push((
1515                "Chat-Group-Avatar",
1516                mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1517            ));
1518        }
1519
1520        if msg.viewtype == Viewtype::Sticker {
1521            headers.push((
1522                "Chat-Content",
1523                mail_builder::headers::raw::Raw::new("sticker").into(),
1524            ));
1525        } else if msg.viewtype == Viewtype::VideochatInvitation {
1526            headers.push((
1527                "Chat-Content",
1528                mail_builder::headers::raw::Raw::new("videochat-invitation").into(),
1529            ));
1530            headers.push((
1531                "Chat-Webrtc-Room",
1532                mail_builder::headers::raw::Raw::new(
1533                    msg.param
1534                        .get(Param::WebrtcRoom)
1535                        .unwrap_or_default()
1536                        .to_string(),
1537                )
1538                .into(),
1539            ));
1540        }
1541
1542        if msg.viewtype == Viewtype::Voice
1543            || msg.viewtype == Viewtype::Audio
1544            || msg.viewtype == Viewtype::Video
1545        {
1546            if msg.viewtype == Viewtype::Voice {
1547                headers.push((
1548                    "Chat-Voice-Message",
1549                    mail_builder::headers::raw::Raw::new("1").into(),
1550                ));
1551            }
1552            let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1553            if duration_ms > 0 {
1554                let dur = duration_ms.to_string();
1555                headers.push((
1556                    "Chat-Duration",
1557                    mail_builder::headers::raw::Raw::new(dur).into(),
1558                ));
1559            }
1560        }
1561
1562        // add text part - we even add empty text and force a MIME-multipart-message as:
1563        // - some Apps have problems with Non-text in the main part (eg. "Mail" from stock Android)
1564        // - we can add "forward hints" this way
1565        // - it looks better
1566
1567        let afwd_email = msg.param.exists(Param::Forwarded);
1568        let fwdhint = if afwd_email {
1569            Some(
1570                "---------- Forwarded message ----------\r\n\
1571                 From: Delta Chat\r\n\
1572                 \r\n"
1573                    .to_string(),
1574            )
1575        } else {
1576            None
1577        };
1578
1579        let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1580
1581        let mut quoted_text = None;
1582        if let Some(msg_quoted_text) = msg.quoted_text() {
1583            let mut some_quoted_text = String::new();
1584            for quoted_line in msg_quoted_text.split('\n') {
1585                some_quoted_text += "> ";
1586                some_quoted_text += quoted_line;
1587                some_quoted_text += "\r\n";
1588            }
1589            some_quoted_text += "\r\n";
1590            quoted_text = Some(some_quoted_text)
1591        }
1592
1593        if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1594            // Message is not encrypted but quotes encrypted message.
1595            quoted_text = Some("> ...\r\n\r\n".to_string());
1596        }
1597        if quoted_text.is_none() && final_text.starts_with('>') {
1598            // Insert empty line to avoid receiver treating user-sent quote as topquote inserted by
1599            // Delta Chat.
1600            quoted_text = Some("\r\n".to_string());
1601        }
1602
1603        let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1604
1605        let footer = if is_reaction { "" } else { &self.selfstatus };
1606
1607        let message_text = format!(
1608            "{}{}{}{}{}{}",
1609            fwdhint.unwrap_or_default(),
1610            quoted_text.unwrap_or_default(),
1611            escape_message_footer_marks(final_text),
1612            if !final_text.is_empty() && !footer.is_empty() {
1613                "\r\n\r\n"
1614            } else {
1615                ""
1616            },
1617            if !footer.is_empty() { "-- \r\n" } else { "" },
1618            footer
1619        );
1620
1621        let mut main_part = MimePart::new("text/plain", message_text);
1622        if is_reaction {
1623            main_part = main_part.header(
1624                "Content-Disposition",
1625                mail_builder::headers::raw::Raw::new("reaction"),
1626            );
1627        }
1628
1629        let mut parts = Vec::new();
1630
1631        // add HTML-part, this is needed only if a HTML-message from a non-delta-client is forwarded;
1632        // for simplificity and to avoid conversion errors, we're generating the HTML-part from the original message.
1633        if msg.has_html() {
1634            let html = if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded) {
1635                MsgId::new(orig_msg_id.try_into()?)
1636                    .get_html(context)
1637                    .await?
1638            } else {
1639                msg.param.get(Param::SendHtml).map(|s| s.to_string())
1640            };
1641            if let Some(html) = html {
1642                main_part = MimePart::new(
1643                    "multipart/alternative",
1644                    vec![main_part, MimePart::new("text/html", html)],
1645                )
1646            }
1647        }
1648
1649        // add attachment part
1650        if msg.viewtype.has_file() {
1651            let file_part = build_body_file(context, &msg).await?;
1652            parts.push(file_part);
1653        }
1654
1655        if let Some(msg_kml_part) = self.get_message_kml_part() {
1656            parts.push(msg_kml_part);
1657        }
1658
1659        if location::is_sending_locations_to_chat(context, Some(msg.chat_id)).await? {
1660            if let Some(part) = self.get_location_kml_part(context).await? {
1661                parts.push(part);
1662            }
1663        }
1664
1665        // we do not piggyback sync-files to other self-sent-messages
1666        // to not risk files becoming too larger and being skipped by download-on-demand.
1667        if command == SystemMessage::MultiDeviceSync {
1668            let json = msg.param.get(Param::Arg).unwrap_or_default();
1669            let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1670            parts.push(context.build_sync_part(json.to_string()));
1671            self.sync_ids_to_delete = Some(ids.to_string());
1672        } else if command == SystemMessage::WebxdcStatusUpdate {
1673            let json = msg.param.get(Param::Arg).unwrap_or_default();
1674            parts.push(context.build_status_update_part(json));
1675        } else if msg.viewtype == Viewtype::Webxdc {
1676            headers.push((
1677                "Iroh-Gossip-Topic",
1678                mail_builder::headers::raw::Raw::new(create_iroh_header(context, msg.id).await?)
1679                    .into(),
1680            ));
1681            if let (Some(json), _) = context
1682                .render_webxdc_status_update_object(
1683                    msg.id,
1684                    StatusUpdateSerial::MIN,
1685                    StatusUpdateSerial::MAX,
1686                    None,
1687                )
1688                .await?
1689            {
1690                parts.push(context.build_status_update_part(&json));
1691            }
1692        }
1693
1694        if self.attach_selfavatar {
1695            match context.get_config(Config::Selfavatar).await? {
1696                Some(path) => match build_avatar_file(context, &path).await {
1697                    Ok(avatar) => headers.push((
1698                        "Chat-User-Avatar",
1699                        mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1700                    )),
1701                    Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1702                },
1703                None => headers.push((
1704                    "Chat-User-Avatar",
1705                    mail_builder::headers::raw::Raw::new("0").into(),
1706                )),
1707            }
1708        }
1709
1710        Ok((main_part, parts))
1711    }
1712
1713    /// Render an MDN
1714    fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1715        // RFC 6522, this also requires the `report-type` parameter which is equal
1716        // to the MIME subtype of the second body part of the multipart/report
1717        let Loaded::Mdn {
1718            rfc724_mid,
1719            additional_msg_ids,
1720        } = &self.loaded
1721        else {
1722            bail!("Attempt to render a message as MDN");
1723        };
1724
1725        // first body part: always human-readable, always REQUIRED by RFC 6522.
1726        // untranslated to no reveal sender's language.
1727        // moreover, translations in unknown languages are confusing, and clients may not display them at all
1728        let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1729
1730        let mut message = MimePart::new(
1731            "multipart/report; report-type=disposition-notification",
1732            vec![text_part],
1733        );
1734
1735        // second body part: machine-readable, always REQUIRED by RFC 6522
1736        let message_text2 = format!(
1737            "Original-Recipient: rfc822;{}\r\n\
1738             Final-Recipient: rfc822;{}\r\n\
1739             Original-Message-ID: <{}>\r\n\
1740             Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1741            self.from_addr, self.from_addr, rfc724_mid
1742        );
1743
1744        let extension_fields = if additional_msg_ids.is_empty() {
1745            "".to_string()
1746        } else {
1747            "Additional-Message-IDs: ".to_string()
1748                + &additional_msg_ids
1749                    .iter()
1750                    .map(|mid| render_rfc724_mid(mid))
1751                    .collect::<Vec<String>>()
1752                    .join(" ")
1753                + "\r\n"
1754        };
1755
1756        message.add_part(MimePart::new(
1757            "message/disposition-notification",
1758            message_text2 + &extension_fields,
1759        ));
1760
1761        Ok(message)
1762    }
1763}
1764
1765fn hidden_recipients() -> Address<'static> {
1766    Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
1767}
1768
1769async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
1770    let file_name = msg.get_filename().context("msg has no file")?;
1771    let blob = msg
1772        .param
1773        .get_file_blob(context)?
1774        .context("msg has no file")?;
1775    let mimetype = msg
1776        .param
1777        .get(Param::MimeType)
1778        .unwrap_or("application/octet-stream")
1779        .to_string();
1780    let body = fs::read(blob.to_abs_path()).await?;
1781
1782    // create mime part, for Content-Disposition, see RFC 2183.
1783    // `Content-Disposition: attachment` seems not to make a difference to `Content-Disposition: inline`
1784    // at least on tested Thunderbird and Gma'l in 2017.
1785    // But I've heard about problems with inline and outl'k, so we just use the attachment-type until we
1786    // run into other problems ...
1787    let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
1788
1789    Ok(mail)
1790}
1791
1792async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
1793    let blob = match path.starts_with("$BLOBDIR/") {
1794        true => BlobObject::from_name(context, path)?,
1795        false => BlobObject::from_path(context, path.as_ref())?,
1796    };
1797    let body = fs::read(blob.to_abs_path()).await?;
1798    let encoded_body = base64::engine::general_purpose::STANDARD
1799        .encode(&body)
1800        .chars()
1801        .enumerate()
1802        .fold(String::new(), |mut res, (i, c)| {
1803            if i % 78 == 77 {
1804                res.push(' ')
1805            }
1806            res.push(c);
1807            res
1808        });
1809    Ok(encoded_body)
1810}
1811
1812fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
1813    let addr_lc = addr.to_lowercase();
1814    recipients
1815        .iter()
1816        .any(|(_, cur)| cur.to_lowercase() == addr_lc)
1817}
1818
1819fn render_rfc724_mid(rfc724_mid: &str) -> String {
1820    let rfc724_mid = rfc724_mid.trim().to_string();
1821
1822    if rfc724_mid.chars().next().unwrap_or_default() == '<' {
1823        rfc724_mid
1824    } else {
1825        format!("<{rfc724_mid}>")
1826    }
1827}
1828
1829#[cfg(test)]
1830mod mimefactory_tests;