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