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