deltachat/
mimefactory.rs

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