deltachat/
mimefactory.rs

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