deltachat/
mimefactory.rs

1//! # MIME message production.
2
3use std::collections::{BTreeSet, HashSet};
4use std::io::Cursor;
5
6use anyhow::{Context as _, Result, bail, format_err};
7use base64::Engine as _;
8use data_encoding::BASE32_NOPAD;
9use deltachat_contact_tools::sanitize_bidi_characters;
10use iroh_gossip::proto::TopicId;
11use mail_builder::headers::HeaderType;
12use mail_builder::headers::address::Address;
13use mail_builder::mime::MimePart;
14use tokio::fs;
15
16use crate::aheader::{Aheader, EncryptPreference};
17use crate::blob::BlobObject;
18use crate::chat::{self, Chat, PARAM_BROADCAST_SECRET, load_broadcast_secret};
19use crate::config::Config;
20use crate::constants::{ASM_SUBJECT, BROADCAST_INCOMPATIBILITY_MSG};
21use crate::constants::{Chattype, DC_FROM_HANDSHAKE};
22use crate::contact::{Contact, ContactId, Origin};
23use crate::context::Context;
24use crate::download::PostMsgMetadata;
25use crate::e2ee::EncryptHelper;
26use crate::ensure_and_debug_assert;
27use crate::ephemeral::Timer as EphemeralTimer;
28use crate::headerdef::HeaderDef;
29use crate::key::{DcKey, SignedPublicKey, self_fingerprint};
30use crate::location;
31use crate::log::warn;
32use crate::message::{Message, MsgId, Viewtype};
33use crate::mimeparser::{SystemMessage, is_hidden};
34use crate::param::Param;
35use crate::peer_channels::{create_iroh_header, get_iroh_topic_for_msg};
36use crate::pgp::SeipdVersion;
37use crate::simplify::escape_message_footer_marks;
38use crate::stock_str;
39use crate::tools::{
40    IsNoneOrEmpty, create_outgoing_rfc724_mid, create_smeared_timestamp, remove_subject_prefix,
41    time,
42};
43use crate::webxdc::StatusUpdateSerial;
44
45// attachments of 25 mb brutto should work on the majority of providers
46// (brutto examples: web.de=50, 1&1=40, t-online.de=32, gmail=25, posteo=50, yahoo=25, all-inkl=100).
47// to get the netto sizes, we subtract 1 mb header-overhead and the base64-overhead.
48pub const RECOMMENDED_FILE_SIZE: u64 = 24 * 1024 * 1024 / 4 * 3;
49
50#[derive(Debug, Clone)]
51#[expect(clippy::large_enum_variant)]
52pub enum Loaded {
53    Message {
54        chat: Chat,
55        msg: Message,
56    },
57    Mdn {
58        rfc724_mid: String,
59        additional_msg_ids: Vec<String>,
60    },
61}
62
63#[derive(Debug, Clone, PartialEq)]
64pub enum PreMessageMode {
65    /// adds the Chat-Is-Post-Message header in unprotected part
66    Post,
67    /// adds the Chat-Post-Message-ID header to protected part
68    /// also adds metadata and explicitly excludes attachment
69    Pre { post_msg_rfc724_mid: String },
70    /// Atomic ("normal") message.
71    None,
72}
73
74/// Helper to construct mime messages.
75#[derive(Debug, Clone)]
76pub struct MimeFactory {
77    from_addr: String,
78    from_displayname: String,
79
80    /// Goes to the `Sender:`-header, if set.
81    /// For overridden names, `sender_displayname` is set to the
82    /// config-name while `from_displayname` is set to the overridden name.
83    /// From the perspective of the receiver,
84    /// a set `Sender:`-header is used as an indicator that the name is overridden;
85    /// names are alsways read from the `From:`-header.
86    sender_displayname: Option<String>,
87
88    selfstatus: String,
89
90    /// Vector of actual recipient addresses.
91    ///
92    /// This is the list of addresses the message should be sent to.
93    /// It is not the same as the `To` header,
94    /// because in case of "member removed" message
95    /// removed member is in the recipient list,
96    /// but not in the `To` header.
97    /// In case of broadcast channels there are multiple recipients,
98    /// but the `To` header has no members.
99    ///
100    /// If `bcc_self` configuration is enabled,
101    /// this list will be extended with own address later,
102    /// but `MimeFactory` is not responsible for this.
103    recipients: Vec<String>,
104
105    /// Vector of pairs of recipient
106    /// addresses and OpenPGP keys
107    /// to use for encryption.
108    ///
109    /// If `Some`, encrypt to self also.
110    /// `None` if the message is not encrypted.
111    encryption_pubkeys: Option<Vec<(String, SignedPublicKey)>>,
112
113    /// Vector of pairs of recipient name and address that goes into the `To` field.
114    ///
115    /// The list of actual message recipient addresses may be different,
116    /// e.g. if members are hidden for broadcast channels
117    /// or if the keys for some recipients are missing
118    /// and encrypted message cannot be sent to them.
119    to: Vec<(String, String)>,
120
121    /// Vector of pairs of past group member names and addresses.
122    past_members: Vec<(String, String)>,
123
124    /// Fingerprints of the members in the same order as in the `to`
125    /// followed by `past_members`.
126    ///
127    /// If this is not empty, its length
128    /// should be the sum of `to` and `past_members` length.
129    member_fingerprints: Vec<String>,
130
131    /// Timestamps of the members in the same order as in the `to`
132    /// followed by `past_members`.
133    ///
134    /// If this is not empty, its length
135    /// should be the sum of `to` and `past_members` length.
136    member_timestamps: Vec<i64>,
137
138    timestamp: i64,
139    loaded: Loaded,
140    in_reply_to: String,
141
142    /// List of Message-IDs for `References` header.
143    references: Vec<String>,
144
145    /// True if the message requests Message Disposition Notification
146    /// using `Chat-Disposition-Notification-To` header.
147    req_mdn: bool,
148
149    last_added_location_id: Option<u32>,
150
151    /// If the created mime-structure contains sync-items,
152    /// the IDs of these items are listed here.
153    /// The IDs are returned via `RenderedEmail`
154    /// and must be deleted if the message is actually queued for sending.
155    sync_ids_to_delete: Option<String>,
156
157    /// True if the avatar should be attached.
158    pub attach_selfavatar: bool,
159
160    /// This field is used to sustain the topic id of webxdcs needed for peer channels.
161    webxdc_topic: Option<TopicId>,
162
163    /// Pre-message / post-message / atomic message.
164    pre_message_mode: PreMessageMode,
165}
166
167/// Result of rendering a message, ready to be submitted to a send job.
168#[derive(Debug, Clone)]
169pub struct RenderedEmail {
170    pub message: String,
171    // pub envelope: Envelope,
172    pub is_encrypted: bool,
173    pub last_added_location_id: Option<u32>,
174
175    /// A comma-separated string of sync-IDs that are used by the rendered email and must be deleted
176    /// from `multi_device_sync` once the message is actually queued for sending.
177    pub sync_ids_to_delete: Option<String>,
178
179    /// Message ID (Message in the sense of Email)
180    pub rfc724_mid: String,
181
182    /// Message subject.
183    pub subject: String,
184}
185
186fn new_address_with_name(name: &str, address: String) -> Address<'static> {
187    Address::new_address(
188        if name == address || name.is_empty() {
189            None
190        } else {
191            Some(name.to_string())
192        },
193        address,
194    )
195}
196
197impl MimeFactory {
198    #[expect(clippy::arithmetic_side_effects)]
199    pub async fn from_msg(context: &Context, msg: Message) -> Result<MimeFactory> {
200        let now = time();
201        let chat = Chat::load_from_db(context, msg.chat_id).await?;
202        let attach_profile_data = Self::should_attach_profile_data(&msg);
203        let undisclosed_recipients = should_hide_recipients(&msg, &chat);
204
205        let from_addr = context.get_primary_self_addr().await?;
206        let config_displayname = context
207            .get_config(Config::Displayname)
208            .await?
209            .unwrap_or_default();
210        let (from_displayname, sender_displayname) =
211            if let Some(override_name) = msg.param.get(Param::OverrideSenderDisplayname) {
212                (override_name.to_string(), Some(config_displayname))
213            } else {
214                let name = match attach_profile_data {
215                    true => config_displayname,
216                    false => "".to_string(),
217                };
218                (name, None)
219            };
220
221        let mut recipients = Vec::new();
222        let mut to = Vec::new();
223        let mut past_members = Vec::new();
224        let mut member_fingerprints = Vec::new();
225        let mut member_timestamps = Vec::new();
226        let mut recipient_ids = HashSet::new();
227        let mut req_mdn = false;
228
229        let encryption_pubkeys;
230
231        let self_fingerprint = self_fingerprint(context).await?;
232
233        if chat.is_self_talk() {
234            to.push((from_displayname.to_string(), from_addr.to_string()));
235
236            encryption_pubkeys = if msg.param.get_bool(Param::ForcePlaintext).unwrap_or(false) {
237                None
238            } else {
239                Some(Vec::new())
240            };
241        } else if chat.is_mailing_list() {
242            let list_post = chat
243                .param
244                .get(Param::ListPost)
245                .context("Can't write to mailinglist without ListPost param")?;
246            to.push(("".to_string(), list_post.to_string()));
247            recipients.push(list_post.to_string());
248
249            // Do not encrypt messages to mailing lists.
250            encryption_pubkeys = None;
251        } else if let Some(fp) = must_have_only_one_recipient(&msg, &chat) {
252            let fp = fp?;
253            // In a broadcast channel, only send member-added/removed messages
254            // to the affected member
255            let (authname, addr) = context
256                .sql
257                .query_row(
258                    "SELECT authname, addr FROM contacts WHERE fingerprint=?",
259                    (fp,),
260                    |row| {
261                        let authname: String = row.get(0)?;
262                        let addr: String = row.get(1)?;
263                        Ok((authname, addr))
264                    },
265                )
266                .await?;
267
268            let public_key_bytes: Vec<_> = context
269                .sql
270                .query_get_value(
271                    "SELECT public_key FROM public_keys WHERE fingerprint=?",
272                    (fp,),
273                )
274                .await?
275                .context("Can't send member addition/removal: missing key")?;
276
277            recipients.push(addr.clone());
278            to.push((authname, addr.clone()));
279
280            let public_key = SignedPublicKey::from_slice(&public_key_bytes)?;
281            encryption_pubkeys = Some(vec![(addr, public_key)]);
282        } else {
283            let email_to_remove = if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
284                msg.param.get(Param::Arg)
285            } else {
286                None
287            };
288
289            let is_encrypted = if msg
290                .param
291                .get_bool(Param::ForcePlaintext)
292                .unwrap_or_default()
293            {
294                false
295            } else {
296                msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
297                    || chat.is_encrypted(context).await?
298            };
299
300            let mut keys = Vec::new();
301            let mut missing_key_addresses = BTreeSet::new();
302            context
303                .sql
304                // Sort recipients by `add_timestamp DESC` so that if the group is large and there
305                // are multiple SMTP messages, a newly added member receives the member addition
306                // message earlier and has gossiped keys of other members (otherwise the new member
307                // may receive messages from other members earlier and fail to verify them).
308                .query_map(
309                    "SELECT
310                     c.authname,
311                     c.addr,
312                     c.fingerprint,
313                     c.id,
314                     cc.add_timestamp,
315                     cc.remove_timestamp,
316                     k.public_key
317                     FROM chats_contacts cc
318                     LEFT JOIN contacts c ON cc.contact_id=c.id
319                     LEFT JOIN public_keys k ON k.fingerprint=c.fingerprint
320                     WHERE cc.chat_id=?
321                     AND (cc.contact_id>9 OR (cc.contact_id=1 AND ?))
322                     ORDER BY cc.add_timestamp DESC",
323                    (msg.chat_id, chat.typ == Chattype::Group),
324                    |row| {
325                        let authname: String = row.get(0)?;
326                        let addr: String = row.get(1)?;
327                        let fingerprint: String = row.get(2)?;
328                        let id: ContactId = row.get(3)?;
329                        let add_timestamp: i64 = row.get(4)?;
330                        let remove_timestamp: i64 = row.get(5)?;
331                        let public_key_bytes_opt: Option<Vec<u8>> = row.get(6)?;
332                        Ok((authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt))
333                    },
334                    |rows| {
335                        let mut past_member_timestamps = Vec::new();
336                        let mut past_member_fingerprints = Vec::new();
337
338                        for row in rows {
339                            let (authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt) = row?;
340
341                            let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
342                                Some(SignedPublicKey::from_slice(public_key_bytes)?)
343                            } else {
344                                None
345                            };
346
347                            let addr = if id == ContactId::SELF {
348                                from_addr.to_string()
349                            } else {
350                                addr
351                            };
352                            let name = match attach_profile_data {
353                                true => authname,
354                                false => "".to_string(),
355                            };
356                            if add_timestamp >= remove_timestamp {
357                                if !recipients_contain_addr(&to, &addr) {
358                                    if id != ContactId::SELF {
359                                        recipients.push(addr.clone());
360                                    }
361                                    if !undisclosed_recipients {
362                                        to.push((name, addr.clone()));
363
364                                        if is_encrypted {
365                                            if !fingerprint.is_empty() {
366                                                member_fingerprints.push(fingerprint);
367                                            } else if id == ContactId::SELF {
368                                                member_fingerprints.push(self_fingerprint.to_string());
369                                            } else {
370                                                ensure_and_debug_assert!(member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
371                                            }
372                                        }
373                                        member_timestamps.push(add_timestamp);
374                                    }
375                                }
376                                recipient_ids.insert(id);
377
378                                if let Some(public_key) = public_key_opt {
379                                    keys.push((addr.clone(), public_key))
380                                } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
381                                    missing_key_addresses.insert(addr.clone());
382                                    if is_encrypted {
383                                        warn!(context, "Missing key for {addr}");
384                                    }
385                                }
386                            } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
387                                // Row is a tombstone,
388                                // member is not actually part of the group.
389                                if !recipients_contain_addr(&past_members, &addr) {
390                                    if let Some(email_to_remove) = email_to_remove
391                                        && email_to_remove == addr {
392                                            // This is a "member removed" message,
393                                            // we need to notify removed member
394                                            // that it was removed.
395                                            if id != ContactId::SELF {
396                                                recipients.push(addr.clone());
397                                            }
398
399                                            if let Some(public_key) = public_key_opt {
400                                                keys.push((addr.clone(), public_key))
401                                            } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat)  {
402                                                missing_key_addresses.insert(addr.clone());
403                                                if is_encrypted {
404                                                    warn!(context, "Missing key for {addr}");
405                                                }
406                                            }
407                                        }
408                                    if !undisclosed_recipients {
409                                        past_members.push((name, addr.clone()));
410                                        past_member_timestamps.push(remove_timestamp);
411
412                                        if is_encrypted {
413                                            if !fingerprint.is_empty() {
414                                                past_member_fingerprints.push(fingerprint);
415                                            } else if id == ContactId::SELF {
416                                                // It's fine to have self in past members
417                                                // if we are leaving the group.
418                                                past_member_fingerprints.push(self_fingerprint.to_string());
419                                            } else {
420                                                ensure_and_debug_assert!(past_member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
421                                            }
422                                        }
423                                    }
424                                }
425                            }
426                        }
427
428                        ensure_and_debug_assert!(
429                            member_timestamps.len() >= to.len(),
430                            "member_timestamps.len() ({}) < to.len() ({})",
431                            member_timestamps.len(), to.len());
432                        ensure_and_debug_assert!(
433                            member_fingerprints.is_empty() || member_fingerprints.len() >= to.len(),
434                            "member_fingerprints.len() ({}) < to.len() ({})",
435                            member_fingerprints.len(), to.len());
436
437                        if to.len() > 1
438                            && let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
439                                to.remove(position);
440                                member_timestamps.remove(position);
441                                if is_encrypted {
442                                    member_fingerprints.remove(position);
443                                }
444                            }
445
446                        member_timestamps.extend(past_member_timestamps);
447                        if is_encrypted {
448                            member_fingerprints.extend(past_member_fingerprints);
449                        }
450                        Ok(())
451                    },
452                )
453                .await?;
454            let recipient_ids: Vec<_> = recipient_ids
455                .into_iter()
456                .filter(|id| *id != ContactId::SELF)
457                .collect();
458            if recipient_ids.len() == 1
459                && !matches!(
460                    msg.param.get_cmd(),
461                    SystemMessage::MemberRemovedFromGroup | SystemMessage::SecurejoinMessage
462                )
463                && !matches!(chat.typ, Chattype::OutBroadcast | Chattype::InBroadcast)
464            {
465                info!(
466                    context,
467                    "Scale up origin of {} recipients to OutgoingTo.", chat.id
468                );
469                ContactId::scaleup_origin(context, &recipient_ids, Origin::OutgoingTo).await?;
470            }
471
472            if !msg.is_system_message()
473                && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
474                && context.should_request_mdns().await?
475            {
476                req_mdn = true;
477            }
478
479            encryption_pubkeys = if !is_encrypted {
480                None
481            } else if should_encrypt_symmetrically(&msg, &chat) {
482                Some(Vec::new())
483            } else {
484                if keys.is_empty() && !recipients.is_empty() {
485                    bail!("No recipient keys are available, cannot encrypt to {recipients:?}.");
486                }
487
488                // Remove recipients for which the key is missing.
489                if !missing_key_addresses.is_empty() {
490                    recipients.retain(|addr| !missing_key_addresses.contains(addr));
491                }
492
493                Some(keys)
494            };
495        }
496
497        let (in_reply_to, references) = context
498            .sql
499            .query_row(
500                "SELECT mime_in_reply_to, IFNULL(mime_references, '')
501                 FROM msgs WHERE id=?",
502                (msg.id,),
503                |row| {
504                    let in_reply_to: String = row.get(0)?;
505                    let references: String = row.get(1)?;
506
507                    Ok((in_reply_to, references))
508                },
509            )
510            .await?;
511        let references: Vec<String> = references
512            .trim()
513            .split_ascii_whitespace()
514            .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
515            .collect();
516        let selfstatus = match attach_profile_data {
517            true => context
518                .get_config(Config::Selfstatus)
519                .await?
520                .unwrap_or_default(),
521            false => "".to_string(),
522        };
523        // We don't display avatars for address-contacts, so sending avatars w/o encryption is not
524        // useful and causes e.g. Outlook to reject a message with a big header, see
525        // https://support.delta.chat/t/invalid-mime-content-single-text-value-size-32822-exceeded-allowed-maximum-32768-for-the-chat-user-avatar-header/4067.
526        let attach_selfavatar =
527            Self::should_attach_selfavatar(context, &msg).await && encryption_pubkeys.is_some();
528
529        ensure_and_debug_assert!(
530            member_timestamps.is_empty()
531                || to.len() + past_members.len() == member_timestamps.len(),
532            "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
533            to.len(),
534            past_members.len(),
535            member_timestamps.len(),
536        );
537        let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
538        let factory = MimeFactory {
539            from_addr,
540            from_displayname,
541            sender_displayname,
542            selfstatus,
543            recipients,
544            encryption_pubkeys,
545            to,
546            past_members,
547            member_fingerprints,
548            member_timestamps,
549            timestamp: msg.timestamp_sort,
550            loaded: Loaded::Message { msg, chat },
551            in_reply_to,
552            references,
553            req_mdn,
554            last_added_location_id: None,
555            sync_ids_to_delete: None,
556            attach_selfavatar,
557            webxdc_topic,
558            pre_message_mode: PreMessageMode::None,
559        };
560        Ok(factory)
561    }
562
563    pub async fn from_mdn(
564        context: &Context,
565        from_id: ContactId,
566        rfc724_mid: String,
567        additional_msg_ids: Vec<String>,
568    ) -> Result<MimeFactory> {
569        let contact = Contact::get_by_id(context, from_id).await?;
570        let from_addr = context.get_primary_self_addr().await?;
571        let timestamp = create_smeared_timestamp(context);
572
573        let addr = contact.get_addr().to_string();
574        let encryption_pubkeys = if from_id == ContactId::SELF {
575            Some(Vec::new())
576        } else if contact.is_key_contact() {
577            if let Some(key) = contact.public_key(context).await? {
578                Some(vec![(addr.clone(), key)])
579            } else {
580                Some(Vec::new())
581            }
582        } else {
583            None
584        };
585
586        let res = MimeFactory {
587            from_addr,
588            from_displayname: "".to_string(),
589            sender_displayname: None,
590            selfstatus: "".to_string(),
591            recipients: vec![addr],
592            encryption_pubkeys,
593            to: vec![("".to_string(), contact.get_addr().to_string())],
594            past_members: vec![],
595            member_fingerprints: vec![],
596            member_timestamps: vec![],
597            timestamp,
598            loaded: Loaded::Mdn {
599                rfc724_mid,
600                additional_msg_ids,
601            },
602            in_reply_to: String::default(),
603            references: Vec::new(),
604            req_mdn: false,
605            last_added_location_id: None,
606            sync_ids_to_delete: None,
607            attach_selfavatar: false,
608            webxdc_topic: None,
609            pre_message_mode: PreMessageMode::None,
610        };
611
612        Ok(res)
613    }
614
615    fn should_skip_autocrypt(&self) -> bool {
616        match &self.loaded {
617            Loaded::Message { msg, .. } => {
618                msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
619            }
620            Loaded::Mdn { .. } => true,
621        }
622    }
623
624    fn should_attach_profile_data(msg: &Message) -> bool {
625        msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
626            let step = msg.param.get(Param::Arg).unwrap_or_default();
627            // Don't attach profile data at the earlier SecureJoin steps:
628            // - The corresponding messages, i.e. "v{c,g}-request" and "v{c,g}-auth-required" are
629            //   deleted right after processing, so other devices won't see the avatar etc.
630            // - It's also good for privacy because the contact isn't yet verified and these
631            //   messages are auto-sent unlike usual unencrypted messages.
632            step == "vg-request-with-auth"
633                || step == "vc-request-with-auth"
634                // Note that for "vg-member-added"
635                // get_cmd() returns `MemberAddedToGroup` rather than `SecurejoinMessage`,
636                // so, it wouldn't actually be necessary to have them in the list here.
637                // Still, they are here for completeness.
638                || step == "vg-member-added"
639                || step == "vc-contact-confirm"
640        }
641    }
642
643    async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
644        Self::should_attach_profile_data(msg)
645            && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
646                Ok(should) => should,
647                Err(err) => {
648                    warn!(
649                        context,
650                        "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
651                    );
652                    false
653                }
654            }
655    }
656
657    fn grpimage(&self) -> Option<String> {
658        match &self.loaded {
659            Loaded::Message { chat, msg } => {
660                let cmd = msg.param.get_cmd();
661
662                match cmd {
663                    SystemMessage::MemberAddedToGroup => {
664                        return chat.param.get(Param::ProfileImage).map(Into::into);
665                    }
666                    SystemMessage::GroupImageChanged => {
667                        return msg.param.get(Param::Arg).map(Into::into);
668                    }
669                    _ => {}
670                }
671
672                if msg
673                    .param
674                    .get_bool(Param::AttachChatAvatarAndDescription)
675                    .unwrap_or_default()
676                {
677                    return chat.param.get(Param::ProfileImage).map(Into::into);
678                }
679
680                None
681            }
682            Loaded::Mdn { .. } => None,
683        }
684    }
685
686    async fn subject_str(&self, context: &Context) -> Result<String> {
687        let subject = match &self.loaded {
688            Loaded::Message { chat, msg } => {
689                let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
690
691                if !msg.subject.is_empty() {
692                    return Ok(msg.subject.clone());
693                }
694
695                if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
696                    && quoted_msg_subject.is_none_or_empty()
697                {
698                    let re = if self.in_reply_to.is_empty() {
699                        ""
700                    } else {
701                        "Re: "
702                    };
703                    return Ok(format!("{}{}", re, chat.name));
704                }
705
706                let parent_subject = if quoted_msg_subject.is_none_or_empty() {
707                    chat.param.get(Param::LastSubject)
708                } else {
709                    quoted_msg_subject.as_deref()
710                };
711                if let Some(last_subject) = parent_subject {
712                    return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
713                }
714
715                let self_name = match Self::should_attach_profile_data(msg) {
716                    true => context.get_config(Config::Displayname).await?,
717                    false => None,
718                };
719                let self_name = &match self_name {
720                    Some(name) => name,
721                    None => context.get_config(Config::Addr).await?.unwrap_or_default(),
722                };
723                stock_str::subject_for_new_contact(context, self_name).await
724            }
725            Loaded::Mdn { .. } => "Receipt Notification".to_string(), // untranslated to no reveal sender's language
726        };
727
728        Ok(subject)
729    }
730
731    pub fn recipients(&self) -> Vec<String> {
732        self.recipients.clone()
733    }
734
735    /// Consumes a `MimeFactory` and renders it into a message which is then stored in
736    /// `smtp`-table to be used by the SMTP loop
737    #[expect(clippy::arithmetic_side_effects)]
738    pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
739        let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
740
741        let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
742
743        let mut to: Vec<Address<'static>> = Vec::new();
744        for (name, addr) in &self.to {
745            to.push(Address::new_address(
746                if name.is_empty() {
747                    None
748                } else {
749                    Some(name.to_string())
750                },
751                addr.clone(),
752            ));
753        }
754
755        let mut past_members: Vec<Address<'static>> = Vec::new(); // Contents of `Chat-Group-Past-Members` header.
756        for (name, addr) in &self.past_members {
757            past_members.push(Address::new_address(
758                if name.is_empty() {
759                    None
760                } else {
761                    Some(name.to_string())
762                },
763                addr.clone(),
764            ));
765        }
766
767        ensure_and_debug_assert!(
768            self.member_timestamps.is_empty()
769                || to.len() + past_members.len() == self.member_timestamps.len(),
770            "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
771            to.len(),
772            past_members.len(),
773            self.member_timestamps.len(),
774        );
775        if to.is_empty() {
776            to.push(hidden_recipients());
777        }
778
779        // Start with Internet Message Format headers in the order of the standard example
780        // <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.1.1>.
781        headers.push(("From", from.into()));
782
783        if let Some(sender_displayname) = &self.sender_displayname {
784            let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
785            headers.push(("Sender", sender.into()));
786        }
787        headers.push((
788            "To",
789            mail_builder::headers::address::Address::new_list(to.clone()).into(),
790        ));
791        if !past_members.is_empty() {
792            headers.push((
793                "Chat-Group-Past-Members",
794                mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
795            ));
796        }
797
798        if let Loaded::Message { chat, .. } = &self.loaded
799            && chat.typ == Chattype::Group
800        {
801            if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await? {
802                headers.push((
803                    "Chat-Group-Member-Timestamps",
804                    mail_builder::headers::raw::Raw::new(
805                        self.member_timestamps
806                            .iter()
807                            .map(|ts| ts.to_string())
808                            .collect::<Vec<String>>()
809                            .join(" "),
810                    )
811                    .into(),
812                ));
813            }
814
815            if !self.member_fingerprints.is_empty() {
816                headers.push((
817                    "Chat-Group-Member-Fpr",
818                    mail_builder::headers::raw::Raw::new(
819                        self.member_fingerprints
820                            .iter()
821                            .map(|fp| fp.to_string())
822                            .collect::<Vec<String>>()
823                            .join(" "),
824                    )
825                    .into(),
826                ));
827            }
828        }
829
830        let subject_str = self.subject_str(context).await?;
831        headers.push((
832            "Subject",
833            mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
834        ));
835
836        let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
837            .unwrap()
838            .to_rfc2822();
839        headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
840
841        let rfc724_mid = match &self.loaded {
842            Loaded::Message { msg, .. } => match &self.pre_message_mode {
843                PreMessageMode::Pre { .. } => create_outgoing_rfc724_mid(),
844                _ => msg.rfc724_mid.clone(),
845            },
846            Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
847        };
848        headers.push((
849            "Message-ID",
850            mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
851        ));
852
853        // Reply headers as in <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.2>.
854        if !self.in_reply_to.is_empty() {
855            headers.push((
856                "In-Reply-To",
857                mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
858            ));
859        }
860        if !self.references.is_empty() {
861            headers.push((
862                "References",
863                mail_builder::headers::message_id::MessageId::<'static>::new_list(
864                    self.references.iter().map(|s| s.to_string()),
865                )
866                .into(),
867            ));
868        }
869
870        // Automatic Response headers <https://www.rfc-editor.org/rfc/rfc3834>
871        if let Loaded::Mdn { .. } = self.loaded {
872            headers.push((
873                "Auto-Submitted",
874                mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
875            ));
876        } else if context.get_config_bool(Config::Bot).await? {
877            headers.push((
878                "Auto-Submitted",
879                mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
880            ));
881        }
882
883        if let Loaded::Message { msg, chat } = &self.loaded
884            && (chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast)
885        {
886            headers.push((
887                "Chat-List-ID",
888                mail_builder::headers::text::Text::new(format!("{} <{}>", chat.name, chat.grpid))
889                    .into(),
890            ));
891
892            if msg.param.get_cmd() == SystemMessage::MemberAddedToGroup
893                && let Some(secret) = msg.param.get(PARAM_BROADCAST_SECRET)
894            {
895                headers.push((
896                    "Chat-Broadcast-Secret",
897                    mail_builder::headers::text::Text::new(secret.to_string()).into(),
898                ));
899            }
900        }
901
902        if let Loaded::Message { msg, .. } = &self.loaded {
903            if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
904                headers.push((
905                    "Chat-Edit",
906                    mail_builder::headers::message_id::MessageId::new(
907                        original_rfc724_mid.to_string(),
908                    )
909                    .into(),
910                ));
911            } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
912                headers.push((
913                    "Chat-Delete",
914                    mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
915                        .into(),
916                ));
917            }
918        }
919
920        // Non-standard headers.
921        headers.push((
922            "Chat-Version",
923            mail_builder::headers::raw::Raw::new("1.0").into(),
924        ));
925
926        if self.req_mdn {
927            // we use "Chat-Disposition-Notification-To"
928            // because replies to "Disposition-Notification-To" are weird in many cases
929            // eg. are just freetext and/or do not follow any standard.
930            headers.push((
931                "Chat-Disposition-Notification-To",
932                mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
933            ));
934        }
935
936        let grpimage = self.grpimage();
937        let skip_autocrypt = self.should_skip_autocrypt();
938        let encrypt_helper = EncryptHelper::new(context).await?;
939
940        if !skip_autocrypt {
941            // unless determined otherwise we add the Autocrypt header
942            let aheader = encrypt_helper.get_aheader().to_string();
943            headers.push((
944                "Autocrypt",
945                mail_builder::headers::raw::Raw::new(aheader).into(),
946            ));
947        }
948
949        if self.pre_message_mode == PreMessageMode::Post {
950            headers.push((
951                "Chat-Is-Post-Message",
952                mail_builder::headers::raw::Raw::new("1").into(),
953            ));
954        } else if let PreMessageMode::Pre {
955            post_msg_rfc724_mid,
956        } = &self.pre_message_mode
957        {
958            headers.push((
959                "Chat-Post-Message-ID",
960                mail_builder::headers::message_id::MessageId::new(post_msg_rfc724_mid.clone())
961                    .into(),
962            ));
963        }
964
965        let is_encrypted = self.will_be_encrypted();
966
967        // Add ephemeral timer for non-MDN messages.
968        // For MDNs it does not matter because they are not visible
969        // and ignored by the receiver.
970        if let Loaded::Message { msg, .. } = &self.loaded {
971            let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
972            if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
973                headers.push((
974                    "Ephemeral-Timer",
975                    mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
976                ));
977            }
978        }
979
980        let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
981            msg.param.get_cmd() == SystemMessage::SecurejoinMessage
982        } else {
983            false
984        };
985
986        let message: MimePart<'static> = match &self.loaded {
987            Loaded::Message { msg, .. } => {
988                let msg = msg.clone();
989                let (main_part, mut parts) = self
990                    .render_message(context, &mut headers, &grpimage, is_encrypted)
991                    .await?;
992                if parts.is_empty() {
993                    // Single part, render as regular message.
994                    main_part
995                } else {
996                    parts.insert(0, main_part);
997
998                    // Multiple parts, render as multipart.
999                    if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
1000                        MimePart::new("multipart/report; report-type=multi-device-sync", parts)
1001                    } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
1002                        MimePart::new("multipart/report; report-type=status-update", parts)
1003                    } else {
1004                        MimePart::new("multipart/mixed", parts)
1005                    }
1006                }
1007            }
1008            Loaded::Mdn { .. } => self.render_mdn()?,
1009        };
1010
1011        let HeadersByConfidentiality {
1012            mut unprotected_headers,
1013            hidden_headers,
1014            protected_headers,
1015        } = group_headers_by_confidentiality(
1016            headers,
1017            &self.from_addr,
1018            self.timestamp,
1019            is_encrypted,
1020            is_securejoin_message,
1021        );
1022
1023        let use_std_header_protection = context
1024            .get_config_bool(Config::StdHeaderProtectionComposing)
1025            .await?;
1026        let outer_message = if let Some(encryption_pubkeys) = self.encryption_pubkeys {
1027            let mut message = add_headers_to_encrypted_part(
1028                message,
1029                &unprotected_headers,
1030                hidden_headers,
1031                protected_headers,
1032                use_std_header_protection,
1033            );
1034
1035            // Add gossip headers in chats with multiple recipients
1036            let multiple_recipients =
1037                encryption_pubkeys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1038
1039            let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1040            let now = time();
1041
1042            match &self.loaded {
1043                Loaded::Message { chat, msg } => {
1044                    if !should_hide_recipients(msg, chat) {
1045                        for (addr, key) in &encryption_pubkeys {
1046                            let fingerprint = key.dc_fingerprint().hex();
1047                            let cmd = msg.param.get_cmd();
1048                            if self.pre_message_mode == PreMessageMode::Post {
1049                                continue;
1050                            }
1051
1052                            let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1053                                || cmd == SystemMessage::SecurejoinMessage
1054                                || multiple_recipients && {
1055                                    let gossiped_timestamp: Option<i64> = context
1056                                        .sql
1057                                        .query_get_value(
1058                                            "SELECT timestamp
1059                                         FROM gossip_timestamp
1060                                         WHERE chat_id=? AND fingerprint=?",
1061                                            (chat.id, &fingerprint),
1062                                        )
1063                                        .await?;
1064
1065                                    // `gossip_period == 0` is a special case for testing,
1066                                    // enabling gossip in every message.
1067                                    //
1068                                    // If current time is in the past compared to
1069                                    // `gossiped_timestamp`, we also gossip because
1070                                    // either the `gossiped_timestamp` or clock is wrong.
1071                                    gossip_period == 0
1072                                        || gossiped_timestamp
1073                                            .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1074                                };
1075
1076                            let verifier_id: Option<u32> = context
1077                                .sql
1078                                .query_get_value(
1079                                    "SELECT verifier FROM contacts WHERE fingerprint=?",
1080                                    (&fingerprint,),
1081                                )
1082                                .await?;
1083
1084                            let is_verified =
1085                                verifier_id.is_some_and(|verifier_id| verifier_id != 0);
1086
1087                            if !should_do_gossip {
1088                                continue;
1089                            }
1090
1091                            let header = Aheader {
1092                                addr: addr.clone(),
1093                                public_key: key.clone(),
1094                                // Autocrypt 1.1.0 specification says that
1095                                // `prefer-encrypt` attribute SHOULD NOT be included.
1096                                prefer_encrypt: EncryptPreference::NoPreference,
1097                                verified: is_verified,
1098                            }
1099                            .to_string();
1100
1101                            message = message.header(
1102                                "Autocrypt-Gossip",
1103                                mail_builder::headers::raw::Raw::new(header),
1104                            );
1105
1106                            context
1107                                .sql
1108                                .execute(
1109                                    "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1110                                     VALUES                       (?, ?, ?)
1111                                     ON CONFLICT                  (chat_id, fingerprint)
1112                                     DO UPDATE SET timestamp=excluded.timestamp",
1113                                    (chat.id, &fingerprint, now),
1114                                )
1115                                .await?;
1116                        }
1117                    }
1118                }
1119                Loaded::Mdn { .. } => {
1120                    // Never gossip in MDNs.
1121                }
1122            }
1123
1124            // Disable compression for SecureJoin to ensure
1125            // there are no compression side channels
1126            // leaking information about the tokens.
1127            let compress = match &self.loaded {
1128                Loaded::Message { msg, .. } => {
1129                    msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1130                }
1131                Loaded::Mdn { .. } => true,
1132            };
1133
1134            let shared_secret: Option<String> = match &self.loaded {
1135                Loaded::Message { chat, msg }
1136                    if should_encrypt_with_broadcast_secret(msg, chat) =>
1137                {
1138                    let secret = load_broadcast_secret(context, chat.id).await?;
1139                    if secret.is_none() {
1140                        // If there is no shared secret yet
1141                        // because this is an old broadcast channel,
1142                        // created before we had symmetric encryption,
1143                        // we show an error message.
1144                        let text = BROADCAST_INCOMPATIBILITY_MSG;
1145                        chat::add_info_msg(context, chat.id, text).await?;
1146                        bail!(text);
1147                    }
1148                    secret
1149                }
1150                _ => None,
1151            };
1152
1153            // Do not anonymize OpenPGP recipients.
1154            //
1155            // This is disabled to avoid interoperability problems
1156            // with old core versions <1.160.0 that do not support
1157            // receiving messages with wildcard Key IDs:
1158            // <https://github.com/chatmail/core/issues/7378>
1159            //
1160            // The option should be changed to true
1161            // once new core versions are sufficiently deployed.
1162            let anonymous_recipients = false;
1163
1164            if context.get_config_bool(Config::TestHooks).await?
1165                && let Some(hook) = &*context.pre_encrypt_mime_hook.lock()
1166            {
1167                message = hook(context, message);
1168            }
1169
1170            let encrypted = if let Some(shared_secret) = shared_secret {
1171                let sign = true;
1172                encrypt_helper
1173                    .encrypt_symmetrically(context, &shared_secret, message, compress, sign)
1174                    .await?
1175            } else {
1176                // Asymmetric encryption
1177
1178                let seipd_version = if encryption_pubkeys.is_empty() {
1179                    // If message is sent only to self,
1180                    // use v2 SEIPD.
1181                    SeipdVersion::V2
1182                } else {
1183                    // If message is sent to others,
1184                    // they may not support v2 SEIPD yet,
1185                    // so use v1 SEIPD.
1186                    SeipdVersion::V1
1187                };
1188
1189                // Encrypt to self unconditionally,
1190                // even for a single-device setup.
1191                let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1192                encryption_keyring
1193                    .extend(encryption_pubkeys.iter().map(|(_addr, key)| (*key).clone()));
1194
1195                encrypt_helper
1196                    .encrypt(
1197                        context,
1198                        encryption_keyring,
1199                        message,
1200                        compress,
1201                        anonymous_recipients,
1202                        seipd_version,
1203                    )
1204                    .await?
1205            };
1206
1207            wrap_encrypted_part(encrypted)
1208        } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1209            // Never add outer multipart/mixed wrapper to MDN
1210            // as multipart/report Content-Type is used to recognize MDNs
1211            // by Delta Chat receiver and Chatmail servers
1212            // allowing them to be unencrypted and not contain Autocrypt header
1213            // without resetting Autocrypt encryption or triggering Chatmail filter
1214            // that normally only allows encrypted mails.
1215
1216            // Hidden headers are dropped.
1217            message
1218        } else {
1219            let message = hidden_headers
1220                .into_iter()
1221                .fold(message, |message, (header, value)| {
1222                    message.header(header, value)
1223                });
1224            let message = MimePart::new("multipart/mixed", vec![message]);
1225            let mut message = protected_headers
1226                .iter()
1227                .fold(message, |message, (header, value)| {
1228                    message.header(*header, value.clone())
1229                });
1230
1231            if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
1232                // Deduplicate unprotected headers that also are in the protected headers:
1233                let protected: HashSet<&str> =
1234                    HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1235                unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1236
1237                message
1238            } else {
1239                for (h, v) in &mut message.headers {
1240                    if h == "Content-Type"
1241                        && let mail_builder::headers::HeaderType::ContentType(ct) = v
1242                    {
1243                        let mut ct_new = ct.clone();
1244                        ct_new = ct_new.attribute("protected-headers", "v1");
1245                        if use_std_header_protection {
1246                            ct_new = ct_new.attribute("hp", "clear");
1247                        }
1248                        *ct = ct_new;
1249                        break;
1250                    }
1251                }
1252
1253                let signature = encrypt_helper.sign(context, &message).await?;
1254                MimePart::new(
1255                    "multipart/signed; protocol=\"application/pgp-signature\"; protected",
1256                    vec![
1257                        message,
1258                        MimePart::new(
1259                            "application/pgp-signature; name=\"signature.asc\"",
1260                            signature,
1261                        )
1262                        .header(
1263                            "Content-Description",
1264                            mail_builder::headers::raw::Raw::<'static>::new(
1265                                "OpenPGP digital signature",
1266                            ),
1267                        )
1268                        .attachment("signature"),
1269                    ],
1270                )
1271            }
1272        };
1273
1274        let MimeFactory {
1275            last_added_location_id,
1276            ..
1277        } = self;
1278
1279        let message = render_outer_message(unprotected_headers, outer_message);
1280
1281        Ok(RenderedEmail {
1282            message,
1283            // envelope: Envelope::new,
1284            is_encrypted,
1285            last_added_location_id,
1286            sync_ids_to_delete: self.sync_ids_to_delete,
1287            rfc724_mid,
1288            subject: subject_str,
1289        })
1290    }
1291
1292    /// Returns MIME part with a `message.kml` attachment.
1293    fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1294        let Loaded::Message { msg, .. } = &self.loaded else {
1295            return None;
1296        };
1297
1298        let latitude = msg.param.get_float(Param::SetLatitude)?;
1299        let longitude = msg.param.get_float(Param::SetLongitude)?;
1300
1301        let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1302        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1303            .attachment("message.kml");
1304        Some(part)
1305    }
1306
1307    /// Returns MIME part with a `location.kml` attachment.
1308    async fn get_location_kml_part(
1309        &mut self,
1310        context: &Context,
1311    ) -> Result<Option<MimePart<'static>>> {
1312        let Loaded::Message { msg, .. } = &self.loaded else {
1313            return Ok(None);
1314        };
1315
1316        let Some((kml_content, last_added_location_id)) =
1317            location::get_kml(context, msg.chat_id).await?
1318        else {
1319            return Ok(None);
1320        };
1321
1322        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1323            .attachment("location.kml");
1324        if !msg.param.exists(Param::SetLatitude) {
1325            // otherwise, the independent location is already filed
1326            self.last_added_location_id = Some(last_added_location_id);
1327        }
1328        Ok(Some(part))
1329    }
1330
1331    async fn render_message(
1332        &mut self,
1333        context: &Context,
1334        headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1335        grpimage: &Option<String>,
1336        is_encrypted: bool,
1337    ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1338        let Loaded::Message { chat, msg } = &self.loaded else {
1339            bail!("Attempt to render MDN as a message");
1340        };
1341        let chat = chat.clone();
1342        let msg = msg.clone();
1343        let command = msg.param.get_cmd();
1344        let mut placeholdertext = None;
1345
1346        let send_verified_headers = match chat.typ {
1347            Chattype::Single => true,
1348            Chattype::Group => true,
1349            // Mailinglists and broadcast channels can actually never be verified:
1350            Chattype::Mailinglist => false,
1351            Chattype::OutBroadcast | Chattype::InBroadcast => false,
1352        };
1353
1354        if send_verified_headers {
1355            let was_protected: bool = context
1356                .sql
1357                .query_get_value("SELECT protected FROM chats WHERE id=?", (chat.id,))
1358                .await?
1359                .unwrap_or_default();
1360
1361            if was_protected {
1362                let unverified_member_exists = context
1363                    .sql
1364                    .exists(
1365                        "SELECT COUNT(*)
1366                        FROM contacts, chats_contacts
1367                        WHERE chats_contacts.contact_id=contacts.id AND chats_contacts.chat_id=?
1368                        AND contacts.id>9
1369                        AND contacts.verifier=0",
1370                        (chat.id,),
1371                    )
1372                    .await?;
1373
1374                if !unverified_member_exists {
1375                    headers.push((
1376                        "Chat-Verified",
1377                        mail_builder::headers::raw::Raw::new("1").into(),
1378                    ));
1379                }
1380            }
1381        }
1382
1383        if chat.typ == Chattype::Group {
1384            // Send group ID unless it is an ad hoc group that has no ID.
1385            if !chat.grpid.is_empty() {
1386                headers.push((
1387                    "Chat-Group-ID",
1388                    mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1389                ));
1390            }
1391        }
1392
1393        if chat.typ == Chattype::Group
1394            || chat.typ == Chattype::OutBroadcast
1395            || chat.typ == Chattype::InBroadcast
1396        {
1397            headers.push((
1398                "Chat-Group-Name",
1399                mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1400            ));
1401            if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1402                headers.push((
1403                    "Chat-Group-Name-Timestamp",
1404                    mail_builder::headers::text::Text::new(ts.to_string()).into(),
1405                ));
1406            }
1407
1408            match command {
1409                SystemMessage::MemberRemovedFromGroup => {
1410                    let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1411                    let fingerprint_to_remove = msg.param.get(Param::Arg4).unwrap_or_default();
1412
1413                    if email_to_remove
1414                        == context
1415                            .get_config(Config::ConfiguredAddr)
1416                            .await?
1417                            .unwrap_or_default()
1418                    {
1419                        placeholdertext = Some(format!("{email_to_remove} left the group."));
1420                    } else {
1421                        placeholdertext = Some(format!("Member {email_to_remove} was removed."));
1422                    };
1423
1424                    if !email_to_remove.is_empty() {
1425                        headers.push((
1426                            "Chat-Group-Member-Removed",
1427                            mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1428                                .into(),
1429                        ));
1430                    }
1431
1432                    if !fingerprint_to_remove.is_empty() {
1433                        headers.push((
1434                            "Chat-Group-Member-Removed-Fpr",
1435                            mail_builder::headers::raw::Raw::new(fingerprint_to_remove.to_string())
1436                                .into(),
1437                        ));
1438                    }
1439                }
1440                SystemMessage::MemberAddedToGroup => {
1441                    let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1442                    let fingerprint_to_add = msg.param.get(Param::Arg4).unwrap_or_default();
1443
1444                    placeholdertext = Some(format!("Member {email_to_add} was added."));
1445
1446                    if !email_to_add.is_empty() {
1447                        headers.push((
1448                            "Chat-Group-Member-Added",
1449                            mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1450                        ));
1451                    }
1452                    if !fingerprint_to_add.is_empty() {
1453                        headers.push((
1454                            "Chat-Group-Member-Added-Fpr",
1455                            mail_builder::headers::raw::Raw::new(fingerprint_to_add.to_string())
1456                                .into(),
1457                        ));
1458                    }
1459                    if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1460                        let step = "vg-member-added";
1461                        info!(context, "Sending secure-join message {:?}.", step);
1462                        headers.push((
1463                            "Secure-Join",
1464                            mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1465                        ));
1466                    }
1467                }
1468                SystemMessage::GroupNameChanged => {
1469                    placeholdertext = Some("Group name changed.".to_string());
1470                    let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1471                    headers.push((
1472                        "Chat-Group-Name-Changed",
1473                        mail_builder::headers::text::Text::new(old_name).into(),
1474                    ));
1475                }
1476                SystemMessage::GroupDescriptionChanged => {
1477                    placeholdertext = Some(
1478                        "[Chat description changed. To see this and other new features, please update the app]".to_string(),
1479                    );
1480                    headers.push((
1481                        "Chat-Group-Description-Changed",
1482                        mail_builder::headers::text::Text::new("").into(),
1483                    ));
1484                }
1485                SystemMessage::GroupImageChanged => {
1486                    placeholdertext = Some("Group image changed.".to_string());
1487                    headers.push((
1488                        "Chat-Content",
1489                        mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1490                    ));
1491                    if grpimage.is_none() && is_encrypted {
1492                        headers.push((
1493                            "Chat-Group-Avatar",
1494                            mail_builder::headers::raw::Raw::new("0").into(),
1495                        ));
1496                    }
1497                }
1498                SystemMessage::Unknown => {}
1499                SystemMessage::AutocryptSetupMessage => {}
1500                SystemMessage::SecurejoinMessage => {}
1501                SystemMessage::LocationStreamingEnabled => {}
1502                SystemMessage::LocationOnly => {}
1503                SystemMessage::EphemeralTimerChanged => {}
1504                SystemMessage::ChatProtectionEnabled => {}
1505                SystemMessage::ChatProtectionDisabled => {}
1506                SystemMessage::InvalidUnencryptedMail => {}
1507                SystemMessage::SecurejoinWait => {}
1508                SystemMessage::SecurejoinWaitTimeout => {}
1509                SystemMessage::MultiDeviceSync => {}
1510                SystemMessage::WebxdcStatusUpdate => {}
1511                SystemMessage::WebxdcInfoMessage => {}
1512                SystemMessage::IrohNodeAddr => {}
1513                SystemMessage::ChatE2ee => {}
1514                SystemMessage::CallAccepted => {}
1515                SystemMessage::CallEnded => {}
1516            }
1517
1518            if command == SystemMessage::GroupDescriptionChanged
1519                || command == SystemMessage::MemberAddedToGroup
1520                || msg
1521                    .param
1522                    .get_bool(Param::AttachChatAvatarAndDescription)
1523                    .unwrap_or_default()
1524            {
1525                let description = chat::get_chat_description(context, chat.id).await?;
1526                headers.push((
1527                    "Chat-Group-Description",
1528                    mail_builder::headers::text::Text::new(description.clone()).into(),
1529                ));
1530                if let Some(ts) = chat.param.get_i64(Param::GroupDescriptionTimestamp) {
1531                    headers.push((
1532                        "Chat-Group-Description-Timestamp",
1533                        mail_builder::headers::text::Text::new(ts.to_string()).into(),
1534                    ));
1535                }
1536            }
1537        }
1538
1539        match command {
1540            SystemMessage::LocationStreamingEnabled => {
1541                headers.push((
1542                    "Chat-Content",
1543                    mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1544                ));
1545            }
1546            SystemMessage::EphemeralTimerChanged => {
1547                headers.push((
1548                    "Chat-Content",
1549                    mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1550                ));
1551            }
1552            SystemMessage::LocationOnly
1553            | SystemMessage::MultiDeviceSync
1554            | SystemMessage::WebxdcStatusUpdate => {
1555                // This should prevent automatic replies,
1556                // such as non-delivery reports,
1557                // if the message is unencrypted.
1558                //
1559                // See <https://tools.ietf.org/html/rfc3834>
1560                headers.push((
1561                    "Auto-Submitted",
1562                    mail_builder::headers::raw::Raw::new("auto-generated").into(),
1563                ));
1564            }
1565            SystemMessage::AutocryptSetupMessage => {
1566                headers.push((
1567                    "Autocrypt-Setup-Message",
1568                    mail_builder::headers::raw::Raw::new("v1").into(),
1569                ));
1570
1571                placeholdertext = Some(ASM_SUBJECT.to_string());
1572            }
1573            SystemMessage::SecurejoinMessage => {
1574                let step = msg.param.get(Param::Arg).unwrap_or_default();
1575                if !step.is_empty() {
1576                    info!(context, "Sending secure-join message {step:?}.");
1577                    headers.push((
1578                        "Secure-Join",
1579                        mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1580                    ));
1581
1582                    let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1583                    if !param2.is_empty() {
1584                        headers.push((
1585                            if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1586                                "Secure-Join-Auth"
1587                            } else {
1588                                "Secure-Join-Invitenumber"
1589                            },
1590                            mail_builder::headers::text::Text::new(param2.to_string()).into(),
1591                        ));
1592                    }
1593
1594                    let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1595                    if !fingerprint.is_empty() {
1596                        headers.push((
1597                            "Secure-Join-Fingerprint",
1598                            mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1599                        ));
1600                    }
1601                    if let Some(id) = msg.param.get(Param::Arg4) {
1602                        headers.push((
1603                            "Secure-Join-Group",
1604                            mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1605                        ));
1606                    };
1607                }
1608            }
1609            SystemMessage::ChatProtectionEnabled => {
1610                headers.push((
1611                    "Chat-Content",
1612                    mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1613                ));
1614            }
1615            SystemMessage::ChatProtectionDisabled => {
1616                headers.push((
1617                    "Chat-Content",
1618                    mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1619                ));
1620            }
1621            SystemMessage::IrohNodeAddr => {
1622                let node_addr = context
1623                    .get_or_try_init_peer_channel()
1624                    .await?
1625                    .get_node_addr()
1626                    .await?;
1627
1628                // We should not send `null` as relay URL
1629                // as this is the only way to reach the node.
1630                debug_assert!(node_addr.relay_url().is_some());
1631                headers.push((
1632                    HeaderDef::IrohNodeAddr.into(),
1633                    mail_builder::headers::text::Text::new(serde_json::to_string(&node_addr)?)
1634                        .into(),
1635                ));
1636            }
1637            SystemMessage::CallAccepted => {
1638                headers.push((
1639                    "Chat-Content",
1640                    mail_builder::headers::raw::Raw::new("call-accepted").into(),
1641                ));
1642            }
1643            SystemMessage::CallEnded => {
1644                headers.push((
1645                    "Chat-Content",
1646                    mail_builder::headers::raw::Raw::new("call-ended").into(),
1647                ));
1648            }
1649            _ => {}
1650        }
1651
1652        if let Some(grpimage) = grpimage
1653            && is_encrypted
1654        {
1655            info!(context, "setting group image '{}'", grpimage);
1656            let avatar = build_avatar_file(context, grpimage)
1657                .await
1658                .context("Cannot attach group image")?;
1659            headers.push((
1660                "Chat-Group-Avatar",
1661                mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1662            ));
1663        }
1664
1665        if msg.viewtype == Viewtype::Sticker {
1666            headers.push((
1667                "Chat-Content",
1668                mail_builder::headers::raw::Raw::new("sticker").into(),
1669            ));
1670        } else if msg.viewtype == Viewtype::Call {
1671            headers.push((
1672                "Chat-Content",
1673                mail_builder::headers::raw::Raw::new("call").into(),
1674            ));
1675            placeholdertext = Some(
1676                "[This is a 'Call'. The sender uses an experiment not supported on your version yet]".to_string(),
1677            );
1678        }
1679
1680        if let Some(offer) = msg.param.get(Param::WebrtcRoom) {
1681            headers.push((
1682                "Chat-Webrtc-Room",
1683                mail_builder::headers::raw::Raw::new(b_encode(offer)).into(),
1684            ));
1685        } else if let Some(answer) = msg.param.get(Param::WebrtcAccepted) {
1686            headers.push((
1687                "Chat-Webrtc-Accepted",
1688                mail_builder::headers::raw::Raw::new(b_encode(answer)).into(),
1689            ));
1690        }
1691        if let Some(has_video) = msg.param.get(Param::WebrtcHasVideoInitially) {
1692            headers.push((
1693                "Chat-Webrtc-Has-Video-Initially",
1694                mail_builder::headers::raw::Raw::new(b_encode(has_video)).into(),
1695            ))
1696        }
1697
1698        if msg.viewtype == Viewtype::Voice
1699            || msg.viewtype == Viewtype::Audio
1700            || msg.viewtype == Viewtype::Video
1701        {
1702            if msg.viewtype == Viewtype::Voice {
1703                headers.push((
1704                    "Chat-Voice-Message",
1705                    mail_builder::headers::raw::Raw::new("1").into(),
1706                ));
1707            }
1708            let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1709            if duration_ms > 0 {
1710                let dur = duration_ms.to_string();
1711                headers.push((
1712                    "Chat-Duration",
1713                    mail_builder::headers::raw::Raw::new(dur).into(),
1714                ));
1715            }
1716        }
1717
1718        // add text part - we even add empty text and force a MIME-multipart-message as:
1719        // - some Apps have problems with Non-text in the main part (eg. "Mail" from stock Android)
1720        // - we can add "forward hints" this way
1721        // - it looks better
1722
1723        let afwd_email = msg.param.exists(Param::Forwarded);
1724        let fwdhint = if afwd_email {
1725            Some(
1726                "---------- Forwarded message ----------\r\n\
1727                 From: Delta Chat\r\n\
1728                 \r\n"
1729                    .to_string(),
1730            )
1731        } else {
1732            None
1733        };
1734
1735        let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1736
1737        let mut quoted_text = None;
1738        if let Some(msg_quoted_text) = msg.quoted_text() {
1739            let mut some_quoted_text = String::new();
1740            for quoted_line in msg_quoted_text.split('\n') {
1741                some_quoted_text += "> ";
1742                some_quoted_text += quoted_line;
1743                some_quoted_text += "\r\n";
1744            }
1745            some_quoted_text += "\r\n";
1746            quoted_text = Some(some_quoted_text)
1747        }
1748
1749        if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1750            // Message is not encrypted but quotes encrypted message.
1751            quoted_text = Some("> ...\r\n\r\n".to_string());
1752        }
1753        if quoted_text.is_none() && final_text.starts_with('>') {
1754            // Insert empty line to avoid receiver treating user-sent quote as topquote inserted by
1755            // Delta Chat.
1756            quoted_text = Some("\r\n".to_string());
1757        }
1758
1759        let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1760
1761        let footer = if is_reaction { "" } else { &self.selfstatus };
1762
1763        let message_text = if self.pre_message_mode == PreMessageMode::Post {
1764            "".to_string()
1765        } else {
1766            format!(
1767                "{}{}{}{}{}{}",
1768                fwdhint.unwrap_or_default(),
1769                quoted_text.unwrap_or_default(),
1770                escape_message_footer_marks(final_text),
1771                if !final_text.is_empty() && !footer.is_empty() {
1772                    "\r\n\r\n"
1773                } else {
1774                    ""
1775                },
1776                if !footer.is_empty() { "-- \r\n" } else { "" },
1777                footer
1778            )
1779        };
1780
1781        let mut main_part = MimePart::new("text/plain", message_text);
1782        if is_reaction {
1783            main_part = main_part.header(
1784                "Content-Disposition",
1785                mail_builder::headers::raw::Raw::new("reaction"),
1786            );
1787        }
1788
1789        let mut parts = Vec::new();
1790
1791        if msg.has_html() {
1792            let html = if let Some(html) = msg.param.get(Param::SendHtml) {
1793                Some(html.to_string())
1794            } else if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded)
1795                && orig_msg_id != 0
1796            {
1797                // Legacy forwarded messages may not have `Param::SendHtml` set. Let's hope the
1798                // original message exists.
1799                MsgId::new(orig_msg_id.try_into()?)
1800                    .get_html(context)
1801                    .await?
1802            } else {
1803                None
1804            };
1805            if let Some(html) = html {
1806                main_part = MimePart::new(
1807                    "multipart/alternative",
1808                    vec![main_part, MimePart::new("text/html", html)],
1809                )
1810            }
1811        }
1812
1813        // add attachment part
1814        if msg.viewtype.has_file() {
1815            if let PreMessageMode::Pre { .. } = self.pre_message_mode {
1816                let Some(metadata) = PostMsgMetadata::from_msg(context, &msg).await? else {
1817                    bail!("Failed to generate metadata for pre-message")
1818                };
1819
1820                headers.push((
1821                    HeaderDef::ChatPostMessageMetadata.into(),
1822                    mail_builder::headers::raw::Raw::new(metadata.to_header_value()?).into(),
1823                ));
1824            } else {
1825                let file_part = build_body_file(context, &msg).await?;
1826                parts.push(file_part);
1827            }
1828        }
1829
1830        if let Some(msg_kml_part) = self.get_message_kml_part() {
1831            parts.push(msg_kml_part);
1832        }
1833
1834        if location::is_sending_locations_to_chat(context, Some(msg.chat_id)).await?
1835            && let Some(part) = self.get_location_kml_part(context).await?
1836        {
1837            parts.push(part);
1838        }
1839
1840        // we do not piggyback sync-files to other self-sent-messages
1841        // to not risk files becoming too larger and being skipped by download-on-demand.
1842        if command == SystemMessage::MultiDeviceSync {
1843            let json = msg.param.get(Param::Arg).unwrap_or_default();
1844            let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1845            parts.push(context.build_sync_part(json.to_string()));
1846            self.sync_ids_to_delete = Some(ids.to_string());
1847        } else if command == SystemMessage::WebxdcStatusUpdate {
1848            let json = msg.param.get(Param::Arg).unwrap_or_default();
1849            parts.push(context.build_status_update_part(json));
1850        } else if msg.viewtype == Viewtype::Webxdc {
1851            let topic = self
1852                .webxdc_topic
1853                .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1854                .unwrap_or(create_iroh_header(context, msg.id).await?);
1855            headers.push((
1856                HeaderDef::IrohGossipTopic.get_headername(),
1857                mail_builder::headers::raw::Raw::new(topic).into(),
1858            ));
1859            if let (Some(json), _) = context
1860                .render_webxdc_status_update_object(
1861                    msg.id,
1862                    StatusUpdateSerial::MIN,
1863                    StatusUpdateSerial::MAX,
1864                    None,
1865                )
1866                .await?
1867            {
1868                parts.push(context.build_status_update_part(&json));
1869            }
1870        }
1871
1872        self.attach_selfavatar =
1873            self.attach_selfavatar && self.pre_message_mode != PreMessageMode::Post;
1874        if self.attach_selfavatar {
1875            match context.get_config(Config::Selfavatar).await? {
1876                Some(path) => match build_avatar_file(context, &path).await {
1877                    Ok(avatar) => headers.push((
1878                        "Chat-User-Avatar",
1879                        mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1880                    )),
1881                    Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1882                },
1883                None => headers.push((
1884                    "Chat-User-Avatar",
1885                    mail_builder::headers::raw::Raw::new("0").into(),
1886                )),
1887            }
1888        }
1889
1890        Ok((main_part, parts))
1891    }
1892
1893    /// Render an MDN
1894    #[expect(clippy::arithmetic_side_effects)]
1895    fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1896        // RFC 6522, this also requires the `report-type` parameter which is equal
1897        // to the MIME subtype of the second body part of the multipart/report
1898        let Loaded::Mdn {
1899            rfc724_mid,
1900            additional_msg_ids,
1901        } = &self.loaded
1902        else {
1903            bail!("Attempt to render a message as MDN");
1904        };
1905
1906        // first body part: always human-readable, always REQUIRED by RFC 6522.
1907        // untranslated to no reveal sender's language.
1908        // moreover, translations in unknown languages are confusing, and clients may not display them at all
1909        let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1910
1911        let mut message = MimePart::new(
1912            "multipart/report; report-type=disposition-notification",
1913            vec![text_part],
1914        );
1915
1916        // second body part: machine-readable, always REQUIRED by RFC 6522
1917        let message_text2 = format!(
1918            "Original-Recipient: rfc822;{}\r\n\
1919             Final-Recipient: rfc822;{}\r\n\
1920             Original-Message-ID: <{}>\r\n\
1921             Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1922            self.from_addr, self.from_addr, rfc724_mid
1923        );
1924
1925        let extension_fields = if additional_msg_ids.is_empty() {
1926            "".to_string()
1927        } else {
1928            "Additional-Message-IDs: ".to_string()
1929                + &additional_msg_ids
1930                    .iter()
1931                    .map(|mid| render_rfc724_mid(mid))
1932                    .collect::<Vec<String>>()
1933                    .join(" ")
1934                + "\r\n"
1935        };
1936
1937        message.add_part(MimePart::new(
1938            "message/disposition-notification",
1939            message_text2 + &extension_fields,
1940        ));
1941
1942        Ok(message)
1943    }
1944
1945    pub fn will_be_encrypted(&self) -> bool {
1946        self.encryption_pubkeys.is_some()
1947    }
1948
1949    pub fn set_as_post_message(&mut self) {
1950        self.pre_message_mode = PreMessageMode::Post;
1951    }
1952
1953    pub fn set_as_pre_message_for(&mut self, post_message: &RenderedEmail) {
1954        self.pre_message_mode = PreMessageMode::Pre {
1955            post_msg_rfc724_mid: post_message.rfc724_mid.clone(),
1956        };
1957    }
1958}
1959
1960/// Stores the unprotected headers on the outer message, and renders it.
1961fn render_outer_message(
1962    unprotected_headers: Vec<(&'static str, HeaderType<'static>)>,
1963    outer_message: MimePart<'static>,
1964) -> String {
1965    let outer_message = unprotected_headers
1966        .into_iter()
1967        .fold(outer_message, |message, (header, value)| {
1968            message.header(header, value)
1969        });
1970
1971    let mut buffer = Vec::new();
1972    let cursor = Cursor::new(&mut buffer);
1973    outer_message.clone().write_part(cursor).ok();
1974    String::from_utf8_lossy(&buffer).to_string()
1975}
1976
1977/// Takes the encrypted part, wraps it in a MimePart,
1978/// and sets the appropriate Content-Type for the outer message
1979fn wrap_encrypted_part(encrypted: String) -> MimePart<'static> {
1980    // XXX: additional newline is needed
1981    // to pass filtermail at
1982    // <https://github.com/deltachat/chatmail/blob/4d915f9800435bf13057d41af8d708abd34dbfa8/chatmaild/src/chatmaild/filtermail.py#L84-L86>:
1983    let encrypted = encrypted + "\n";
1984
1985    MimePart::new(
1986        "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1987        vec![
1988            // Autocrypt part 1
1989            MimePart::new("application/pgp-encrypted", "Version: 1\r\n").header(
1990                "Content-Description",
1991                mail_builder::headers::raw::Raw::new("PGP/MIME version identification"),
1992            ),
1993            // Autocrypt part 2
1994            MimePart::new(
1995                "application/octet-stream; name=\"encrypted.asc\"",
1996                encrypted,
1997            )
1998            .header(
1999                "Content-Description",
2000                mail_builder::headers::raw::Raw::new("OpenPGP encrypted message"),
2001            )
2002            .header(
2003                "Content-Disposition",
2004                mail_builder::headers::raw::Raw::new("inline; filename=\"encrypted.asc\";"),
2005            ),
2006        ],
2007    )
2008}
2009
2010fn add_headers_to_encrypted_part(
2011    message: MimePart<'static>,
2012    unprotected_headers: &[(&'static str, HeaderType<'static>)],
2013    hidden_headers: Vec<(&'static str, HeaderType<'static>)>,
2014    protected_headers: Vec<(&'static str, HeaderType<'static>)>,
2015    use_std_header_protection: bool,
2016) -> MimePart<'static> {
2017    // Store protected headers in the inner message.
2018    let message = protected_headers
2019        .into_iter()
2020        .fold(message, |message, (header, value)| {
2021            message.header(header, value)
2022        });
2023
2024    // Add hidden headers to encrypted payload.
2025    let mut message: MimePart<'static> = hidden_headers
2026        .into_iter()
2027        .fold(message, |message, (header, value)| {
2028            message.header(header, value)
2029        });
2030
2031    if use_std_header_protection {
2032        message = unprotected_headers
2033            .iter()
2034            // Structural headers shouldn't be added as "HP-Outer". They are defined in
2035            // <https://www.rfc-editor.org/rfc/rfc9787.html#structural-header-fields>.
2036            .filter(|(name, _)| {
2037                !(name.eq_ignore_ascii_case("mime-version")
2038                    || name.eq_ignore_ascii_case("content-type")
2039                    || name.eq_ignore_ascii_case("content-transfer-encoding")
2040                    || name.eq_ignore_ascii_case("content-disposition"))
2041            })
2042            .fold(message, |message, (name, value)| {
2043                message.header(format!("HP-Outer: {name}"), value.clone())
2044            });
2045    }
2046
2047    // Set the appropriate Content-Type for the inner message
2048    for (h, v) in &mut message.headers {
2049        if h == "Content-Type"
2050            && let mail_builder::headers::HeaderType::ContentType(ct) = v
2051        {
2052            let mut ct_new = ct.clone();
2053            ct_new = ct_new.attribute("protected-headers", "v1");
2054            if use_std_header_protection {
2055                ct_new = ct_new.attribute("hp", "cipher");
2056            }
2057            *ct = ct_new;
2058            break;
2059        }
2060    }
2061
2062    message
2063}
2064
2065struct HeadersByConfidentiality {
2066    /// Headers that must go into IMF header section.
2067    ///
2068    /// These are standard headers such as Date, In-Reply-To, References, which cannot be placed
2069    /// anywhere else according to the standard. Placing headers here also allows them to be fetched
2070    /// individually over IMAP without downloading the message body. This is why Chat-Version is
2071    /// placed here.
2072    unprotected_headers: Vec<(&'static str, HeaderType<'static>)>,
2073
2074    /// Headers that MUST NOT (only) go into IMF header section:
2075    /// - Large headers which may hit the header section size limit on the server, such as
2076    ///   Chat-User-Avatar with a base64-encoded image inside.
2077    /// - Headers duplicated here that servers mess up with in the IMF header section, like
2078    ///   Message-ID.
2079    /// - Nonstandard headers that should be DKIM-protected because e.g. OpenDKIM only signs
2080    ///   known headers.
2081    ///
2082    /// The header should be hidden from MTA
2083    /// by moving it either into protected part
2084    /// in case of encrypted mails
2085    /// or unprotected MIME preamble in case of unencrypted mails.
2086    hidden_headers: Vec<(&'static str, HeaderType<'static>)>,
2087
2088    /// Opportunistically protected headers.
2089    ///
2090    /// These headers are placed into encrypted part *if* the message is encrypted. Place headers
2091    /// which are not needed before decryption (e.g. Chat-Group-Name) or are not interesting if the
2092    /// message cannot be decrypted (e.g. Chat-Disposition-Notification-To) here.
2093    ///
2094    /// If the message is not encrypted, these headers are placed into IMF header section, so make
2095    /// sure that the message will be encrypted if you place any sensitive information here.
2096    protected_headers: Vec<(&'static str, HeaderType<'static>)>,
2097}
2098
2099/// Split headers based on header confidentiality policy.
2100/// See [`HeadersByConfidentiality`] for more info.
2101fn group_headers_by_confidentiality(
2102    headers: Vec<(&'static str, HeaderType<'static>)>,
2103    from_addr: &str,
2104    timestamp: i64,
2105    is_encrypted: bool,
2106    is_securejoin_message: bool,
2107) -> HeadersByConfidentiality {
2108    let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2109    let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2110    let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2111
2112    // MIME header <https://datatracker.ietf.org/doc/html/rfc2045>.
2113    unprotected_headers.push((
2114        "MIME-Version",
2115        mail_builder::headers::raw::Raw::new("1.0").into(),
2116    ));
2117
2118    for header @ (original_header_name, _header_value) in &headers {
2119        let header_name = original_header_name.to_lowercase();
2120        if header_name == "message-id" {
2121            unprotected_headers.push(header.clone());
2122            hidden_headers.push(header.clone());
2123        } else if is_hidden(&header_name) {
2124            hidden_headers.push(header.clone());
2125        } else if header_name == "from" {
2126            // Unencrypted securejoin messages should _not_ include the display name:
2127            if is_encrypted || !is_securejoin_message {
2128                protected_headers.push(header.clone());
2129            }
2130
2131            unprotected_headers.push((
2132                original_header_name,
2133                Address::new_address(None::<&'static str>, from_addr.to_string()).into(),
2134            ));
2135        } else if header_name == "to" {
2136            protected_headers.push(header.clone());
2137            if is_encrypted {
2138                unprotected_headers.push(("To", hidden_recipients().into()));
2139            } else {
2140                unprotected_headers.push(header.clone());
2141            }
2142        } else if header_name == "chat-broadcast-secret" {
2143            if is_encrypted {
2144                protected_headers.push(header.clone());
2145            }
2146        } else if is_encrypted && header_name == "date" {
2147            protected_headers.push(header.clone());
2148
2149            // Randomized date goes to unprotected header.
2150            //
2151            // We cannot just send "Thu, 01 Jan 1970 00:00:00 +0000"
2152            // or omit the header because GMX then fails with
2153            //
2154            // host mx00.emig.gmx.net[212.227.15.9] said:
2155            // 554-Transaction failed
2156            // 554-Reject due to policy restrictions.
2157            // 554 For explanation visit https://postmaster.gmx.net/en/case?...
2158            // (in reply to end of DATA command)
2159            //
2160            // and the explanation page says
2161            // "The time information deviates too much from the actual time".
2162            //
2163            // We also limit the range to 6 days (518400 seconds)
2164            // because with a larger range we got
2165            // error "500 Date header far in the past/future"
2166            // which apparently originates from Symantec Messaging Gateway
2167            // and means the message has a Date that is more
2168            // than 7 days in the past:
2169            // <https://github.com/chatmail/core/issues/7466>
2170            let timestamp_offset = rand::random_range(0..518400);
2171            let protected_timestamp = timestamp.saturating_sub(timestamp_offset);
2172            let unprotected_date =
2173                chrono::DateTime::<chrono::Utc>::from_timestamp(protected_timestamp, 0)
2174                    .unwrap()
2175                    .to_rfc2822();
2176            unprotected_headers.push((
2177                "Date",
2178                mail_builder::headers::raw::Raw::new(unprotected_date).into(),
2179            ));
2180        } else if is_encrypted {
2181            protected_headers.push(header.clone());
2182
2183            match header_name.as_str() {
2184                "subject" => {
2185                    unprotected_headers.push((
2186                        "Subject",
2187                        mail_builder::headers::raw::Raw::new("[...]").into(),
2188                    ));
2189                }
2190                "chat-version" | "autocrypt-setup-message" | "chat-is-post-message" => {
2191                    unprotected_headers.push(header.clone());
2192                }
2193                _ => {
2194                    // Other headers are removed from unprotected part.
2195                }
2196            }
2197        } else {
2198            // Copy the header to the protected headers
2199            // in case of signed-only message.
2200            // If the message is not signed, this value will not be used.
2201            protected_headers.push(header.clone());
2202            unprotected_headers.push(header.clone())
2203        }
2204    }
2205    HeadersByConfidentiality {
2206        unprotected_headers,
2207        hidden_headers,
2208        protected_headers,
2209    }
2210}
2211
2212fn hidden_recipients() -> Address<'static> {
2213    Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
2214}
2215
2216fn should_encrypt_with_broadcast_secret(msg: &Message, chat: &Chat) -> bool {
2217    chat.typ == Chattype::OutBroadcast && must_have_only_one_recipient(msg, chat).is_none()
2218}
2219
2220fn should_hide_recipients(msg: &Message, chat: &Chat) -> bool {
2221    should_encrypt_with_broadcast_secret(msg, chat)
2222}
2223
2224fn should_encrypt_symmetrically(msg: &Message, chat: &Chat) -> bool {
2225    should_encrypt_with_broadcast_secret(msg, chat)
2226}
2227
2228/// Some messages sent into outgoing broadcast channels (member-added/member-removed)
2229/// should only go to a single recipient,
2230/// rather than all recipients.
2231/// This function returns the fingerprint of the recipient the message should be sent to.
2232fn must_have_only_one_recipient<'a>(msg: &'a Message, chat: &Chat) -> Option<Result<&'a str>> {
2233    if chat.typ == Chattype::OutBroadcast
2234        && matches!(
2235            msg.param.get_cmd(),
2236            SystemMessage::MemberRemovedFromGroup | SystemMessage::MemberAddedToGroup
2237        )
2238    {
2239        let Some(fp) = msg.param.get(Param::Arg4) else {
2240            return Some(Err(format_err!("Missing removed/added member")));
2241        };
2242        return Some(Ok(fp));
2243    }
2244    None
2245}
2246
2247async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
2248    let file_name = msg.get_filename().context("msg has no file")?;
2249    let blob = msg
2250        .param
2251        .get_file_blob(context)?
2252        .context("msg has no file")?;
2253    let mimetype = msg
2254        .param
2255        .get(Param::MimeType)
2256        .unwrap_or("application/octet-stream")
2257        .to_string();
2258    let body = fs::read(blob.to_abs_path()).await?;
2259
2260    // create mime part, for Content-Disposition, see RFC 2183.
2261    // `Content-Disposition: attachment` seems not to make a difference to `Content-Disposition: inline`
2262    // at least on tested Thunderbird and Gma'l in 2017.
2263    // But I've heard about problems with inline and outl'k, so we just use the attachment-type until we
2264    // run into other problems ...
2265    let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
2266
2267    Ok(mail)
2268}
2269
2270async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
2271    let blob = match path.starts_with("$BLOBDIR/") {
2272        true => BlobObject::from_name(context, path)?,
2273        false => BlobObject::from_path(context, path.as_ref())?,
2274    };
2275    let body = fs::read(blob.to_abs_path()).await?;
2276    let encoded_body = base64::engine::general_purpose::STANDARD
2277        .encode(&body)
2278        .chars()
2279        .enumerate()
2280        .fold(String::new(), |mut res, (i, c)| {
2281            if i % 78 == 77 {
2282                res.push(' ')
2283            }
2284            res.push(c);
2285            res
2286        });
2287    Ok(encoded_body)
2288}
2289
2290fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
2291    let addr_lc = addr.to_lowercase();
2292    recipients
2293        .iter()
2294        .any(|(_, cur)| cur.to_lowercase() == addr_lc)
2295}
2296
2297fn render_rfc724_mid(rfc724_mid: &str) -> String {
2298    let rfc724_mid = rfc724_mid.trim().to_string();
2299
2300    if rfc724_mid.chars().next().unwrap_or_default() == '<' {
2301        rfc724_mid
2302    } else {
2303        format!("<{rfc724_mid}>")
2304    }
2305}
2306
2307/// Encodes UTF-8 string as a single B-encoded-word.
2308///
2309/// We manually encode some headers because as of
2310/// version 0.4.4 mail-builder crate does not encode
2311/// newlines correctly if they appear in a text header.
2312fn b_encode(value: &str) -> String {
2313    format!(
2314        "=?utf-8?B?{}?=",
2315        base64::engine::general_purpose::STANDARD.encode(value)
2316    )
2317}
2318
2319pub(crate) async fn render_symm_encrypted_securejoin_message(
2320    context: &Context,
2321    step: &str,
2322    rfc724_mid: &str,
2323    attach_self_pubkey: bool,
2324    auth: &str,
2325) -> Result<String> {
2326    info!(context, "Sending secure-join message {step:?}.");
2327
2328    let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
2329
2330    let from_addr = context.get_primary_self_addr().await?;
2331    let from = new_address_with_name("", from_addr.to_string());
2332    headers.push(("From", from.into()));
2333
2334    let to: Vec<Address<'static>> = vec![hidden_recipients()];
2335    headers.push((
2336        "To",
2337        mail_builder::headers::address::Address::new_list(to.clone()).into(),
2338    ));
2339
2340    headers.push((
2341        "Subject",
2342        mail_builder::headers::text::Text::new("Secure-Join".to_string()).into(),
2343    ));
2344
2345    let timestamp = create_smeared_timestamp(context);
2346    let date = chrono::DateTime::<chrono::Utc>::from_timestamp(timestamp, 0)
2347        .unwrap()
2348        .to_rfc2822();
2349    headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
2350
2351    headers.push((
2352        "Message-ID",
2353        mail_builder::headers::message_id::MessageId::new(rfc724_mid.to_string()).into(),
2354    ));
2355
2356    // Automatic Response headers <https://www.rfc-editor.org/rfc/rfc3834>
2357    if context.get_config_bool(Config::Bot).await? {
2358        headers.push((
2359            "Auto-Submitted",
2360            mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
2361        ));
2362    }
2363
2364    let encrypt_helper = EncryptHelper::new(context).await?;
2365
2366    if attach_self_pubkey {
2367        let aheader = encrypt_helper.get_aheader().to_string();
2368        headers.push((
2369            "Autocrypt",
2370            mail_builder::headers::raw::Raw::new(aheader).into(),
2371        ));
2372    }
2373
2374    headers.push((
2375        "Secure-Join",
2376        mail_builder::headers::raw::Raw::new(step.to_string()).into(),
2377    ));
2378
2379    headers.push((
2380        "Secure-Join-Auth",
2381        mail_builder::headers::text::Text::new(auth.to_string()).into(),
2382    ));
2383
2384    let message: MimePart<'static> = MimePart::new("text/plain", "Secure-Join");
2385
2386    let is_encrypted = true;
2387    let is_securejoin_message = true;
2388    let HeadersByConfidentiality {
2389        unprotected_headers,
2390        hidden_headers,
2391        protected_headers,
2392    } = group_headers_by_confidentiality(
2393        headers,
2394        &from_addr,
2395        timestamp,
2396        is_encrypted,
2397        is_securejoin_message,
2398    );
2399
2400    let outer_message = {
2401        let use_std_header_protection = true;
2402        let message = add_headers_to_encrypted_part(
2403            message,
2404            &unprotected_headers,
2405            hidden_headers,
2406            protected_headers,
2407            use_std_header_protection,
2408        );
2409
2410        // Disable compression for SecureJoin to ensure
2411        // there are no compression side channels
2412        // leaking information about the tokens.
2413        let compress = false;
2414        // Only sign the message if we attach the pubkey.
2415        let sign = attach_self_pubkey;
2416        let encrypted = encrypt_helper
2417            .encrypt_symmetrically(context, auth, message, compress, sign)
2418            .await?;
2419
2420        wrap_encrypted_part(encrypted)
2421    };
2422
2423    let message = render_outer_message(unprotected_headers, outer_message);
2424
2425    Ok(message)
2426}
2427
2428#[cfg(test)]
2429mod mimefactory_tests;