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