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