deltachat/
mimefactory.rs

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