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