Skip to main content

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            let encrypted = if let Some(shared_secret) = shared_secret {
1172                let sign = true;
1173                encrypt_helper
1174                    .encrypt_symmetrically(context, &shared_secret, message, compress, sign)
1175                    .await?
1176            } else {
1177                // Asymmetric encryption
1178
1179                // Use SEIPDv2 if all recipients support it.
1180                let seipd_version = if encryption_pubkeys
1181                    .iter()
1182                    .all(|(_addr, pubkey)| pubkey_supports_seipdv2(pubkey))
1183                {
1184                    SeipdVersion::V2
1185                } else {
1186                    SeipdVersion::V1
1187                };
1188
1189                // Encrypt to self unconditionally,
1190                // even for a single-device setup.
1191                let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1192                encryption_keyring
1193                    .extend(encryption_pubkeys.iter().map(|(_addr, key)| (*key).clone()));
1194
1195                encrypt_helper
1196                    .encrypt(
1197                        context,
1198                        encryption_keyring,
1199                        message,
1200                        compress,
1201                        seipd_version,
1202                    )
1203                    .await?
1204            };
1205
1206            wrap_encrypted_part(encrypted)
1207        } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1208            // Never add outer multipart/mixed wrapper to MDN
1209            // as multipart/report Content-Type is used to recognize MDNs
1210            // by Delta Chat receiver and Chatmail servers
1211            // allowing them to be unencrypted and not contain Autocrypt header
1212            // without resetting Autocrypt encryption or triggering Chatmail filter
1213            // that normally only allows encrypted mails.
1214
1215            // Hidden headers are dropped.
1216            message
1217        } else {
1218            let message = hidden_headers
1219                .into_iter()
1220                .fold(message, |message, (header, value)| {
1221                    message.header(header, value)
1222                });
1223            let message = MimePart::new("multipart/mixed", vec![message]);
1224            let message = protected_headers
1225                .iter()
1226                .fold(message, |message, (header, value)| {
1227                    message.header(*header, value.clone())
1228                });
1229
1230            // Deduplicate unprotected headers that also are in the protected headers:
1231            let protected: HashSet<&str> =
1232                HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1233            unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1234
1235            message
1236        };
1237
1238        let MimeFactory {
1239            last_added_location_id,
1240            ..
1241        } = self;
1242
1243        let message = render_outer_message(unprotected_headers, outer_message);
1244
1245        Ok(RenderedEmail {
1246            message,
1247            // envelope: Envelope::new,
1248            is_encrypted,
1249            last_added_location_id,
1250            sync_ids_to_delete: self.sync_ids_to_delete,
1251            rfc724_mid,
1252            subject: subject_str,
1253        })
1254    }
1255
1256    /// Returns MIME part with a `message.kml` attachment.
1257    fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1258        let Loaded::Message { msg, .. } = &self.loaded else {
1259            return None;
1260        };
1261
1262        let latitude = msg.param.get_float(Param::SetLatitude)?;
1263        let longitude = msg.param.get_float(Param::SetLongitude)?;
1264
1265        let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1266        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1267            .attachment("message.kml");
1268        Some(part)
1269    }
1270
1271    /// Returns MIME part with a `location.kml` attachment.
1272    async fn get_location_kml_part(
1273        &mut self,
1274        context: &Context,
1275    ) -> Result<Option<MimePart<'static>>> {
1276        let Loaded::Message { msg, .. } = &self.loaded else {
1277            return Ok(None);
1278        };
1279
1280        let Some((kml_content, last_added_location_id)) =
1281            location::get_kml(context, msg.chat_id).await?
1282        else {
1283            return Ok(None);
1284        };
1285
1286        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1287            .attachment("location.kml");
1288        if !msg.param.exists(Param::SetLatitude) {
1289            // otherwise, the independent location is already filed
1290            self.last_added_location_id = Some(last_added_location_id);
1291        }
1292        Ok(Some(part))
1293    }
1294
1295    async fn render_message(
1296        &mut self,
1297        context: &Context,
1298        headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1299        grpimage: &Option<String>,
1300        is_encrypted: bool,
1301    ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1302        let Loaded::Message { chat, msg } = &self.loaded else {
1303            bail!("Attempt to render MDN as a message");
1304        };
1305        let chat = chat.clone();
1306        let msg = msg.clone();
1307        let command = msg.param.get_cmd();
1308        let mut placeholdertext = None;
1309
1310        let send_verified_headers = match chat.typ {
1311            Chattype::Single => true,
1312            Chattype::Group => true,
1313            // Mailinglists and broadcast channels can actually never be verified:
1314            Chattype::Mailinglist => false,
1315            Chattype::OutBroadcast | Chattype::InBroadcast => false,
1316        };
1317
1318        if send_verified_headers {
1319            let was_protected: bool = context
1320                .sql
1321                .query_get_value("SELECT protected FROM chats WHERE id=?", (chat.id,))
1322                .await?
1323                .unwrap_or_default();
1324
1325            if was_protected {
1326                let unverified_member_exists = context
1327                    .sql
1328                    .exists(
1329                        "SELECT COUNT(*)
1330                        FROM contacts, chats_contacts
1331                        WHERE chats_contacts.contact_id=contacts.id AND chats_contacts.chat_id=?
1332                        AND contacts.id>9
1333                        AND contacts.verifier=0",
1334                        (chat.id,),
1335                    )
1336                    .await?;
1337
1338                if !unverified_member_exists {
1339                    headers.push((
1340                        "Chat-Verified",
1341                        mail_builder::headers::raw::Raw::new("1").into(),
1342                    ));
1343                }
1344            }
1345        }
1346
1347        if chat.typ == Chattype::Group {
1348            // Send group ID unless it is an ad hoc group that has no ID.
1349            if !chat.grpid.is_empty() {
1350                headers.push((
1351                    "Chat-Group-ID",
1352                    mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1353                ));
1354            }
1355        }
1356
1357        if chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast {
1358            headers.push((
1359                "Chat-Group-Name",
1360                mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1361            ));
1362            if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1363                headers.push((
1364                    "Chat-Group-Name-Timestamp",
1365                    mail_builder::headers::text::Text::new(ts.to_string()).into(),
1366                ));
1367            }
1368        }
1369        if chat.typ == Chattype::Group
1370            || chat.typ == Chattype::OutBroadcast
1371            || chat.typ == Chattype::InBroadcast
1372        {
1373            match command {
1374                SystemMessage::MemberRemovedFromGroup => {
1375                    let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1376                    let fingerprint_to_remove = msg.param.get(Param::Arg4).unwrap_or_default();
1377
1378                    if email_to_remove
1379                        == context
1380                            .get_config(Config::ConfiguredAddr)
1381                            .await?
1382                            .unwrap_or_default()
1383                    {
1384                        placeholdertext = Some(format!("{email_to_remove} left the group."));
1385                    } else {
1386                        placeholdertext = Some(format!("Member {email_to_remove} was removed."));
1387                    };
1388
1389                    if !email_to_remove.is_empty() {
1390                        headers.push((
1391                            "Chat-Group-Member-Removed",
1392                            mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1393                                .into(),
1394                        ));
1395                    }
1396
1397                    if !fingerprint_to_remove.is_empty() {
1398                        headers.push((
1399                            "Chat-Group-Member-Removed-Fpr",
1400                            mail_builder::headers::raw::Raw::new(fingerprint_to_remove.to_string())
1401                                .into(),
1402                        ));
1403                    }
1404                }
1405                SystemMessage::MemberAddedToGroup => {
1406                    let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1407                    let fingerprint_to_add = msg.param.get(Param::Arg4).unwrap_or_default();
1408
1409                    placeholdertext = Some(format!("Member {email_to_add} was added."));
1410
1411                    if !email_to_add.is_empty() {
1412                        headers.push((
1413                            "Chat-Group-Member-Added",
1414                            mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1415                        ));
1416                    }
1417                    if !fingerprint_to_add.is_empty() {
1418                        headers.push((
1419                            "Chat-Group-Member-Added-Fpr",
1420                            mail_builder::headers::raw::Raw::new(fingerprint_to_add.to_string())
1421                                .into(),
1422                        ));
1423                    }
1424                    if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1425                        let step = "vg-member-added";
1426                        info!(context, "Sending secure-join message {:?}.", step);
1427                        headers.push((
1428                            "Secure-Join",
1429                            mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1430                        ));
1431                    }
1432                }
1433                SystemMessage::GroupNameChanged => {
1434                    placeholdertext = Some("Chat name changed.".to_string());
1435                    let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1436                    headers.push((
1437                        "Chat-Group-Name-Changed",
1438                        mail_builder::headers::text::Text::new(old_name).into(),
1439                    ));
1440                }
1441                SystemMessage::GroupDescriptionChanged => {
1442                    placeholdertext = Some(
1443                        "[Chat description changed. To see this and other new features, please update the app]".to_string(),
1444                    );
1445                    headers.push((
1446                        "Chat-Group-Description-Changed",
1447                        mail_builder::headers::text::Text::new("").into(),
1448                    ));
1449                }
1450                SystemMessage::GroupImageChanged => {
1451                    placeholdertext = Some("Chat image changed.".to_string());
1452                    headers.push((
1453                        "Chat-Content",
1454                        mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1455                    ));
1456                    if grpimage.is_none() && is_encrypted {
1457                        headers.push((
1458                            "Chat-Group-Avatar",
1459                            mail_builder::headers::raw::Raw::new("0").into(),
1460                        ));
1461                    }
1462                }
1463                SystemMessage::Unknown => {}
1464                SystemMessage::AutocryptSetupMessage => {}
1465                SystemMessage::SecurejoinMessage => {}
1466                SystemMessage::LocationStreamingEnabled => {}
1467                SystemMessage::LocationOnly => {}
1468                SystemMessage::EphemeralTimerChanged => {}
1469                SystemMessage::ChatProtectionEnabled => {}
1470                SystemMessage::ChatProtectionDisabled => {}
1471                SystemMessage::InvalidUnencryptedMail => {}
1472                SystemMessage::SecurejoinWait => {}
1473                SystemMessage::SecurejoinWaitTimeout => {}
1474                SystemMessage::MultiDeviceSync => {}
1475                SystemMessage::WebxdcStatusUpdate => {}
1476                SystemMessage::WebxdcInfoMessage => {}
1477                SystemMessage::IrohNodeAddr => {}
1478                SystemMessage::ChatE2ee => {}
1479                SystemMessage::CallAccepted => {}
1480                SystemMessage::CallEnded => {}
1481            }
1482
1483            if command == SystemMessage::GroupDescriptionChanged
1484                || command == SystemMessage::MemberAddedToGroup
1485                || msg
1486                    .param
1487                    .get_bool(Param::AttachChatAvatarAndDescription)
1488                    .unwrap_or_default()
1489            {
1490                let description = chat::get_chat_description(context, chat.id).await?;
1491                headers.push((
1492                    "Chat-Group-Description",
1493                    mail_builder::headers::raw::Raw::new(b_encode(&description)).into(),
1494                ));
1495                if let Some(ts) = chat.param.get_i64(Param::GroupDescriptionTimestamp) {
1496                    headers.push((
1497                        "Chat-Group-Description-Timestamp",
1498                        mail_builder::headers::text::Text::new(ts.to_string()).into(),
1499                    ));
1500                }
1501            }
1502        }
1503
1504        match command {
1505            SystemMessage::LocationStreamingEnabled => {
1506                headers.push((
1507                    "Chat-Content",
1508                    mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1509                ));
1510            }
1511            SystemMessage::EphemeralTimerChanged => {
1512                headers.push((
1513                    "Chat-Content",
1514                    mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1515                ));
1516            }
1517            SystemMessage::LocationOnly
1518            | SystemMessage::MultiDeviceSync
1519            | SystemMessage::WebxdcStatusUpdate => {
1520                // This should prevent automatic replies,
1521                // such as non-delivery reports,
1522                // if the message is unencrypted.
1523                //
1524                // See <https://tools.ietf.org/html/rfc3834>
1525                headers.push((
1526                    "Auto-Submitted",
1527                    mail_builder::headers::raw::Raw::new("auto-generated").into(),
1528                ));
1529            }
1530            SystemMessage::SecurejoinMessage => {
1531                let step = msg.param.get(Param::Arg).unwrap_or_default();
1532                if !step.is_empty() {
1533                    info!(context, "Sending secure-join message {step:?}.");
1534                    headers.push((
1535                        "Secure-Join",
1536                        mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1537                    ));
1538
1539                    let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1540                    if !param2.is_empty() {
1541                        headers.push((
1542                            if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1543                                "Secure-Join-Auth"
1544                            } else {
1545                                "Secure-Join-Invitenumber"
1546                            },
1547                            mail_builder::headers::text::Text::new(param2.to_string()).into(),
1548                        ));
1549                    }
1550
1551                    let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1552                    if !fingerprint.is_empty() {
1553                        headers.push((
1554                            "Secure-Join-Fingerprint",
1555                            mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1556                        ));
1557                    }
1558                    if let Some(id) = msg.param.get(Param::Arg4) {
1559                        headers.push((
1560                            "Secure-Join-Group",
1561                            mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1562                        ));
1563                    };
1564                }
1565            }
1566            SystemMessage::ChatProtectionEnabled => {
1567                headers.push((
1568                    "Chat-Content",
1569                    mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1570                ));
1571            }
1572            SystemMessage::ChatProtectionDisabled => {
1573                headers.push((
1574                    "Chat-Content",
1575                    mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1576                ));
1577            }
1578            SystemMessage::IrohNodeAddr => {
1579                let node_addr = context
1580                    .get_or_try_init_peer_channel()
1581                    .await?
1582                    .get_node_addr()
1583                    .await?;
1584
1585                // We should not send `null` as relay URL
1586                // as this is the only way to reach the node.
1587                debug_assert!(node_addr.relay_url().is_some());
1588                headers.push((
1589                    HeaderDef::IrohNodeAddr.into(),
1590                    mail_builder::headers::text::Text::new(serde_json::to_string(&node_addr)?)
1591                        .into(),
1592                ));
1593            }
1594            SystemMessage::CallAccepted => {
1595                headers.push((
1596                    "Chat-Content",
1597                    mail_builder::headers::raw::Raw::new("call-accepted").into(),
1598                ));
1599            }
1600            SystemMessage::CallEnded => {
1601                headers.push((
1602                    "Chat-Content",
1603                    mail_builder::headers::raw::Raw::new("call-ended").into(),
1604                ));
1605            }
1606            _ => {}
1607        }
1608
1609        if let Some(grpimage) = grpimage
1610            && is_encrypted
1611        {
1612            info!(context, "setting group image '{}'", grpimage);
1613            let avatar = build_avatar_file(context, grpimage)
1614                .await
1615                .context("Cannot attach group image")?;
1616            headers.push((
1617                "Chat-Group-Avatar",
1618                mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1619            ));
1620        }
1621
1622        if msg.viewtype == Viewtype::Sticker {
1623            headers.push((
1624                "Chat-Content",
1625                mail_builder::headers::raw::Raw::new("sticker").into(),
1626            ));
1627        } else if msg.viewtype == Viewtype::Call {
1628            headers.push((
1629                "Chat-Content",
1630                mail_builder::headers::raw::Raw::new("call").into(),
1631            ));
1632            placeholdertext = Some(
1633                "[This is a 'Call'. The sender uses an experiment not supported on your version yet]".to_string(),
1634            );
1635        }
1636
1637        if let Some(offer) = msg.param.get(Param::WebrtcRoom) {
1638            headers.push((
1639                "Chat-Webrtc-Room",
1640                mail_builder::headers::raw::Raw::new(b_encode(offer)).into(),
1641            ));
1642        } else if let Some(answer) = msg.param.get(Param::WebrtcAccepted) {
1643            headers.push((
1644                "Chat-Webrtc-Accepted",
1645                mail_builder::headers::raw::Raw::new(b_encode(answer)).into(),
1646            ));
1647        }
1648        if let Some(has_video) = msg.param.get(Param::WebrtcHasVideoInitially) {
1649            headers.push((
1650                "Chat-Webrtc-Has-Video-Initially",
1651                mail_builder::headers::raw::Raw::new(b_encode(has_video)).into(),
1652            ))
1653        }
1654
1655        if msg.viewtype == Viewtype::Voice
1656            || msg.viewtype == Viewtype::Audio
1657            || msg.viewtype == Viewtype::Video
1658        {
1659            if msg.viewtype == Viewtype::Voice {
1660                headers.push((
1661                    "Chat-Voice-Message",
1662                    mail_builder::headers::raw::Raw::new("1").into(),
1663                ));
1664            }
1665            let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1666            if duration_ms > 0 {
1667                let dur = duration_ms.to_string();
1668                headers.push((
1669                    "Chat-Duration",
1670                    mail_builder::headers::raw::Raw::new(dur).into(),
1671                ));
1672            }
1673        }
1674
1675        // add text part - we even add empty text and force a MIME-multipart-message as:
1676        // - some Apps have problems with Non-text in the main part (eg. "Mail" from stock Android)
1677        // - we can add "forward hints" this way
1678        // - it looks better
1679
1680        let afwd_email = msg.param.exists(Param::Forwarded);
1681        let fwdhint = if afwd_email {
1682            Some(
1683                "---------- Forwarded message ----------\r\n\
1684                 From: Delta Chat\r\n\
1685                 \r\n"
1686                    .to_string(),
1687            )
1688        } else {
1689            None
1690        };
1691
1692        let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1693
1694        let mut quoted_text = None;
1695        if let Some(msg_quoted_text) = msg.quoted_text() {
1696            let mut some_quoted_text = String::new();
1697            for quoted_line in msg_quoted_text.split('\n') {
1698                some_quoted_text += "> ";
1699                some_quoted_text += quoted_line;
1700                some_quoted_text += "\r\n";
1701            }
1702            some_quoted_text += "\r\n";
1703            quoted_text = Some(some_quoted_text)
1704        }
1705
1706        if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1707            // Message is not encrypted but quotes encrypted message.
1708            quoted_text = Some("> ...\r\n\r\n".to_string());
1709        }
1710        if quoted_text.is_none() && final_text.starts_with('>') {
1711            // Insert empty line to avoid receiver treating user-sent quote as topquote inserted by
1712            // Delta Chat.
1713            quoted_text = Some("\r\n".to_string());
1714        }
1715
1716        let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1717
1718        let footer = if is_reaction { "" } else { &self.selfstatus };
1719
1720        let message_text = if self.pre_message_mode == PreMessageMode::Post {
1721            "".to_string()
1722        } else {
1723            format!(
1724                "{}{}{}{}{}{}",
1725                fwdhint.unwrap_or_default(),
1726                quoted_text.unwrap_or_default(),
1727                escape_message_footer_marks(final_text),
1728                if !final_text.is_empty() && !footer.is_empty() {
1729                    "\r\n\r\n"
1730                } else {
1731                    ""
1732                },
1733                if !footer.is_empty() { "-- \r\n" } else { "" },
1734                footer
1735            )
1736        };
1737
1738        let mut main_part = MimePart::new("text/plain", message_text);
1739        if is_reaction {
1740            main_part = main_part.header(
1741                "Content-Disposition",
1742                mail_builder::headers::raw::Raw::new("reaction"),
1743            );
1744        }
1745
1746        let mut parts = Vec::new();
1747
1748        if msg.has_html() {
1749            let html = if let Some(html) = msg.param.get(Param::SendHtml) {
1750                Some(html.to_string())
1751            } else if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded)
1752                && orig_msg_id != 0
1753            {
1754                // Legacy forwarded messages may not have `Param::SendHtml` set. Let's hope the
1755                // original message exists.
1756                MsgId::new(orig_msg_id.try_into()?)
1757                    .get_html(context)
1758                    .await?
1759            } else {
1760                None
1761            };
1762            if let Some(html) = html {
1763                main_part = MimePart::new(
1764                    "multipart/alternative",
1765                    vec![main_part, MimePart::new("text/html", html)],
1766                )
1767            }
1768        }
1769
1770        // add attachment part
1771        if msg.viewtype.has_file() {
1772            if let PreMessageMode::Pre { .. } = self.pre_message_mode {
1773                let Some(metadata) = PostMsgMetadata::from_msg(context, &msg).await? else {
1774                    bail!("Failed to generate metadata for pre-message")
1775                };
1776
1777                headers.push((
1778                    HeaderDef::ChatPostMessageMetadata.into(),
1779                    mail_builder::headers::raw::Raw::new(metadata.to_header_value()?).into(),
1780                ));
1781            } else {
1782                let file_part = build_body_file(context, &msg).await?;
1783                parts.push(file_part);
1784            }
1785        }
1786
1787        if let Some(msg_kml_part) = self.get_message_kml_part() {
1788            parts.push(msg_kml_part);
1789        }
1790
1791        if location::is_sending_to_chat(context, msg.chat_id).await?
1792            && let Some(part) = self.get_location_kml_part(context).await?
1793        {
1794            parts.push(part);
1795        }
1796
1797        // we do not piggyback sync-files to other self-sent-messages
1798        // to not risk files becoming too larger and being skipped by download-on-demand.
1799        if command == SystemMessage::MultiDeviceSync {
1800            let json = msg.param.get(Param::Arg).unwrap_or_default();
1801            let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1802            parts.push(context.build_sync_part(json.to_string()));
1803            self.sync_ids_to_delete = Some(ids.to_string());
1804        } else if command == SystemMessage::WebxdcStatusUpdate {
1805            let json = msg.param.get(Param::Arg).unwrap_or_default();
1806            parts.push(context.build_status_update_part(json));
1807        } else if msg.viewtype == Viewtype::Webxdc {
1808            let topic = self
1809                .webxdc_topic
1810                .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1811                .unwrap_or(create_iroh_header(context, msg.id).await?);
1812            headers.push((
1813                HeaderDef::IrohGossipTopic.get_headername(),
1814                mail_builder::headers::raw::Raw::new(topic).into(),
1815            ));
1816            if let (Some(json), _) = context
1817                .render_webxdc_status_update_object(
1818                    msg.id,
1819                    StatusUpdateSerial::MIN,
1820                    StatusUpdateSerial::MAX,
1821                    None,
1822                )
1823                .await?
1824            {
1825                parts.push(context.build_status_update_part(&json));
1826            }
1827        }
1828
1829        self.attach_selfavatar =
1830            self.attach_selfavatar && self.pre_message_mode != PreMessageMode::Post;
1831        if self.attach_selfavatar {
1832            match context.get_config(Config::Selfavatar).await? {
1833                Some(path) => match build_avatar_file(context, &path).await {
1834                    Ok(avatar) => headers.push((
1835                        "Chat-User-Avatar",
1836                        mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1837                    )),
1838                    Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1839                },
1840                None => headers.push((
1841                    "Chat-User-Avatar",
1842                    mail_builder::headers::raw::Raw::new("0").into(),
1843                )),
1844            }
1845        }
1846
1847        Ok((main_part, parts))
1848    }
1849
1850    /// Render an MDN
1851    fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1852        // RFC 6522, this also requires the `report-type` parameter which is equal
1853        // to the MIME subtype of the second body part of the multipart/report
1854        let Loaded::Mdn {
1855            rfc724_mid,
1856            additional_msg_ids,
1857        } = &self.loaded
1858        else {
1859            bail!("Attempt to render a message as MDN");
1860        };
1861
1862        // first body part: always human-readable, always REQUIRED by RFC 6522.
1863        // untranslated to no reveal sender's language.
1864        // moreover, translations in unknown languages are confusing, and clients may not display them at all
1865        let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1866
1867        let mut message = MimePart::new(
1868            "multipart/report; report-type=disposition-notification",
1869            vec![text_part],
1870        );
1871
1872        // second body part: machine-readable, always REQUIRED by RFC 6522
1873        let message_text2 = format!(
1874            "Original-Recipient: rfc822;{}\r\n\
1875             Final-Recipient: rfc822;{}\r\n\
1876             Original-Message-ID: <{}>\r\n\
1877             Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1878            self.from_addr, self.from_addr, rfc724_mid
1879        );
1880
1881        let extension_fields = if additional_msg_ids.is_empty() {
1882            "".to_string()
1883        } else {
1884            "Additional-Message-IDs: ".to_string()
1885                + &additional_msg_ids
1886                    .iter()
1887                    .map(|mid| render_rfc724_mid(mid))
1888                    .collect::<Vec<String>>()
1889                    .join(" ")
1890                + "\r\n"
1891        };
1892
1893        message.add_part(MimePart::new(
1894            "message/disposition-notification",
1895            message_text2 + &extension_fields,
1896        ));
1897
1898        Ok(message)
1899    }
1900
1901    pub fn will_be_encrypted(&self) -> bool {
1902        self.encryption_pubkeys.is_some()
1903    }
1904
1905    pub fn set_as_post_message(&mut self) {
1906        self.pre_message_mode = PreMessageMode::Post;
1907    }
1908
1909    pub fn set_as_pre_message_for(&mut self, post_message: &RenderedEmail) {
1910        self.pre_message_mode = PreMessageMode::Pre {
1911            post_msg_rfc724_mid: post_message.rfc724_mid.clone(),
1912        };
1913    }
1914}
1915
1916/// Stores the unprotected headers on the outer message, and renders it.
1917pub(crate) fn render_outer_message(
1918    unprotected_headers: Vec<(&'static str, HeaderType<'static>)>,
1919    outer_message: MimePart<'static>,
1920) -> String {
1921    let outer_message = unprotected_headers
1922        .into_iter()
1923        .fold(outer_message, |message, (header, value)| {
1924            message.header(header, value)
1925        });
1926
1927    let mut buffer = Vec::new();
1928    let cursor = Cursor::new(&mut buffer);
1929    outer_message.clone().write_part(cursor).ok();
1930    String::from_utf8_lossy(&buffer).to_string()
1931}
1932
1933/// Takes the encrypted part, wraps it in a MimePart,
1934/// and sets the appropriate Content-Type for the outer message
1935pub(crate) fn wrap_encrypted_part(encrypted: String) -> MimePart<'static> {
1936    MimePart::new(
1937        "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1938        vec![
1939            // Autocrypt part 1
1940            MimePart::new("application/pgp-encrypted", "Version: 1\r\n"),
1941            // Autocrypt part 2
1942            MimePart::new("application/octet-stream", encrypted),
1943        ],
1944    )
1945}
1946
1947fn add_headers_to_encrypted_part(
1948    message: MimePart<'static>,
1949    unprotected_headers: &[(&'static str, HeaderType<'static>)],
1950    hidden_headers: Vec<(&'static str, HeaderType<'static>)>,
1951    protected_headers: Vec<(&'static str, HeaderType<'static>)>,
1952    use_std_header_protection: bool,
1953) -> MimePart<'static> {
1954    // Store protected headers in the inner message.
1955    let message = protected_headers
1956        .into_iter()
1957        .fold(message, |message, (header, value)| {
1958            message.header(header, value)
1959        });
1960
1961    // Add hidden headers to encrypted payload.
1962    let mut message: MimePart<'static> = hidden_headers
1963        .into_iter()
1964        .fold(message, |message, (header, value)| {
1965            message.header(header, value)
1966        });
1967
1968    if use_std_header_protection {
1969        message = unprotected_headers
1970            .iter()
1971            // Structural headers shouldn't be added as "HP-Outer". They are defined in
1972            // <https://www.rfc-editor.org/rfc/rfc9787.html#structural-header-fields>.
1973            .filter(|(name, _)| {
1974                !(name.eq_ignore_ascii_case("mime-version")
1975                    || name.eq_ignore_ascii_case("content-type")
1976                    || name.eq_ignore_ascii_case("content-transfer-encoding")
1977                    || name.eq_ignore_ascii_case("content-disposition"))
1978            })
1979            .fold(message, |message, (name, value)| {
1980                message.header(format!("HP-Outer: {name}"), value.clone())
1981            });
1982    }
1983
1984    // Set the appropriate Content-Type for the inner message
1985    for (h, v) in &mut message.headers {
1986        if h == "Content-Type"
1987            && let mail_builder::headers::HeaderType::ContentType(ct) = v
1988        {
1989            let mut ct_new = ct.clone();
1990            ct_new = ct_new.attribute("protected-headers", "v1");
1991            if use_std_header_protection {
1992                ct_new = ct_new.attribute("hp", "cipher");
1993            }
1994            *ct = ct_new;
1995            break;
1996        }
1997    }
1998
1999    message
2000}
2001
2002struct HeadersByConfidentiality {
2003    /// Headers that must go into IMF header section.
2004    ///
2005    /// These are standard headers such as Date, In-Reply-To, References, which cannot be placed
2006    /// anywhere else according to the standard. Placing headers here also allows them to be fetched
2007    /// individually over IMAP without downloading the message body. This is why Chat-Version is
2008    /// placed here.
2009    unprotected_headers: Vec<(&'static str, HeaderType<'static>)>,
2010
2011    /// Headers that MUST NOT (only) go into IMF header section:
2012    /// - Large headers which may hit the header section size limit on the server, such as
2013    ///   Chat-User-Avatar with a base64-encoded image inside.
2014    /// - Headers duplicated here that servers mess up with in the IMF header section, like
2015    ///   Message-ID.
2016    /// - Nonstandard headers that should be DKIM-protected because e.g. OpenDKIM only signs
2017    ///   known headers.
2018    ///
2019    /// The header should be hidden from MTA
2020    /// by moving it either into protected part
2021    /// in case of encrypted mails
2022    /// or unprotected MIME preamble in case of unencrypted mails.
2023    hidden_headers: Vec<(&'static str, HeaderType<'static>)>,
2024
2025    /// Opportunistically protected headers.
2026    ///
2027    /// These headers are placed into encrypted part *if* the message is encrypted. Place headers
2028    /// which are not needed before decryption (e.g. Chat-Group-Name) or are not interesting if the
2029    /// message cannot be decrypted (e.g. Chat-Disposition-Notification-To) here.
2030    ///
2031    /// If the message is not encrypted, these headers are placed into IMF header section, so make
2032    /// sure that the message will be encrypted if you place any sensitive information here.
2033    protected_headers: Vec<(&'static str, HeaderType<'static>)>,
2034}
2035
2036/// Split headers based on header confidentiality policy.
2037/// See [`HeadersByConfidentiality`] for more info.
2038fn group_headers_by_confidentiality(
2039    headers: Vec<(&'static str, HeaderType<'static>)>,
2040    from_addr: &str,
2041    timestamp: i64,
2042    is_encrypted: bool,
2043    is_securejoin_message: bool,
2044) -> HeadersByConfidentiality {
2045    let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2046    let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2047    let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2048
2049    // MIME header <https://datatracker.ietf.org/doc/html/rfc2045>.
2050    unprotected_headers.push((
2051        "MIME-Version",
2052        mail_builder::headers::raw::Raw::new("1.0").into(),
2053    ));
2054
2055    for header @ (original_header_name, _header_value) in &headers {
2056        let header_name = original_header_name.to_lowercase();
2057        if header_name == "message-id" {
2058            unprotected_headers.push(header.clone());
2059            hidden_headers.push(header.clone());
2060        } else if is_hidden(&header_name) {
2061            hidden_headers.push(header.clone());
2062        } else if header_name == "from" {
2063            // Unencrypted securejoin messages should _not_ include the display name:
2064            if is_encrypted || !is_securejoin_message {
2065                protected_headers.push(header.clone());
2066            }
2067
2068            unprotected_headers.push((
2069                original_header_name,
2070                Address::new_address(None::<&'static str>, from_addr.to_string()).into(),
2071            ));
2072        } else if header_name == "to" {
2073            protected_headers.push(header.clone());
2074            if is_encrypted {
2075                unprotected_headers.push(("To", hidden_recipients().into()));
2076            } else {
2077                unprotected_headers.push(header.clone());
2078            }
2079        } else if header_name == "chat-broadcast-secret" {
2080            if is_encrypted {
2081                protected_headers.push(header.clone());
2082            }
2083        } else if is_encrypted && header_name == "date" {
2084            protected_headers.push(header.clone());
2085
2086            // Randomized date goes to unprotected header.
2087            //
2088            // We cannot just send "Thu, 01 Jan 1970 00:00:00 +0000"
2089            // or omit the header because GMX then fails with
2090            //
2091            // host mx00.emig.gmx.net[212.227.15.9] said:
2092            // 554-Transaction failed
2093            // 554-Reject due to policy restrictions.
2094            // 554 For explanation visit https://postmaster.gmx.net/en/case?...
2095            // (in reply to end of DATA command)
2096            //
2097            // and the explanation page says
2098            // "The time information deviates too much from the actual time".
2099            //
2100            // We also limit the range to 6 days (518400 seconds)
2101            // because with a larger range we got
2102            // error "500 Date header far in the past/future"
2103            // which apparently originates from Symantec Messaging Gateway
2104            // and means the message has a Date that is more
2105            // than 7 days in the past:
2106            // <https://github.com/chatmail/core/issues/7466>
2107            let timestamp_offset = rand::random_range(0..518400);
2108            let protected_timestamp = timestamp.saturating_sub(timestamp_offset);
2109            let unprotected_date =
2110                chrono::DateTime::<chrono::Utc>::from_timestamp(protected_timestamp, 0)
2111                    .unwrap()
2112                    .to_rfc2822();
2113            unprotected_headers.push((
2114                "Date",
2115                mail_builder::headers::raw::Raw::new(unprotected_date).into(),
2116            ));
2117        } else if is_encrypted {
2118            protected_headers.push(header.clone());
2119
2120            match header_name.as_str() {
2121                "subject" => {
2122                    unprotected_headers.push((
2123                        "Subject",
2124                        mail_builder::headers::raw::Raw::new("[...]").into(),
2125                    ));
2126                }
2127                "chat-version" | "autocrypt-setup-message" | "chat-is-post-message" => {
2128                    unprotected_headers.push(header.clone());
2129                }
2130                _ => {
2131                    // Other headers are removed from unprotected part.
2132                }
2133            }
2134        } else {
2135            unprotected_headers.push(header.clone())
2136        }
2137    }
2138    HeadersByConfidentiality {
2139        unprotected_headers,
2140        hidden_headers,
2141        protected_headers,
2142    }
2143}
2144
2145fn hidden_recipients() -> Address<'static> {
2146    Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
2147}
2148
2149fn should_encrypt_with_broadcast_secret(msg: &Message, chat: &Chat) -> bool {
2150    chat.typ == Chattype::OutBroadcast && must_have_only_one_recipient(msg, chat).is_none()
2151}
2152
2153fn should_hide_recipients(msg: &Message, chat: &Chat) -> bool {
2154    should_encrypt_with_broadcast_secret(msg, chat)
2155}
2156
2157fn should_encrypt_symmetrically(msg: &Message, chat: &Chat) -> bool {
2158    should_encrypt_with_broadcast_secret(msg, chat)
2159}
2160
2161/// Some messages sent into outgoing broadcast channels (member-added/member-removed)
2162/// should only go to a single recipient,
2163/// rather than all recipients.
2164/// This function returns the fingerprint of the recipient the message should be sent to.
2165fn must_have_only_one_recipient<'a>(msg: &'a Message, chat: &Chat) -> Option<Result<&'a str>> {
2166    if chat.typ != Chattype::OutBroadcast {
2167        None
2168    } else if let Some(fp) = msg.param.get(Param::Arg4) {
2169        Some(Ok(fp))
2170    } else if matches!(
2171        msg.param.get_cmd(),
2172        SystemMessage::MemberRemovedFromGroup | SystemMessage::MemberAddedToGroup
2173    ) {
2174        Some(Err(format_err!("Missing removed/added member")))
2175    } else {
2176        None
2177    }
2178}
2179
2180async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
2181    let file_name = msg.get_filename().context("msg has no file")?;
2182    let blob = msg
2183        .param
2184        .get_file_blob(context)?
2185        .context("msg has no file")?;
2186    let mimetype = msg
2187        .param
2188        .get(Param::MimeType)
2189        .unwrap_or("application/octet-stream")
2190        .to_string();
2191    let body = fs::read(blob.to_abs_path()).await?;
2192
2193    // create mime part, for Content-Disposition, see RFC 2183.
2194    // `Content-Disposition: attachment` seems not to make a difference to `Content-Disposition: inline`
2195    // at least on tested Thunderbird and Gma'l in 2017.
2196    // But I've heard about problems with inline and outl'k, so we just use the attachment-type until we
2197    // run into other problems ...
2198    let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
2199
2200    Ok(mail)
2201}
2202
2203async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
2204    let blob = match path.starts_with("$BLOBDIR/") {
2205        true => BlobObject::from_name(context, path)?,
2206        false => BlobObject::from_path(context, path.as_ref())?,
2207    };
2208    let body = fs::read(blob.to_abs_path()).await?;
2209    let encoded_body = base64::engine::general_purpose::STANDARD
2210        .encode(&body)
2211        .chars()
2212        .enumerate()
2213        .fold(String::new(), |mut res, (i, c)| {
2214            if i % 78 == 77 {
2215                res.push(' ')
2216            }
2217            res.push(c);
2218            res
2219        });
2220    Ok(encoded_body)
2221}
2222
2223fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
2224    let addr_lc = addr.to_lowercase();
2225    recipients
2226        .iter()
2227        .any(|(_, cur)| cur.to_lowercase() == addr_lc)
2228}
2229
2230fn render_rfc724_mid(rfc724_mid: &str) -> String {
2231    let rfc724_mid = rfc724_mid.trim().to_string();
2232
2233    if rfc724_mid.chars().next().unwrap_or_default() == '<' {
2234        rfc724_mid
2235    } else {
2236        format!("<{rfc724_mid}>")
2237    }
2238}
2239
2240/// Encodes UTF-8 string as a single B-encoded-word.
2241///
2242/// We manually encode some headers because as of
2243/// version 0.4.4 mail-builder crate does not encode
2244/// newlines correctly if they appear in a text header.
2245fn b_encode(value: &str) -> String {
2246    format!(
2247        "=?utf-8?B?{}?=",
2248        base64::engine::general_purpose::STANDARD.encode(value)
2249    )
2250}
2251
2252pub(crate) async fn render_symm_encrypted_securejoin_message(
2253    context: &Context,
2254    step: &str,
2255    rfc724_mid: &str,
2256    attach_self_pubkey: bool,
2257    auth: &str,
2258    shared_secret: &str,
2259) -> Result<String> {
2260    info!(context, "Sending secure-join message {step:?}.");
2261
2262    let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
2263
2264    let from_addr = context.get_primary_self_addr().await?;
2265    let from = new_address_with_name("", from_addr.to_string());
2266    headers.push(("From", from.into()));
2267
2268    let to: Vec<Address<'static>> = vec![hidden_recipients()];
2269    headers.push((
2270        "To",
2271        mail_builder::headers::address::Address::new_list(to.clone()).into(),
2272    ));
2273
2274    headers.push((
2275        "Subject",
2276        mail_builder::headers::text::Text::new("Secure-Join".to_string()).into(),
2277    ));
2278
2279    let timestamp = create_smeared_timestamp(context);
2280    let date = chrono::DateTime::<chrono::Utc>::from_timestamp(timestamp, 0)
2281        .unwrap()
2282        .to_rfc2822();
2283    headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
2284
2285    headers.push((
2286        "Message-ID",
2287        mail_builder::headers::message_id::MessageId::new(rfc724_mid.to_string()).into(),
2288    ));
2289
2290    // Automatic Response headers <https://www.rfc-editor.org/rfc/rfc3834>
2291    if context.get_config_bool(Config::Bot).await? {
2292        headers.push((
2293            "Auto-Submitted",
2294            mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
2295        ));
2296    }
2297
2298    let encrypt_helper = EncryptHelper::new(context).await?;
2299
2300    if attach_self_pubkey {
2301        let aheader = encrypt_helper.get_aheader().to_string();
2302        headers.push((
2303            "Autocrypt",
2304            mail_builder::headers::raw::Raw::new(aheader).into(),
2305        ));
2306    }
2307
2308    headers.push((
2309        "Secure-Join",
2310        mail_builder::headers::raw::Raw::new(step.to_string()).into(),
2311    ));
2312
2313    headers.push((
2314        "Secure-Join-Auth",
2315        mail_builder::headers::text::Text::new(auth.to_string()).into(),
2316    ));
2317
2318    let message: MimePart<'static> = MimePart::new("text/plain", "Secure-Join");
2319
2320    let is_encrypted = true;
2321    let is_securejoin_message = true;
2322    let HeadersByConfidentiality {
2323        unprotected_headers,
2324        hidden_headers,
2325        protected_headers,
2326    } = group_headers_by_confidentiality(
2327        headers,
2328        &from_addr,
2329        timestamp,
2330        is_encrypted,
2331        is_securejoin_message,
2332    );
2333
2334    let outer_message = {
2335        let use_std_header_protection = true;
2336        let message = add_headers_to_encrypted_part(
2337            message,
2338            &unprotected_headers,
2339            hidden_headers,
2340            protected_headers,
2341            use_std_header_protection,
2342        );
2343
2344        // Disable compression for SecureJoin to ensure
2345        // there are no compression side channels
2346        // leaking information about the tokens.
2347        let compress = false;
2348        // Only sign the message if we attach the pubkey.
2349        let sign = attach_self_pubkey;
2350        let encrypted = encrypt_helper
2351            .encrypt_symmetrically(context, shared_secret, message, compress, sign)
2352            .await?;
2353
2354        wrap_encrypted_part(encrypted)
2355    };
2356
2357    let message = render_outer_message(unprotected_headers, outer_message);
2358
2359    Ok(message)
2360}
2361
2362#[cfg(test)]
2363mod mimefactory_tests;