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    /// Largest timestamp of the location sent in `location.kml` in this message.
146    last_added_location_timestamp: Option<i64>,
147
148    /// If the created mime-structure contains sync-items,
149    /// the IDs of these items are listed here.
150    /// The IDs are returned via `RenderedEmail`
151    /// and must be deleted if the message is actually queued for sending.
152    sync_ids_to_delete: Option<String>,
153
154    /// True if the avatar should be attached.
155    pub attach_selfavatar: bool,
156
157    /// This field is used to sustain the topic id of webxdcs needed for peer channels.
158    webxdc_topic: Option<TopicId>,
159
160    /// Pre-message / post-message / atomic message.
161    pre_message_mode: PreMessageMode,
162}
163
164/// Result of rendering a message, ready to be submitted to a send job.
165#[derive(Debug, Clone)]
166pub struct RenderedEmail {
167    pub message: String,
168    pub is_encrypted: bool,
169
170    /// Largest timestamp of the location sent in `location.kml` in this message.
171    pub last_added_location_timestamp: Option<i64>,
172
173    /// A comma-separated string of sync-IDs that are used by the rendered email and must be deleted
174    /// from `multi_device_sync` once the message is actually queued for sending.
175    pub sync_ids_to_delete: Option<String>,
176
177    /// Message ID (Message in the sense of Email)
178    pub rfc724_mid: String,
179
180    /// Message subject.
181    pub subject: String,
182}
183
184fn new_address_with_name(name: &str, address: String) -> Address<'static> {
185    Address::new_address(
186        if name == address || name.is_empty() {
187            None
188        } else {
189            Some(name.to_string())
190        },
191        address,
192    )
193}
194
195impl MimeFactory {
196    /// Returns `MimeFactory` for rendering `msg`.
197    #[expect(clippy::arithmetic_side_effects)]
198    pub async fn from_msg(context: &Context, msg: Message) -> Result<MimeFactory> {
199        let now = time();
200        let chat = Chat::load_from_db(context, msg.chat_id).await?;
201        let attach_profile_data = Self::should_attach_profile_data(&msg);
202        let undisclosed_recipients = should_hide_recipients(&msg, &chat);
203
204        let from_addr = context.get_primary_self_addr().await?;
205        let config_displayname = context
206            .get_config(Config::Displayname)
207            .await?
208            .unwrap_or_default();
209        let (from_displayname, sender_displayname) =
210            if let Some(override_name) = msg.param.get(Param::OverrideSenderDisplayname) {
211                (override_name.to_string(), Some(config_displayname))
212            } else {
213                let name = match attach_profile_data {
214                    true => config_displayname,
215                    false => "".to_string(),
216                };
217                (name, None)
218            };
219
220        let mut recipients = Vec::new();
221        let mut to = Vec::new();
222        let mut past_members = Vec::new();
223        let mut member_fingerprints = Vec::new();
224        let mut member_timestamps = Vec::new();
225        let mut recipient_ids = HashSet::new();
226        let req_mdn = !chat.is_self_talk()
227            && !msg.is_system_message()
228            && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
229            && context.should_request_mdns().await?;
230
231        let encryption_pubkeys;
232
233        let self_fingerprint = self_fingerprint(context).await?;
234
235        if chat.is_self_talk() {
236            to.push((from_displayname.to_string(), from_addr.to_string()));
237
238            encryption_pubkeys = Some(Vec::new());
239        } else if chat.is_mailing_list() {
240            let list_post = chat
241                .param
242                .get(Param::ListPost)
243                .context("Can't write to mailinglist without ListPost param")?;
244            to.push(("".to_string(), list_post.to_string()));
245            recipients.push(list_post.to_string());
246
247            // Do not encrypt messages to mailing lists.
248            encryption_pubkeys = None;
249        } else if let Some(fp) = must_have_only_one_recipient(&msg, &chat) {
250            let fp = fp?;
251            // In a broadcast channel, only send member-added/removed messages
252            // to the affected member
253            let (authname, addr) = context
254                .sql
255                .query_row(
256                    "SELECT authname, addr FROM contacts WHERE fingerprint=?",
257                    (fp,),
258                    |row| {
259                        let authname: String = row.get(0)?;
260                        let addr: String = row.get(1)?;
261                        Ok((authname, addr))
262                    },
263                )
264                .await?;
265
266            let public_key_bytes: Vec<_> = context
267                .sql
268                .query_get_value(
269                    "SELECT public_key FROM public_keys WHERE fingerprint=?",
270                    (fp,),
271                )
272                .await?
273                .context("Can't send member addition/removal: missing key")?;
274
275            let public_key = SignedPublicKey::from_slice(&public_key_bytes)?;
276
277            let relays =
278                addresses_from_public_key(&public_key).unwrap_or_else(|| vec![addr.clone()]);
279            recipients.extend(relays);
280            to.push((authname, addr.clone()));
281
282            encryption_pubkeys = Some(vec![(addr, public_key)]);
283        } else {
284            let email_to_remove = if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
285                msg.param.get(Param::Arg)
286            } else {
287                None
288            };
289
290            let is_encrypted = if msg
291                .param
292                .get_bool(Param::ForcePlaintext)
293                .unwrap_or_default()
294            {
295                false
296            } else {
297                msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
298                    || chat.is_encrypted(context).await?
299            };
300
301            let mut keys = Vec::new();
302            let mut missing_key_addresses = BTreeSet::new();
303            context
304                .sql
305                // Sort recipients by `add_timestamp DESC` so that if the group is large and there
306                // are multiple SMTP messages, a newly added member receives the member addition
307                // message earlier and has gossiped keys of other members (otherwise the new member
308                // may receive messages from other members earlier and fail to verify them).
309                .query_map(
310                    "SELECT
311                     c.authname,
312                     c.addr,
313                     c.fingerprint,
314                     c.id,
315                     cc.add_timestamp,
316                     cc.remove_timestamp,
317                     k.public_key
318                     FROM chats_contacts cc
319                     LEFT JOIN contacts c ON cc.contact_id=c.id
320                     LEFT JOIN public_keys k ON k.fingerprint=c.fingerprint
321                     WHERE cc.chat_id=?
322                     AND (cc.contact_id>9 OR (cc.contact_id=1 AND ?))
323                     ORDER BY cc.add_timestamp DESC",
324                    (msg.chat_id, chat.typ == Chattype::Group),
325                    |row| {
326                        let authname: String = row.get(0)?;
327                        let addr: String = row.get(1)?;
328                        let fingerprint: String = row.get(2)?;
329                        let id: ContactId = row.get(3)?;
330                        let add_timestamp: i64 = row.get(4)?;
331                        let remove_timestamp: i64 = row.get(5)?;
332                        let public_key_bytes_opt: Option<Vec<u8>> = row.get(6)?;
333                        Ok((authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt))
334                    },
335                    |rows| {
336                        let mut past_member_timestamps = Vec::new();
337                        let mut past_member_fingerprints = Vec::new();
338
339                        for row in rows {
340                            let (authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt) = row?;
341
342                            let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
343                                Some(SignedPublicKey::from_slice(public_key_bytes)?)
344                            } else {
345                                None
346                            };
347
348                            let addr = if id == ContactId::SELF {
349                                from_addr.to_string()
350                            } else {
351                                addr
352                            };
353                            let name = match attach_profile_data {
354                                true => authname,
355                                false => "".to_string(),
356                            };
357                            if add_timestamp >= remove_timestamp {
358                                let relays = if let Some(public_key) = public_key_opt {
359                                    let addrs = addresses_from_public_key(&public_key);
360                                    keys.push((addr.clone(), public_key));
361                                    addrs
362                                } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
363                                    missing_key_addresses.insert(addr.clone());
364                                    if is_encrypted {
365                                        warn!(context, "Missing key for {addr}");
366                                    }
367                                    None
368                                } else {
369                                    None
370                                }.unwrap_or_else(|| vec![addr.clone()]);
371
372                                if !recipients_contain_addr(&to, &addr) {
373                                    if id != ContactId::SELF {
374                                        recipients.extend(relays);
375                                    }
376                                    if !undisclosed_recipients {
377                                        to.push((name, addr.clone()));
378
379                                        if is_encrypted {
380                                            if !fingerprint.is_empty() {
381                                                member_fingerprints.push(fingerprint);
382                                            } else if id == ContactId::SELF {
383                                                member_fingerprints.push(self_fingerprint.to_string());
384                                            } else {
385                                                ensure_and_debug_assert!(member_fingerprints.is_empty(), "If some member is a key-contact, all other members should be key-contacts too");
386                                            }
387                                        }
388                                        member_timestamps.push(add_timestamp);
389                                    }
390                                }
391                                recipient_ids.insert(id);
392                            } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
393                                // Row is a tombstone,
394                                // member is not actually part of the group.
395                                if !recipients_contain_addr(&past_members, &addr) {
396                                    if let Some(email_to_remove) = email_to_remove
397                                        && email_to_remove == addr {
398                                            let relays = if let Some(public_key) = public_key_opt {
399                                                let addrs = addresses_from_public_key(&public_key);
400                                                keys.push((addr.clone(), public_key));
401                                                addrs
402                                            } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat)  {
403                                                missing_key_addresses.insert(addr.clone());
404                                                if is_encrypted {
405                                                    warn!(context, "Missing key for {addr}");
406                                                }
407                                                None
408                                            } else {
409                                                None
410                                            }.unwrap_or_else(|| vec![addr.clone()]);
411
412                                            // This is a "member removed" message,
413                                            // we need to notify removed member
414                                            // that it was removed.
415                                            if id != ContactId::SELF {
416                                                recipients.extend(relays);
417                                            }
418                                        }
419                                    if !undisclosed_recipients {
420                                        past_members.push((name, addr.clone()));
421                                        past_member_timestamps.push(remove_timestamp);
422
423                                        if is_encrypted {
424                                            if !fingerprint.is_empty() {
425                                                past_member_fingerprints.push(fingerprint);
426                                            } else if id == ContactId::SELF {
427                                                // It's fine to have self in past members
428                                                // if we are leaving the group.
429                                                past_member_fingerprints.push(self_fingerprint.to_string());
430                                            } else {
431                                                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");
432                                            }
433                                        }
434                                    }
435                                }
436                            }
437                        }
438
439                        ensure_and_debug_assert!(
440                            member_timestamps.len() >= to.len(),
441                            "member_timestamps.len() ({}) < to.len() ({})",
442                            member_timestamps.len(), to.len());
443                        ensure_and_debug_assert!(
444                            member_fingerprints.is_empty() || member_fingerprints.len() >= to.len(),
445                            "member_fingerprints.len() ({}) < to.len() ({})",
446                            member_fingerprints.len(), to.len());
447
448                        if to.len() > 1
449                            && let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
450                                to.remove(position);
451                                member_timestamps.remove(position);
452                                if is_encrypted {
453                                    member_fingerprints.remove(position);
454                                }
455                            }
456
457                        member_timestamps.extend(past_member_timestamps);
458                        if is_encrypted {
459                            member_fingerprints.extend(past_member_fingerprints);
460                        }
461                        Ok(())
462                    },
463                )
464                .await?;
465            let recipient_ids: Vec<_> = recipient_ids
466                .into_iter()
467                .filter(|id| *id != ContactId::SELF)
468                .collect();
469            if !matches!(
470                msg.param.get_cmd(),
471                SystemMessage::MemberRemovedFromGroup | SystemMessage::SecurejoinMessage
472            ) && !matches!(chat.typ, Chattype::OutBroadcast | Chattype::InBroadcast)
473            {
474                let origin = match recipient_ids.len() {
475                    1 => Origin::OutgoingTo,
476                    // Use the same origin as ChatId::accept_ex() does for groups.
477                    _ => Origin::IncomingTo,
478                };
479                info!(
480                    context,
481                    "Scale up origin of {} recipients to {origin:?}.", chat.id
482                );
483                ContactId::scaleup_origin(context, &recipient_ids, origin).await?;
484            }
485
486            encryption_pubkeys = if !is_encrypted {
487                None
488            } else if should_encrypt_symmetrically(&msg, &chat) {
489                Some(Vec::new())
490            } else {
491                if keys.is_empty() && !recipients.is_empty() {
492                    bail!("No recipient keys are available, cannot encrypt to {recipients:?}.");
493                }
494
495                // Remove recipients for which the key is missing.
496                if !missing_key_addresses.is_empty() {
497                    recipients.retain(|addr| !missing_key_addresses.contains(addr));
498                }
499
500                Some(keys)
501            };
502        }
503
504        let (in_reply_to, references) = context
505            .sql
506            .query_row(
507                "SELECT mime_in_reply_to, IFNULL(mime_references, '')
508                 FROM msgs WHERE id=?",
509                (msg.id,),
510                |row| {
511                    let in_reply_to: String = row.get(0)?;
512                    let references: String = row.get(1)?;
513
514                    Ok((in_reply_to, references))
515                },
516            )
517            .await?;
518        let references: Vec<String> = references
519            .trim()
520            .split_ascii_whitespace()
521            .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
522            .collect();
523        let selfstatus = match attach_profile_data {
524            true => context
525                .get_config(Config::Selfstatus)
526                .await?
527                .unwrap_or_default(),
528            false => "".to_string(),
529        };
530        // We don't display avatars for address-contacts, so sending avatars w/o encryption is not
531        // useful and causes e.g. Outlook to reject a message with a big header, see
532        // https://support.delta.chat/t/invalid-mime-content-single-text-value-size-32822-exceeded-allowed-maximum-32768-for-the-chat-user-avatar-header/4067.
533        let attach_selfavatar =
534            Self::should_attach_selfavatar(context, &msg).await && encryption_pubkeys.is_some();
535
536        ensure_and_debug_assert!(
537            member_timestamps.is_empty()
538                || to.len() + past_members.len() == member_timestamps.len(),
539            "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
540            to.len(),
541            past_members.len(),
542            member_timestamps.len(),
543        );
544        let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
545        let factory = MimeFactory {
546            from_addr,
547            from_displayname,
548            sender_displayname,
549            selfstatus,
550            recipients,
551            encryption_pubkeys,
552            to,
553            past_members,
554            member_fingerprints,
555            member_timestamps,
556            timestamp: msg.timestamp_sort,
557            loaded: Loaded::Message { msg, chat },
558            in_reply_to,
559            references,
560            req_mdn,
561            last_added_location_timestamp: None,
562            sync_ids_to_delete: None,
563            attach_selfavatar,
564            webxdc_topic,
565            pre_message_mode: PreMessageMode::None,
566        };
567        Ok(factory)
568    }
569
570    pub async fn from_mdn(
571        context: &Context,
572        from_id: ContactId,
573        rfc724_mid: String,
574        additional_msg_ids: Vec<String>,
575    ) -> Result<MimeFactory> {
576        let contact = Contact::get_by_id(context, from_id).await?;
577        let from_addr = context.get_primary_self_addr().await?;
578        let timestamp = time();
579
580        let addr = contact.get_addr().to_string();
581        let encryption_pubkeys = if from_id == ContactId::SELF {
582            Some(Vec::new())
583        } else if contact.is_key_contact() {
584            if let Some(key) = contact.public_key(context).await? {
585                Some(vec![(addr.clone(), key)])
586            } else {
587                Some(Vec::new())
588            }
589        } else {
590            None
591        };
592
593        let res = MimeFactory {
594            from_addr,
595            from_displayname: "".to_string(),
596            sender_displayname: None,
597            selfstatus: "".to_string(),
598            recipients: vec![addr],
599            encryption_pubkeys,
600            to: vec![("".to_string(), contact.get_addr().to_string())],
601            past_members: vec![],
602            member_fingerprints: vec![],
603            member_timestamps: vec![],
604            timestamp,
605            loaded: Loaded::Mdn {
606                rfc724_mid,
607                additional_msg_ids,
608            },
609            in_reply_to: String::default(),
610            references: Vec::new(),
611            req_mdn: false,
612            last_added_location_timestamp: None,
613            sync_ids_to_delete: None,
614            attach_selfavatar: false,
615            webxdc_topic: None,
616            pre_message_mode: PreMessageMode::None,
617        };
618
619        Ok(res)
620    }
621
622    fn should_skip_autocrypt(&self) -> bool {
623        match &self.loaded {
624            Loaded::Message { .. } => false,
625            Loaded::Mdn { .. } => true,
626        }
627    }
628
629    fn should_attach_profile_data(msg: &Message) -> bool {
630        msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
631            let step = msg.param.get(Param::Arg).unwrap_or_default();
632            // Don't attach profile data at the earlier SecureJoin steps:
633            // - The corresponding messages, i.e. "v{c,g}-request" and "v{c,g}-auth-required" are
634            //   deleted right after processing, so other devices won't see the avatar etc.
635            // - It's also good for privacy because the contact isn't yet verified and these
636            //   messages are auto-sent unlike usual unencrypted messages.
637            step == "vg-request-with-auth"
638                || step == "vc-request-with-auth"
639                // Note that for "vg-member-added"
640                // get_cmd() returns `MemberAddedToGroup` rather than `SecurejoinMessage`,
641                // so, it wouldn't actually be necessary to have them in the list here.
642                // Still, they are here for completeness.
643                || step == "vg-member-added"
644                || step == "vc-contact-confirm"
645        }
646    }
647
648    async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
649        Self::should_attach_profile_data(msg)
650            && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
651                Ok(should) => should,
652                Err(err) => {
653                    warn!(
654                        context,
655                        "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
656                    );
657                    false
658                }
659            }
660    }
661
662    fn grpimage(&self) -> Option<String> {
663        match &self.loaded {
664            Loaded::Message { chat, msg } => {
665                let cmd = msg.param.get_cmd();
666
667                match cmd {
668                    SystemMessage::MemberAddedToGroup => {
669                        return chat.param.get(Param::ProfileImage).map(Into::into);
670                    }
671                    SystemMessage::GroupImageChanged => {
672                        return msg.param.get(Param::Arg).map(Into::into);
673                    }
674                    _ => {}
675                }
676
677                if msg
678                    .param
679                    .get_bool(Param::AttachChatAvatarAndDescription)
680                    .unwrap_or_default()
681                {
682                    return chat.param.get(Param::ProfileImage).map(Into::into);
683                }
684
685                None
686            }
687            Loaded::Mdn { .. } => None,
688        }
689    }
690
691    async fn subject_str(&self, context: &Context) -> Result<String> {
692        let subject = match &self.loaded {
693            Loaded::Message { chat, msg } => {
694                let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
695
696                if !msg.subject.is_empty() {
697                    return Ok(msg.subject.clone());
698                }
699
700                if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
701                    && quoted_msg_subject.is_none_or_empty()
702                {
703                    let re = if self.in_reply_to.is_empty() {
704                        ""
705                    } else {
706                        "Re: "
707                    };
708                    return Ok(format!("{}{}", re, chat.name));
709                }
710
711                let parent_subject = if quoted_msg_subject.is_none_or_empty() {
712                    chat.param.get(Param::LastSubject)
713                } else {
714                    quoted_msg_subject.as_deref()
715                };
716                if let Some(last_subject) = parent_subject {
717                    return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
718                }
719
720                let self_name = match Self::should_attach_profile_data(msg) {
721                    true => context.get_config(Config::Displayname).await?,
722                    false => None,
723                };
724                let self_name = &match self_name {
725                    Some(name) => name,
726                    None => context.get_config(Config::Addr).await?.unwrap_or_default(),
727                };
728                stock_str::subject_for_new_contact(context, self_name)
729            }
730            Loaded::Mdn { .. } => "Receipt Notification".to_string(), // untranslated to no reveal sender's language
731        };
732
733        Ok(subject)
734    }
735
736    pub fn recipients(&self) -> Vec<String> {
737        self.recipients.clone()
738    }
739
740    /// Consumes a `MimeFactory` and renders it into a message which is then stored in
741    /// `smtp`-table to be used by the SMTP loop
742    #[expect(clippy::arithmetic_side_effects)]
743    pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
744        let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
745
746        let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
747
748        let mut to: Vec<Address<'static>> = Vec::new();
749        for (name, addr) in &self.to {
750            to.push(Address::new_address(
751                if name.is_empty() {
752                    None
753                } else {
754                    Some(name.to_string())
755                },
756                addr.clone(),
757            ));
758        }
759
760        let mut past_members: Vec<Address<'static>> = Vec::new(); // Contents of `Chat-Group-Past-Members` header.
761        for (name, addr) in &self.past_members {
762            past_members.push(Address::new_address(
763                if name.is_empty() {
764                    None
765                } else {
766                    Some(name.to_string())
767                },
768                addr.clone(),
769            ));
770        }
771
772        ensure_and_debug_assert!(
773            self.member_timestamps.is_empty()
774                || to.len() + past_members.len() == self.member_timestamps.len(),
775            "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
776            to.len(),
777            past_members.len(),
778            self.member_timestamps.len(),
779        );
780        if to.is_empty() {
781            to.push(hidden_recipients());
782        }
783
784        // Start with Internet Message Format headers in the order of the standard example
785        // <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.1.1>.
786        headers.push(("From", from.into()));
787
788        if let Some(sender_displayname) = &self.sender_displayname {
789            let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
790            headers.push(("Sender", sender.into()));
791        }
792        headers.push((
793            "To",
794            mail_builder::headers::address::Address::new_list(to.clone()).into(),
795        ));
796        if !past_members.is_empty() {
797            headers.push((
798                "Chat-Group-Past-Members",
799                mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
800            ));
801        }
802
803        if let Loaded::Message { chat, .. } = &self.loaded
804            && chat.typ == Chattype::Group
805        {
806            if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await? {
807                headers.push((
808                    "Chat-Group-Member-Timestamps",
809                    mail_builder::headers::raw::Raw::new(
810                        self.member_timestamps
811                            .iter()
812                            .map(|ts| ts.to_string())
813                            .collect::<Vec<String>>()
814                            .join(" "),
815                    )
816                    .into(),
817                ));
818            }
819
820            if !self.member_fingerprints.is_empty() {
821                headers.push((
822                    "Chat-Group-Member-Fpr",
823                    mail_builder::headers::raw::Raw::new(
824                        self.member_fingerprints
825                            .iter()
826                            .map(|fp| fp.to_string())
827                            .collect::<Vec<String>>()
828                            .join(" "),
829                    )
830                    .into(),
831                ));
832            }
833        }
834
835        let subject_str = self.subject_str(context).await?;
836        headers.push((
837            "Subject",
838            mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
839        ));
840
841        let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
842            .unwrap()
843            .to_rfc2822();
844        headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
845
846        let rfc724_mid = match &self.loaded {
847            Loaded::Message { msg, .. } => match &self.pre_message_mode {
848                PreMessageMode::Pre { .. } => {
849                    if msg.pre_rfc724_mid.is_empty() {
850                        create_outgoing_rfc724_mid()
851                    } else {
852                        msg.pre_rfc724_mid.clone()
853                    }
854                }
855                _ => msg.rfc724_mid.clone(),
856            },
857            Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
858        };
859        headers.push((
860            "Message-ID",
861            mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
862        ));
863
864        // Reply headers as in <https://datatracker.ietf.org/doc/html/rfc5322#appendix-A.2>.
865        if !self.in_reply_to.is_empty() {
866            headers.push((
867                "In-Reply-To",
868                mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
869            ));
870        }
871        if !self.references.is_empty() {
872            headers.push((
873                "References",
874                mail_builder::headers::message_id::MessageId::<'static>::new_list(
875                    self.references.iter().map(|s| s.to_string()),
876                )
877                .into(),
878            ));
879        }
880
881        // Automatic Response headers <https://www.rfc-editor.org/rfc/rfc3834>
882        if let Loaded::Mdn { .. } = self.loaded {
883            headers.push((
884                "Auto-Submitted",
885                mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
886            ));
887        } else if context.get_config_bool(Config::Bot).await? {
888            headers.push((
889                "Auto-Submitted",
890                mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
891            ));
892        }
893
894        if let Loaded::Message { msg, chat } = &self.loaded
895            && (chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast)
896        {
897            headers.push((
898                "Chat-List-ID",
899                mail_builder::headers::text::Text::new(format!("{} <{}>", chat.name, chat.grpid))
900                    .into(),
901            ));
902
903            if msg.param.get_cmd() == SystemMessage::MemberAddedToGroup
904                && let Some(secret) = msg.param.get(PARAM_BROADCAST_SECRET)
905            {
906                headers.push((
907                    "Chat-Broadcast-Secret",
908                    mail_builder::headers::text::Text::new(secret.to_string()).into(),
909                ));
910            }
911        }
912
913        if let Loaded::Message { msg, .. } = &self.loaded {
914            if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
915                headers.push((
916                    "Chat-Edit",
917                    mail_builder::headers::message_id::MessageId::new(
918                        original_rfc724_mid.to_string(),
919                    )
920                    .into(),
921                ));
922            } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
923                headers.push((
924                    "Chat-Delete",
925                    mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
926                        .into(),
927                ));
928            }
929        }
930
931        // Non-standard headers.
932        headers.push((
933            "Chat-Version",
934            mail_builder::headers::raw::Raw::new("1.0").into(),
935        ));
936
937        if self.req_mdn {
938            // we use "Chat-Disposition-Notification-To"
939            // because replies to "Disposition-Notification-To" are weird in many cases
940            // eg. are just freetext and/or do not follow any standard.
941            headers.push((
942                "Chat-Disposition-Notification-To",
943                mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
944            ));
945        }
946
947        let grpimage = self.grpimage();
948        let skip_autocrypt = self.should_skip_autocrypt();
949        let encrypt_helper = EncryptHelper::new(context).await?;
950
951        if !skip_autocrypt {
952            // unless determined otherwise we add the Autocrypt header
953            let aheader = encrypt_helper.get_aheader().to_string();
954            headers.push((
955                "Autocrypt",
956                mail_builder::headers::raw::Raw::new(aheader).into(),
957            ));
958        }
959
960        if self.pre_message_mode == PreMessageMode::Post {
961            headers.push((
962                "Chat-Is-Post-Message",
963                mail_builder::headers::raw::Raw::new("1").into(),
964            ));
965        } else if let PreMessageMode::Pre {
966            post_msg_rfc724_mid,
967        } = &self.pre_message_mode
968        {
969            headers.push((
970                "Chat-Post-Message-ID",
971                mail_builder::headers::message_id::MessageId::new(post_msg_rfc724_mid.clone())
972                    .into(),
973            ));
974        }
975
976        let is_encrypted = self.will_be_encrypted();
977
978        // Add ephemeral timer for non-MDN messages.
979        // For MDNs it does not matter because they are not visible
980        // and ignored by the receiver.
981        if let Loaded::Message { msg, .. } = &self.loaded {
982            let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
983            if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
984                headers.push((
985                    "Ephemeral-Timer",
986                    mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
987                ));
988            }
989        }
990
991        let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
992            msg.param.get_cmd() == SystemMessage::SecurejoinMessage
993        } else {
994            false
995        };
996
997        let message: MimePart<'static> = match &self.loaded {
998            Loaded::Message { msg, .. } => {
999                let msg = msg.clone();
1000                let (main_part, mut parts) = self
1001                    .render_message(context, &mut headers, &grpimage, is_encrypted)
1002                    .await?;
1003                if parts.is_empty() {
1004                    // Single part, render as regular message.
1005                    main_part
1006                } else {
1007                    parts.insert(0, main_part);
1008
1009                    // Multiple parts, render as multipart.
1010                    if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
1011                        MimePart::new("multipart/report; report-type=multi-device-sync", parts)
1012                    } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
1013                        MimePart::new("multipart/report; report-type=status-update", parts)
1014                    } else {
1015                        MimePart::new("multipart/mixed", parts)
1016                    }
1017                }
1018            }
1019            Loaded::Mdn { .. } => self.render_mdn()?,
1020        };
1021
1022        let HeadersByConfidentiality {
1023            mut unprotected_headers,
1024            hidden_headers,
1025            protected_headers,
1026        } = group_headers_by_confidentiality(
1027            headers,
1028            &self.from_addr,
1029            self.timestamp,
1030            is_encrypted,
1031            is_securejoin_message,
1032        );
1033
1034        let outer_message = if let Some(encryption_pubkeys) = self.encryption_pubkeys {
1035            let mut message = add_headers_to_encrypted_part(
1036                message,
1037                &unprotected_headers,
1038                hidden_headers,
1039                protected_headers,
1040            );
1041
1042            // Add gossip headers in chats with multiple recipients
1043            let multiple_recipients =
1044                encryption_pubkeys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1045
1046            let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1047            let now = time();
1048
1049            match &self.loaded {
1050                Loaded::Message { chat, msg } => {
1051                    if !should_hide_recipients(msg, chat) {
1052                        for (addr, key) in &encryption_pubkeys {
1053                            let fingerprint = key.dc_fingerprint().hex();
1054                            let cmd = msg.param.get_cmd();
1055                            if self.pre_message_mode == PreMessageMode::Post {
1056                                continue;
1057                            }
1058
1059                            let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1060                                || cmd == SystemMessage::SecurejoinMessage
1061                                || multiple_recipients && {
1062                                    let gossiped_timestamp: Option<i64> = context
1063                                        .sql
1064                                        .query_get_value(
1065                                            "SELECT timestamp
1066                                         FROM gossip_timestamp
1067                                         WHERE chat_id=? AND fingerprint=?",
1068                                            (chat.id, &fingerprint),
1069                                        )
1070                                        .await?;
1071
1072                                    // `gossip_period == 0` is a special case for testing,
1073                                    // enabling gossip in every message.
1074                                    //
1075                                    // If current time is in the past compared to
1076                                    // `gossiped_timestamp`, we also gossip because
1077                                    // either the `gossiped_timestamp` or clock is wrong.
1078                                    gossip_period == 0
1079                                        || gossiped_timestamp
1080                                            .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1081                                };
1082
1083                            let verifier_id: Option<u32> = context
1084                                .sql
1085                                .query_get_value(
1086                                    "SELECT verifier FROM contacts WHERE fingerprint=?",
1087                                    (&fingerprint,),
1088                                )
1089                                .await?;
1090
1091                            let is_verified =
1092                                verifier_id.is_some_and(|verifier_id| verifier_id != 0);
1093
1094                            if !should_do_gossip {
1095                                continue;
1096                            }
1097
1098                            let header = Aheader {
1099                                addr: addr.clone(),
1100                                public_key: key.clone(),
1101                                // Autocrypt 1.1.0 specification says that
1102                                // `prefer-encrypt` attribute SHOULD NOT be included.
1103                                prefer_encrypt: EncryptPreference::NoPreference,
1104                                verified: is_verified,
1105                            }
1106                            .to_string();
1107
1108                            message = message.header(
1109                                "Autocrypt-Gossip",
1110                                mail_builder::headers::raw::Raw::new(header),
1111                            );
1112
1113                            context
1114                                .sql
1115                                .execute(
1116                                    "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1117                                     VALUES                       (?, ?, ?)
1118                                     ON CONFLICT                  (chat_id, fingerprint)
1119                                     DO UPDATE SET timestamp=excluded.timestamp",
1120                                    (chat.id, &fingerprint, now),
1121                                )
1122                                .await?;
1123                        }
1124                    }
1125                }
1126                Loaded::Mdn { .. } => {
1127                    // Never gossip in MDNs.
1128                }
1129            }
1130
1131            // Disable compression for SecureJoin to ensure
1132            // there are no compression side channels
1133            // leaking information about the tokens.
1134            let compress = match &self.loaded {
1135                Loaded::Message { msg, .. } => {
1136                    msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1137                }
1138                Loaded::Mdn { .. } => true,
1139            };
1140
1141            let shared_secret: Option<String> = match &self.loaded {
1142                Loaded::Message { chat, msg }
1143                    if should_encrypt_with_broadcast_secret(msg, chat) =>
1144                {
1145                    let secret = load_broadcast_secret(context, chat.id).await?;
1146                    if secret.is_none() {
1147                        // If there is no shared secret yet
1148                        // because this is an old broadcast channel,
1149                        // created before we had symmetric encryption,
1150                        // we show an error message.
1151                        let text = BROADCAST_INCOMPATIBILITY_MSG;
1152                        chat::add_info_msg(context, chat.id, text).await?;
1153                        bail!(text);
1154                    }
1155                    secret
1156                }
1157                _ => None,
1158            };
1159
1160            let encrypted = if let Some(shared_secret) = shared_secret {
1161                let sign = true;
1162                encrypt_helper
1163                    .encrypt_symmetrically(context, &shared_secret, message, compress, sign)
1164                    .await?
1165            } else {
1166                // Asymmetric encryption
1167
1168                // Use SEIPDv2 if all recipients support it.
1169                let seipd_version = if encryption_pubkeys
1170                    .iter()
1171                    .all(|(_addr, pubkey)| pubkey_supports_seipdv2(pubkey))
1172                {
1173                    SeipdVersion::V2
1174                } else {
1175                    SeipdVersion::V1
1176                };
1177
1178                // Encrypt to self unconditionally,
1179                // even for a single-device setup.
1180                let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1181                encryption_keyring
1182                    .extend(encryption_pubkeys.iter().map(|(_addr, key)| (*key).clone()));
1183
1184                encrypt_helper
1185                    .encrypt(
1186                        context,
1187                        encryption_keyring,
1188                        message,
1189                        compress,
1190                        seipd_version,
1191                    )
1192                    .await?
1193            };
1194
1195            wrap_encrypted_part(encrypted)
1196        } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1197            // Never add outer multipart/mixed wrapper to MDN
1198            // as multipart/report Content-Type is used to recognize MDNs
1199            // by Delta Chat receiver and Chatmail servers
1200            // allowing them to be unencrypted and not contain Autocrypt header
1201            // without resetting Autocrypt encryption or triggering Chatmail filter
1202            // that normally only allows encrypted mails.
1203
1204            // Hidden headers are dropped.
1205            message
1206        } else {
1207            let message = hidden_headers
1208                .into_iter()
1209                .fold(message, |message, (header, value)| {
1210                    message.header(header, value)
1211                });
1212            let message = MimePart::new("multipart/mixed", vec![message]);
1213            let message = protected_headers
1214                .iter()
1215                .fold(message, |message, (header, value)| {
1216                    message.header(*header, value.clone())
1217                });
1218
1219            // Deduplicate unprotected headers that also are in the protected headers:
1220            let protected: HashSet<&str> =
1221                HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1222            unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1223
1224            message
1225        };
1226
1227        let MimeFactory {
1228            last_added_location_timestamp,
1229            ..
1230        } = self;
1231
1232        let message = render_outer_message(unprotected_headers, outer_message);
1233
1234        Ok(RenderedEmail {
1235            message,
1236            is_encrypted,
1237            last_added_location_timestamp,
1238            sync_ids_to_delete: self.sync_ids_to_delete,
1239            rfc724_mid,
1240            subject: subject_str,
1241        })
1242    }
1243
1244    /// Returns MIME part with a `message.kml` attachment.
1245    fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1246        let Loaded::Message { msg, .. } = &self.loaded else {
1247            return None;
1248        };
1249
1250        let latitude = msg.param.get_float(Param::SetLatitude)?;
1251        let longitude = msg.param.get_float(Param::SetLongitude)?;
1252
1253        let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1254        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1255            .attachment("message.kml");
1256        Some(part)
1257    }
1258
1259    /// Returns MIME part with a `location.kml` attachment
1260    /// and the timestamp of the latest location timestamp.
1261    async fn get_location_kml_part(
1262        &self,
1263        context: &Context,
1264    ) -> Result<Option<(MimePart<'static>, i64)>> {
1265        let Loaded::Message { msg, .. } = &self.loaded else {
1266            return Ok(None);
1267        };
1268
1269        let Some((kml_content, last_added_location_timestamp)) =
1270            location::get_kml(context, msg.chat_id).await?
1271        else {
1272            return Ok(None);
1273        };
1274
1275        let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1276            .attachment("location.kml");
1277        Ok(Some((part, last_added_location_timestamp)))
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 !matches!(self.pre_message_mode, PreMessageMode::Pre { .. })
1773            && let Some(msg_kml_part) = self.get_message_kml_part()
1774        {
1775            parts.push(msg_kml_part);
1776        }
1777
1778        if !matches!(self.pre_message_mode, PreMessageMode::Pre { .. })
1779            && location::is_sending_to_chat(context, msg.chat_id).await?
1780            && let Some((part, timestamp)) = self.get_location_kml_part(context).await?
1781        {
1782            parts.push(part);
1783            self.last_added_location_timestamp = Some(timestamp);
1784        }
1785
1786        // we do not piggyback sync-files to other self-sent-messages
1787        // to not risk files becoming too larger and being skipped by download-on-demand.
1788        if command == SystemMessage::MultiDeviceSync {
1789            let json = msg.param.get(Param::Arg).unwrap_or_default();
1790            let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1791            parts.push(context.build_sync_part(json.to_string()));
1792            self.sync_ids_to_delete = Some(ids.to_string());
1793        } else if command == SystemMessage::WebxdcStatusUpdate {
1794            let json = msg.param.get(Param::Arg).unwrap_or_default();
1795            parts.push(context.build_status_update_part(json));
1796        } else if msg.viewtype == Viewtype::Webxdc {
1797            let topic = self
1798                .webxdc_topic
1799                .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1800                .unwrap_or(create_iroh_header(context, msg.id).await?);
1801            headers.push((
1802                HeaderDef::IrohGossipTopic.get_headername(),
1803                mail_builder::headers::raw::Raw::new(topic).into(),
1804            ));
1805            if !matches!(self.pre_message_mode, PreMessageMode::Pre { .. })
1806                && let (Some(json), _) = context
1807                    .render_webxdc_status_update_object(
1808                        msg.id,
1809                        StatusUpdateSerial::MIN,
1810                        StatusUpdateSerial::MAX,
1811                        None,
1812                    )
1813                    .await?
1814            {
1815                parts.push(context.build_status_update_part(&json));
1816            }
1817        }
1818
1819        self.attach_selfavatar =
1820            self.attach_selfavatar && self.pre_message_mode != PreMessageMode::Post;
1821        if self.attach_selfavatar {
1822            match context.get_config(Config::Selfavatar).await? {
1823                Some(path) => match build_avatar_file(context, &path).await {
1824                    Ok(avatar) => headers.push((
1825                        "Chat-User-Avatar",
1826                        mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1827                    )),
1828                    Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1829                },
1830                None => headers.push((
1831                    "Chat-User-Avatar",
1832                    mail_builder::headers::raw::Raw::new("0").into(),
1833                )),
1834            }
1835        }
1836
1837        Ok((main_part, parts))
1838    }
1839
1840    /// Render an MDN
1841    fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1842        // RFC 6522, this also requires the `report-type` parameter which is equal
1843        // to the MIME subtype of the second body part of the multipart/report
1844        let Loaded::Mdn {
1845            rfc724_mid,
1846            additional_msg_ids,
1847        } = &self.loaded
1848        else {
1849            bail!("Attempt to render a message as MDN");
1850        };
1851
1852        // first body part: always human-readable, always REQUIRED by RFC 6522.
1853        // untranslated to no reveal sender's language.
1854        // moreover, translations in unknown languages are confusing, and clients may not display them at all
1855        let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1856
1857        let mut message = MimePart::new(
1858            "multipart/report; report-type=disposition-notification",
1859            vec![text_part],
1860        );
1861
1862        // second body part: machine-readable, always REQUIRED by RFC 6522
1863        let message_text2 = format!(
1864            "Original-Recipient: rfc822;{}\r\n\
1865             Final-Recipient: rfc822;{}\r\n\
1866             Original-Message-ID: <{}>\r\n\
1867             Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1868            self.from_addr, self.from_addr, rfc724_mid
1869        );
1870
1871        let extension_fields = if additional_msg_ids.is_empty() {
1872            "".to_string()
1873        } else {
1874            "Additional-Message-IDs: ".to_string()
1875                + &additional_msg_ids
1876                    .iter()
1877                    .map(|mid| render_rfc724_mid(mid))
1878                    .collect::<Vec<String>>()
1879                    .join(" ")
1880                + "\r\n"
1881        };
1882
1883        message.add_part(MimePart::new(
1884            "message/disposition-notification",
1885            message_text2 + &extension_fields,
1886        ));
1887
1888        Ok(message)
1889    }
1890
1891    pub fn will_be_encrypted(&self) -> bool {
1892        self.encryption_pubkeys.is_some()
1893    }
1894
1895    pub fn set_as_post_message(&mut self) {
1896        self.pre_message_mode = PreMessageMode::Post;
1897    }
1898
1899    pub fn set_as_pre_message_for(&mut self, post_message: &RenderedEmail) {
1900        self.pre_message_mode = PreMessageMode::Pre {
1901            post_msg_rfc724_mid: post_message.rfc724_mid.clone(),
1902        };
1903    }
1904}
1905
1906/// Stores the unprotected headers on the outer message, and renders it.
1907pub(crate) fn render_outer_message(
1908    unprotected_headers: Vec<(&'static str, HeaderType<'static>)>,
1909    outer_message: MimePart<'static>,
1910) -> String {
1911    let outer_message = unprotected_headers
1912        .into_iter()
1913        .fold(outer_message, |message, (header, value)| {
1914            message.header(header, value)
1915        });
1916
1917    let mut buffer = Vec::new();
1918    let cursor = Cursor::new(&mut buffer);
1919    outer_message.clone().write_part(cursor).ok();
1920    String::from_utf8_lossy(&buffer).to_string()
1921}
1922
1923/// Takes the encrypted part, wraps it in a MimePart,
1924/// and sets the appropriate Content-Type for the outer message
1925pub(crate) fn wrap_encrypted_part(encrypted: String) -> MimePart<'static> {
1926    MimePart::new(
1927        "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1928        vec![
1929            // Autocrypt part 1
1930            MimePart::new("application/pgp-encrypted", "Version: 1\r\n"),
1931            // Autocrypt part 2
1932            MimePart::new("application/octet-stream", encrypted),
1933        ],
1934    )
1935}
1936
1937fn add_headers_to_encrypted_part(
1938    message: MimePart<'static>,
1939    unprotected_headers: &[(&'static str, HeaderType<'static>)],
1940    hidden_headers: Vec<(&'static str, HeaderType<'static>)>,
1941    protected_headers: Vec<(&'static str, HeaderType<'static>)>,
1942) -> MimePart<'static> {
1943    // Store protected headers in the inner message.
1944    let message = protected_headers
1945        .into_iter()
1946        .fold(message, |message, (header, value)| {
1947            message.header(header, value)
1948        });
1949
1950    // Add hidden headers to encrypted payload.
1951    let mut message: MimePart<'static> = hidden_headers
1952        .into_iter()
1953        .fold(message, |message, (header, value)| {
1954            message.header(header, value)
1955        });
1956
1957    message = unprotected_headers
1958        .iter()
1959        // Structural headers shouldn't be added as "HP-Outer". They are defined in
1960        // <https://www.rfc-editor.org/rfc/rfc9787.html#structural-header-fields>.
1961        .filter(|(name, _)| {
1962            !(name.eq_ignore_ascii_case("mime-version")
1963                || name.eq_ignore_ascii_case("content-type")
1964                || name.eq_ignore_ascii_case("content-transfer-encoding")
1965                || name.eq_ignore_ascii_case("content-disposition"))
1966        })
1967        .fold(message, |message, (name, value)| {
1968            message.header(format!("HP-Outer: {name}"), value.clone())
1969        });
1970
1971    // Set the appropriate Content-Type for the inner message
1972    for (h, v) in &mut message.headers {
1973        if h == "Content-Type"
1974            && let mail_builder::headers::HeaderType::ContentType(ct) = v
1975        {
1976            let mut ct_new = ct.clone();
1977            ct_new = ct_new.attribute("protected-headers", "v1");
1978            ct_new = ct_new.attribute("hp", "cipher");
1979            *ct = ct_new;
1980            break;
1981        }
1982    }
1983
1984    message
1985}
1986
1987struct HeadersByConfidentiality {
1988    /// Headers that must go into IMF header section.
1989    ///
1990    /// These are standard headers such as Date, In-Reply-To, References, which cannot be placed
1991    /// anywhere else according to the standard. Placing headers here also allows them to be fetched
1992    /// individually over IMAP without downloading the message body. This is why Chat-Version is
1993    /// placed here.
1994    unprotected_headers: Vec<(&'static str, HeaderType<'static>)>,
1995
1996    /// Headers that MUST NOT (only) go into IMF header section:
1997    /// - Large headers which may hit the header section size limit on the server, such as
1998    ///   Chat-User-Avatar with a base64-encoded image inside.
1999    /// - Headers duplicated here that servers mess up with in the IMF header section, like
2000    ///   Message-ID.
2001    /// - Nonstandard headers that should be DKIM-protected because e.g. OpenDKIM only signs
2002    ///   known headers.
2003    ///
2004    /// The header should be hidden from MTA
2005    /// by moving it either into protected part
2006    /// in case of encrypted mails
2007    /// or unprotected MIME preamble in case of unencrypted mails.
2008    hidden_headers: Vec<(&'static str, HeaderType<'static>)>,
2009
2010    /// Opportunistically protected headers.
2011    ///
2012    /// These headers are placed into encrypted part *if* the message is encrypted. Place headers
2013    /// which are not needed before decryption (e.g. Chat-Group-Name) or are not interesting if the
2014    /// message cannot be decrypted (e.g. Chat-Disposition-Notification-To) here.
2015    ///
2016    /// If the message is not encrypted, these headers are placed into IMF header section, so make
2017    /// sure that the message will be encrypted if you place any sensitive information here.
2018    protected_headers: Vec<(&'static str, HeaderType<'static>)>,
2019}
2020
2021/// Split headers based on header confidentiality policy.
2022/// See [`HeadersByConfidentiality`] for more info.
2023fn group_headers_by_confidentiality(
2024    headers: Vec<(&'static str, HeaderType<'static>)>,
2025    from_addr: &str,
2026    timestamp: i64,
2027    is_encrypted: bool,
2028    is_securejoin_message: bool,
2029) -> HeadersByConfidentiality {
2030    let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2031    let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2032    let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
2033
2034    // MIME header <https://datatracker.ietf.org/doc/html/rfc2045>.
2035    unprotected_headers.push((
2036        "MIME-Version",
2037        mail_builder::headers::raw::Raw::new("1.0").into(),
2038    ));
2039
2040    for header @ (original_header_name, _header_value) in &headers {
2041        let header_name = original_header_name.to_lowercase();
2042        if header_name == "message-id" {
2043            unprotected_headers.push(header.clone());
2044            hidden_headers.push(header.clone());
2045        } else if is_hidden(&header_name) {
2046            hidden_headers.push(header.clone());
2047        } else if header_name == "from" {
2048            // Unencrypted securejoin messages should _not_ include the display name:
2049            if is_encrypted || !is_securejoin_message {
2050                protected_headers.push(header.clone());
2051            }
2052
2053            unprotected_headers.push((
2054                original_header_name,
2055                Address::new_address(None::<&'static str>, from_addr.to_string()).into(),
2056            ));
2057        } else if header_name == "to" {
2058            protected_headers.push(header.clone());
2059            if is_encrypted {
2060                unprotected_headers.push(("To", hidden_recipients().into()));
2061            } else {
2062                unprotected_headers.push(header.clone());
2063            }
2064        } else if header_name == "chat-broadcast-secret" {
2065            if is_encrypted {
2066                protected_headers.push(header.clone());
2067            }
2068        } else if is_encrypted && header_name == "date" {
2069            protected_headers.push(header.clone());
2070
2071            // Randomized date goes to unprotected header.
2072            //
2073            // We cannot just send "Thu, 01 Jan 1970 00:00:00 +0000"
2074            // or omit the header because GMX then fails with
2075            //
2076            // host mx00.emig.gmx.net[212.227.15.9] said:
2077            // 554-Transaction failed
2078            // 554-Reject due to policy restrictions.
2079            // 554 For explanation visit https://postmaster.gmx.net/en/case?...
2080            // (in reply to end of DATA command)
2081            //
2082            // and the explanation page says
2083            // "The time information deviates too much from the actual time".
2084            //
2085            // We also limit the range to 6 days (518400 seconds)
2086            // because with a larger range we got
2087            // error "500 Date header far in the past/future"
2088            // which apparently originates from Symantec Messaging Gateway
2089            // and means the message has a Date that is more
2090            // than 7 days in the past:
2091            // <https://github.com/chatmail/core/issues/7466>
2092            let timestamp_offset = rand::random_range(0..518400);
2093            let protected_timestamp = timestamp.saturating_sub(timestamp_offset);
2094            let unprotected_date =
2095                chrono::DateTime::<chrono::Utc>::from_timestamp(protected_timestamp, 0)
2096                    .unwrap()
2097                    .to_rfc2822();
2098            unprotected_headers.push((
2099                "Date",
2100                mail_builder::headers::raw::Raw::new(unprotected_date).into(),
2101            ));
2102        } else if is_encrypted {
2103            protected_headers.push(header.clone());
2104
2105            match header_name.as_str() {
2106                "subject" => {
2107                    unprotected_headers.push((
2108                        "Subject",
2109                        mail_builder::headers::raw::Raw::new("[...]").into(),
2110                    ));
2111                }
2112                "chat-version" | "autocrypt-setup-message" | "chat-is-post-message" => {
2113                    unprotected_headers.push(header.clone());
2114                }
2115                _ => {
2116                    // Other headers are removed from unprotected part.
2117                }
2118            }
2119        } else {
2120            unprotected_headers.push(header.clone())
2121        }
2122    }
2123    HeadersByConfidentiality {
2124        unprotected_headers,
2125        hidden_headers,
2126        protected_headers,
2127    }
2128}
2129
2130fn hidden_recipients() -> Address<'static> {
2131    Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
2132}
2133
2134fn should_encrypt_with_broadcast_secret(msg: &Message, chat: &Chat) -> bool {
2135    chat.typ == Chattype::OutBroadcast && must_have_only_one_recipient(msg, chat).is_none()
2136}
2137
2138fn should_hide_recipients(msg: &Message, chat: &Chat) -> bool {
2139    should_encrypt_with_broadcast_secret(msg, chat)
2140}
2141
2142fn should_encrypt_symmetrically(msg: &Message, chat: &Chat) -> bool {
2143    should_encrypt_with_broadcast_secret(msg, chat)
2144}
2145
2146/// Some messages sent into outgoing broadcast channels (member-added/member-removed)
2147/// should only go to a single recipient,
2148/// rather than all recipients.
2149/// This function returns the fingerprint of the recipient the message should be sent to.
2150fn must_have_only_one_recipient<'a>(msg: &'a Message, chat: &Chat) -> Option<Result<&'a str>> {
2151    if chat.typ != Chattype::OutBroadcast {
2152        None
2153    } else if let Some(fp) = msg.param.get(Param::Arg4) {
2154        Some(Ok(fp))
2155    } else if matches!(
2156        msg.param.get_cmd(),
2157        SystemMessage::MemberRemovedFromGroup | SystemMessage::MemberAddedToGroup
2158    ) {
2159        Some(Err(format_err!("Missing removed/added member")))
2160    } else {
2161        None
2162    }
2163}
2164
2165async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
2166    let file_name = msg.get_filename().context("msg has no file")?;
2167    let blob = msg
2168        .param
2169        .get_file_blob(context)?
2170        .context("msg has no file")?;
2171    let mimetype = msg
2172        .param
2173        .get(Param::MimeType)
2174        .unwrap_or("application/octet-stream")
2175        .to_string();
2176    let body = fs::read(blob.to_abs_path()).await?;
2177
2178    // create mime part, for Content-Disposition, see RFC 2183.
2179    // `Content-Disposition: attachment` seems not to make a difference to `Content-Disposition: inline`
2180    // at least on tested Thunderbird and Gma'l in 2017.
2181    // But I've heard about problems with inline and outl'k, so we just use the attachment-type until we
2182    // run into other problems ...
2183    let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
2184
2185    Ok(mail)
2186}
2187
2188async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
2189    let blob = match path.starts_with("$BLOBDIR/") {
2190        true => BlobObject::from_name(context, path)?,
2191        false => BlobObject::from_path(context, path.as_ref())?,
2192    };
2193    let body = fs::read(blob.to_abs_path()).await?;
2194    let encoded_body = base64::engine::general_purpose::STANDARD
2195        .encode(&body)
2196        .chars()
2197        .enumerate()
2198        .fold(String::new(), |mut res, (i, c)| {
2199            if i % 78 == 77 {
2200                res.push(' ')
2201            }
2202            res.push(c);
2203            res
2204        });
2205    Ok(encoded_body)
2206}
2207
2208fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
2209    let addr_lc = addr.to_lowercase();
2210    recipients
2211        .iter()
2212        .any(|(_, cur)| cur.to_lowercase() == addr_lc)
2213}
2214
2215fn render_rfc724_mid(rfc724_mid: &str) -> String {
2216    let rfc724_mid = rfc724_mid.trim().to_string();
2217
2218    if rfc724_mid.chars().next().unwrap_or_default() == '<' {
2219        rfc724_mid
2220    } else {
2221        format!("<{rfc724_mid}>")
2222    }
2223}
2224
2225/// Encodes UTF-8 string as a single B-encoded-word.
2226///
2227/// We manually encode some headers because as of
2228/// version 0.4.4 mail-builder crate does not encode
2229/// newlines correctly if they appear in a text header.
2230fn b_encode(value: &str) -> String {
2231    format!(
2232        "=?utf-8?B?{}?=",
2233        base64::engine::general_purpose::STANDARD.encode(value)
2234    )
2235}
2236
2237pub(crate) async fn render_symm_encrypted_securejoin_message(
2238    context: &Context,
2239    step: &str,
2240    rfc724_mid: &str,
2241    attach_self_pubkey: bool,
2242    auth: &str,
2243    shared_secret: &str,
2244) -> Result<String> {
2245    info!(context, "Sending secure-join message {step:?}.");
2246
2247    let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
2248
2249    let from_addr = context.get_primary_self_addr().await?;
2250    let from = new_address_with_name("", from_addr.to_string());
2251    headers.push(("From", from.into()));
2252
2253    let to: Vec<Address<'static>> = vec![hidden_recipients()];
2254    headers.push((
2255        "To",
2256        mail_builder::headers::address::Address::new_list(to.clone()).into(),
2257    ));
2258
2259    headers.push((
2260        "Subject",
2261        mail_builder::headers::text::Text::new("Secure-Join".to_string()).into(),
2262    ));
2263
2264    let timestamp = time();
2265    let date = chrono::DateTime::<chrono::Utc>::from_timestamp(timestamp, 0)
2266        .unwrap()
2267        .to_rfc2822();
2268    headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
2269
2270    headers.push((
2271        "Message-ID",
2272        mail_builder::headers::message_id::MessageId::new(rfc724_mid.to_string()).into(),
2273    ));
2274
2275    // Automatic Response headers <https://www.rfc-editor.org/rfc/rfc3834>
2276    if context.get_config_bool(Config::Bot).await? {
2277        headers.push((
2278            "Auto-Submitted",
2279            mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
2280        ));
2281    }
2282
2283    let encrypt_helper = EncryptHelper::new(context).await?;
2284
2285    if attach_self_pubkey {
2286        let aheader = encrypt_helper.get_aheader().to_string();
2287        headers.push((
2288            "Autocrypt",
2289            mail_builder::headers::raw::Raw::new(aheader).into(),
2290        ));
2291    }
2292
2293    headers.push((
2294        "Secure-Join",
2295        mail_builder::headers::raw::Raw::new(step.to_string()).into(),
2296    ));
2297
2298    headers.push((
2299        "Secure-Join-Auth",
2300        mail_builder::headers::text::Text::new(auth.to_string()).into(),
2301    ));
2302
2303    let message: MimePart<'static> = MimePart::new("text/plain", "Secure-Join");
2304
2305    let is_encrypted = true;
2306    let is_securejoin_message = true;
2307    let HeadersByConfidentiality {
2308        unprotected_headers,
2309        hidden_headers,
2310        protected_headers,
2311    } = group_headers_by_confidentiality(
2312        headers,
2313        &from_addr,
2314        timestamp,
2315        is_encrypted,
2316        is_securejoin_message,
2317    );
2318
2319    let outer_message = {
2320        let message = add_headers_to_encrypted_part(
2321            message,
2322            &unprotected_headers,
2323            hidden_headers,
2324            protected_headers,
2325        );
2326
2327        // Disable compression for SecureJoin to ensure
2328        // there are no compression side channels
2329        // leaking information about the tokens.
2330        let compress = false;
2331        // Only sign the message if we attach the pubkey.
2332        let sign = attach_self_pubkey;
2333        let encrypted = encrypt_helper
2334            .encrypt_symmetrically(context, shared_secret, message, compress, sign)
2335            .await?;
2336
2337        wrap_encrypted_part(encrypted)
2338    };
2339
2340    let message = render_outer_message(unprotected_headers, outer_message);
2341
2342    Ok(message)
2343}
2344
2345#[cfg(test)]
2346mod mimefactory_tests;