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