deltachat/
mimefactory.rs

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