1use std::collections::{BTreeSet, HashSet};
4use std::io::Cursor;
5
6use anyhow::{Context as _, Result, bail, ensure};
7use base64::Engine as _;
8use data_encoding::BASE32_NOPAD;
9use deltachat_contact_tools::sanitize_bidi_characters;
10use iroh_gossip::proto::TopicId;
11use mail_builder::headers::HeaderType;
12use mail_builder::headers::address::{Address, EmailAddress};
13use mail_builder::mime::MimePart;
14use tokio::fs;
15
16use crate::aheader::{Aheader, EncryptPreference};
17use crate::blob::BlobObject;
18use crate::chat::{self, Chat};
19use crate::config::Config;
20use crate::constants::ASM_SUBJECT;
21use crate::constants::{Chattype, DC_FROM_HANDSHAKE};
22use crate::contact::{Contact, ContactId, Origin};
23use crate::context::Context;
24use crate::e2ee::EncryptHelper;
25use crate::ensure_and_debug_assert;
26use crate::ephemeral::Timer as EphemeralTimer;
27use crate::headerdef::HeaderDef;
28use crate::key::{DcKey, SignedPublicKey, self_fingerprint};
29use crate::location;
30use crate::log::{info, warn};
31use crate::message::{Message, MsgId, Viewtype};
32use crate::mimeparser::{SystemMessage, is_hidden};
33use crate::param::Param;
34use crate::peer_channels::{create_iroh_header, get_iroh_topic_for_msg};
35use crate::simplify::escape_message_footer_marks;
36use crate::stock_str;
37use crate::tools::{
38 IsNoneOrEmpty, create_outgoing_rfc724_mid, create_smeared_timestamp, remove_subject_prefix,
39 time,
40};
41use crate::webxdc::StatusUpdateSerial;
42
43pub 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#[derive(Debug, Clone)]
63pub struct MimeFactory {
64 from_addr: String,
65 from_displayname: String,
66
67 sender_displayname: Option<String>,
74
75 selfstatus: String,
76
77 recipients: Vec<String>,
91
92 encryption_keys: Option<Vec<(String, SignedPublicKey)>>,
98
99 to: Vec<(String, String)>,
106
107 past_members: Vec<(String, String)>,
109
110 member_fingerprints: Vec<String>,
116
117 member_timestamps: Vec<i64>,
123
124 timestamp: i64,
125 loaded: Loaded,
126 in_reply_to: String,
127
128 references: Vec<String>,
130
131 req_mdn: bool,
134
135 last_added_location_id: Option<u32>,
136
137 sync_ids_to_delete: Option<String>,
142
143 pub attach_selfavatar: bool,
145
146 webxdc_topic: Option<TopicId>,
148}
149
150#[derive(Debug, Clone)]
152pub struct RenderedEmail {
153 pub message: String,
154 pub is_encrypted: bool,
156 pub last_added_location_id: Option<u32>,
157
158 pub sync_ids_to_delete: Option<String>,
161
162 pub rfc724_mid: String,
164
165 pub subject: String,
167}
168
169fn new_address_with_name(name: &str, address: String) -> Address<'static> {
170 Address::new_address(
171 if name == address || name.is_empty() {
172 None
173 } else {
174 Some(name.to_string())
175 },
176 address,
177 )
178}
179
180impl MimeFactory {
181 pub async fn from_msg(context: &Context, msg: Message) -> Result<MimeFactory> {
182 let now = time();
183 let chat = Chat::load_from_db(context, msg.chat_id).await?;
184 let attach_profile_data = Self::should_attach_profile_data(&msg);
185 let undisclosed_recipients = chat.typ == Chattype::OutBroadcast;
186
187 let from_addr = context.get_primary_self_addr().await?;
188 let config_displayname = context
189 .get_config(Config::Displayname)
190 .await?
191 .unwrap_or_default();
192 let (from_displayname, sender_displayname) =
193 if let Some(override_name) = msg.param.get(Param::OverrideSenderDisplayname) {
194 (override_name.to_string(), Some(config_displayname))
195 } else {
196 let name = match attach_profile_data {
197 true => config_displayname,
198 false => "".to_string(),
199 };
200 (name, None)
201 };
202
203 let mut recipients = Vec::new();
204 let mut to = Vec::new();
205 let mut past_members = Vec::new();
206 let mut member_fingerprints = Vec::new();
207 let mut member_timestamps = Vec::new();
208 let mut recipient_ids = HashSet::new();
209 let mut req_mdn = false;
210
211 let encryption_keys;
212
213 let self_fingerprint = self_fingerprint(context).await?;
214
215 if chat.is_self_talk() {
216 to.push((from_displayname.to_string(), from_addr.to_string()));
217
218 encryption_keys = if msg.param.get_bool(Param::ForcePlaintext).unwrap_or(false) {
219 None
220 } else {
221 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 encryption_keys = None;
234 } else {
235 let email_to_remove = if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
236 msg.param.get(Param::Arg)
237 } else {
238 None
239 };
240
241 let is_encrypted = if msg
242 .param
243 .get_bool(Param::ForcePlaintext)
244 .unwrap_or_default()
245 {
246 false
247 } else {
248 msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
249 || chat.is_encrypted(context).await?
250 };
251
252 let mut keys = Vec::new();
253 let mut missing_key_addresses = BTreeSet::new();
254 context
255 .sql
256 .query_map(
261 "SELECT
262 c.authname,
263 c.addr,
264 c.fingerprint,
265 c.id,
266 cc.add_timestamp,
267 cc.remove_timestamp,
268 k.public_key
269 FROM chats_contacts cc
270 LEFT JOIN contacts c ON cc.contact_id=c.id
271 LEFT JOIN public_keys k ON k.fingerprint=c.fingerprint
272 WHERE cc.chat_id=?
273 AND (cc.contact_id>9 OR (cc.contact_id=1 AND ?))
274 ORDER BY cc.add_timestamp DESC",
275 (msg.chat_id, chat.typ == Chattype::Group),
276 |row| {
277 let authname: String = row.get(0)?;
278 let addr: String = row.get(1)?;
279 let fingerprint: String = row.get(2)?;
280 let id: ContactId = row.get(3)?;
281 let add_timestamp: i64 = row.get(4)?;
282 let remove_timestamp: i64 = row.get(5)?;
283 let public_key_bytes_opt: Option<Vec<u8>> = row.get(6)?;
284 Ok((authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt))
285 },
286 |rows| {
287 let mut past_member_timestamps = Vec::new();
288 let mut past_member_fingerprints = Vec::new();
289
290 for row in rows {
291 let (authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt) = row?;
292
293 let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
294 Some(SignedPublicKey::from_slice(public_key_bytes)?)
295 } else {
296 None
297 };
298
299 let addr = if id == ContactId::SELF {
300 from_addr.to_string()
301 } else {
302 addr
303 };
304 let name = match attach_profile_data {
305 true => authname,
306 false => "".to_string(),
307 };
308 if add_timestamp >= remove_timestamp {
309 if !recipients_contain_addr(&to, &addr) {
310 if id != ContactId::SELF {
311 recipients.push(addr.clone());
312 }
313 if !undisclosed_recipients {
314 to.push((name, addr.clone()));
315
316 if is_encrypted {
317 if !fingerprint.is_empty() {
318 member_fingerprints.push(fingerprint);
319 } else if id == ContactId::SELF {
320 member_fingerprints.push(self_fingerprint.to_string());
321 } else {
322 ensure_and_debug_assert!(member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
323 }
324 }
325 member_timestamps.push(add_timestamp);
326 }
327 }
328 recipient_ids.insert(id);
329
330 if let Some(public_key) = public_key_opt {
331 keys.push((addr.clone(), public_key))
332 } else if id != ContactId::SELF {
333 missing_key_addresses.insert(addr.clone());
334 if is_encrypted {
335 warn!(context, "Missing key for {addr}");
336 }
337 }
338 } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
339 if !recipients_contain_addr(&past_members, &addr) {
342 if let Some(email_to_remove) = email_to_remove {
343 if email_to_remove == addr {
344 if id != ContactId::SELF {
348 recipients.push(addr.clone());
349 }
350
351 if let Some(public_key) = public_key_opt {
352 keys.push((addr.clone(), public_key))
353 } else if id != ContactId::SELF {
354 missing_key_addresses.insert(addr.clone());
355 if is_encrypted {
356 warn!(context, "Missing key for {addr}");
357 }
358 }
359 }
360 }
361 if !undisclosed_recipients {
362 past_members.push((name, addr.clone()));
363 past_member_timestamps.push(remove_timestamp);
364
365 if is_encrypted {
366 if !fingerprint.is_empty() {
367 past_member_fingerprints.push(fingerprint);
368 } else if id == ContactId::SELF {
369 past_member_fingerprints.push(self_fingerprint.to_string());
372 } else {
373 ensure_and_debug_assert!(past_member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
374 }
375 }
376 }
377 }
378 }
379 }
380
381 ensure_and_debug_assert!(
382 member_timestamps.len() >= to.len(),
383 "member_timestamps.len() ({}) < to.len() ({})",
384 member_timestamps.len(), to.len());
385 ensure_and_debug_assert!(
386 member_fingerprints.is_empty() || member_fingerprints.len() >= to.len(),
387 "member_fingerprints.len() ({}) < to.len() ({})",
388 member_fingerprints.len(), to.len());
389
390 if to.len() > 1 {
391 if let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
392 to.remove(position);
393 member_timestamps.remove(position);
394 if is_encrypted {
395 member_fingerprints.remove(position);
396 }
397 }
398 }
399
400 member_timestamps.extend(past_member_timestamps);
401 if is_encrypted {
402 member_fingerprints.extend(past_member_fingerprints);
403 }
404 Ok(())
405 },
406 )
407 .await?;
408 let recipient_ids: Vec<_> = recipient_ids.into_iter().collect();
409 ContactId::scaleup_origin(context, &recipient_ids, Origin::OutgoingTo).await?;
410
411 if !msg.is_system_message()
412 && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
413 && context.should_request_mdns().await?
414 {
415 req_mdn = true;
416 }
417
418 encryption_keys = if !is_encrypted {
419 None
420 } else {
421 if keys.is_empty() && !recipients.is_empty() {
422 bail!(
423 "No recipient keys are available, cannot encrypt to {:?}.",
424 recipients
425 );
426 }
427
428 if !missing_key_addresses.is_empty() {
430 recipients.retain(|addr| !missing_key_addresses.contains(addr));
431 }
432
433 Some(keys)
434 };
435 }
436
437 let (in_reply_to, references) = context
438 .sql
439 .query_row(
440 "SELECT mime_in_reply_to, IFNULL(mime_references, '')
441 FROM msgs WHERE id=?",
442 (msg.id,),
443 |row| {
444 let in_reply_to: String = row.get(0)?;
445 let references: String = row.get(1)?;
446
447 Ok((in_reply_to, references))
448 },
449 )
450 .await?;
451 let references: Vec<String> = references
452 .trim()
453 .split_ascii_whitespace()
454 .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
455 .collect();
456 let selfstatus = match attach_profile_data {
457 true => context
458 .get_config(Config::Selfstatus)
459 .await?
460 .unwrap_or_default(),
461 false => "".to_string(),
462 };
463 let attach_selfavatar = Self::should_attach_selfavatar(context, &msg).await;
464
465 ensure_and_debug_assert!(
466 member_timestamps.is_empty()
467 || to.len() + past_members.len() == member_timestamps.len(),
468 "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
469 to.len(),
470 past_members.len(),
471 member_timestamps.len(),
472 );
473 let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
474 let factory = MimeFactory {
475 from_addr,
476 from_displayname,
477 sender_displayname,
478 selfstatus,
479 recipients,
480 encryption_keys,
481 to,
482 past_members,
483 member_fingerprints,
484 member_timestamps,
485 timestamp: msg.timestamp_sort,
486 loaded: Loaded::Message { msg, chat },
487 in_reply_to,
488 references,
489 req_mdn,
490 last_added_location_id: None,
491 sync_ids_to_delete: None,
492 attach_selfavatar,
493 webxdc_topic,
494 };
495 Ok(factory)
496 }
497
498 pub async fn from_mdn(
499 context: &Context,
500 from_id: ContactId,
501 rfc724_mid: String,
502 additional_msg_ids: Vec<String>,
503 ) -> Result<MimeFactory> {
504 let contact = Contact::get_by_id(context, from_id).await?;
505 let from_addr = context.get_primary_self_addr().await?;
506 let timestamp = create_smeared_timestamp(context);
507
508 let addr = contact.get_addr().to_string();
509 let encryption_keys = if contact.is_key_contact() {
510 if let Some(key) = contact.public_key(context).await? {
511 Some(vec![(addr.clone(), key)])
512 } else {
513 Some(Vec::new())
514 }
515 } else {
516 None
517 };
518
519 let res = MimeFactory {
520 from_addr,
521 from_displayname: "".to_string(),
522 sender_displayname: None,
523 selfstatus: "".to_string(),
524 recipients: vec![addr],
525 encryption_keys,
526 to: vec![("".to_string(), contact.get_addr().to_string())],
527 past_members: vec![],
528 member_fingerprints: vec![],
529 member_timestamps: vec![],
530 timestamp,
531 loaded: Loaded::Mdn {
532 rfc724_mid,
533 additional_msg_ids,
534 },
535 in_reply_to: String::default(),
536 references: Vec::new(),
537 req_mdn: false,
538 last_added_location_id: None,
539 sync_ids_to_delete: None,
540 attach_selfavatar: false,
541 webxdc_topic: None,
542 };
543
544 Ok(res)
545 }
546
547 fn should_skip_autocrypt(&self) -> bool {
548 match &self.loaded {
549 Loaded::Message { msg, .. } => {
550 msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
551 }
552 Loaded::Mdn { .. } => false,
553 }
554 }
555
556 fn should_attach_profile_data(msg: &Message) -> bool {
557 msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
558 let step = msg.param.get(Param::Arg).unwrap_or_default();
559 step == "vg-request-with-auth"
565 || step == "vc-request-with-auth"
566 || step == "vg-member-added"
567 || step == "vc-contact-confirm"
568 }
569 }
570
571 async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
572 Self::should_attach_profile_data(msg)
573 && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
574 Ok(should) => should,
575 Err(err) => {
576 warn!(
577 context,
578 "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
579 );
580 false
581 }
582 }
583 }
584
585 fn grpimage(&self) -> Option<String> {
586 match &self.loaded {
587 Loaded::Message { chat, msg } => {
588 let cmd = msg.param.get_cmd();
589
590 match cmd {
591 SystemMessage::MemberAddedToGroup => {
592 return chat.param.get(Param::ProfileImage).map(Into::into);
593 }
594 SystemMessage::GroupImageChanged => {
595 return msg.param.get(Param::Arg).map(Into::into);
596 }
597 _ => {}
598 }
599
600 if msg
601 .param
602 .get_bool(Param::AttachGroupImage)
603 .unwrap_or_default()
604 {
605 return chat.param.get(Param::ProfileImage).map(Into::into);
606 }
607
608 None
609 }
610 Loaded::Mdn { .. } => None,
611 }
612 }
613
614 async fn subject_str(&self, context: &Context) -> Result<String> {
615 let subject = match &self.loaded {
616 Loaded::Message { chat, msg } => {
617 let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
618
619 if !msg.subject.is_empty() {
620 return Ok(msg.subject.clone());
621 }
622
623 if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
624 && quoted_msg_subject.is_none_or_empty()
625 {
626 let re = if self.in_reply_to.is_empty() {
627 ""
628 } else {
629 "Re: "
630 };
631 return Ok(format!("{}{}", re, chat.name));
632 }
633
634 let parent_subject = if quoted_msg_subject.is_none_or_empty() {
635 chat.param.get(Param::LastSubject)
636 } else {
637 quoted_msg_subject.as_deref()
638 };
639 if let Some(last_subject) = parent_subject {
640 return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
641 }
642
643 let self_name = match Self::should_attach_profile_data(msg) {
644 true => context.get_config(Config::Displayname).await?,
645 false => None,
646 };
647 let self_name = &match self_name {
648 Some(name) => name,
649 None => context.get_config(Config::Addr).await?.unwrap_or_default(),
650 };
651 stock_str::subject_for_new_contact(context, self_name).await
652 }
653 Loaded::Mdn { .. } => "Receipt Notification".to_string(), };
655
656 Ok(subject)
657 }
658
659 pub fn recipients(&self) -> Vec<String> {
660 self.recipients.clone()
661 }
662
663 pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
666 let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
667
668 let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
669
670 let mut to: Vec<Address<'static>> = Vec::new();
671 for (name, addr) in &self.to {
672 to.push(Address::new_address(
673 if name.is_empty() {
674 None
675 } else {
676 Some(name.to_string())
677 },
678 addr.clone(),
679 ));
680 }
681
682 let mut past_members: Vec<Address<'static>> = Vec::new(); for (name, addr) in &self.past_members {
684 past_members.push(Address::new_address(
685 if name.is_empty() {
686 None
687 } else {
688 Some(name.to_string())
689 },
690 addr.clone(),
691 ));
692 }
693
694 ensure_and_debug_assert!(
695 self.member_timestamps.is_empty()
696 || to.len() + past_members.len() == self.member_timestamps.len(),
697 "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
698 to.len(),
699 past_members.len(),
700 self.member_timestamps.len(),
701 );
702 if to.is_empty() {
703 to.push(hidden_recipients());
704 }
705
706 headers.push(("From", from.into()));
709
710 if let Some(sender_displayname) = &self.sender_displayname {
711 let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
712 headers.push(("Sender", sender.into()));
713 }
714 headers.push((
715 "To",
716 mail_builder::headers::address::Address::new_list(to.clone()).into(),
717 ));
718 if !past_members.is_empty() {
719 headers.push((
720 "Chat-Group-Past-Members",
721 mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
722 ));
723 }
724
725 if let Loaded::Message { chat, .. } = &self.loaded {
726 if chat.typ == Chattype::Group {
727 if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await?
728 {
729 headers.push((
730 "Chat-Group-Member-Timestamps",
731 mail_builder::headers::raw::Raw::new(
732 self.member_timestamps
733 .iter()
734 .map(|ts| ts.to_string())
735 .collect::<Vec<String>>()
736 .join(" "),
737 )
738 .into(),
739 ));
740 }
741
742 if !self.member_fingerprints.is_empty() {
743 headers.push((
744 "Chat-Group-Member-Fpr",
745 mail_builder::headers::raw::Raw::new(
746 self.member_fingerprints
747 .iter()
748 .map(|fp| fp.to_string())
749 .collect::<Vec<String>>()
750 .join(" "),
751 )
752 .into(),
753 ));
754 }
755 }
756 }
757
758 let subject_str = self.subject_str(context).await?;
759 headers.push((
760 "Subject",
761 mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
762 ));
763
764 let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
765 .unwrap()
766 .to_rfc2822();
767 headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
768
769 let rfc724_mid = match &self.loaded {
770 Loaded::Message { msg, .. } => msg.rfc724_mid.clone(),
771 Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
772 };
773 headers.push((
774 "Message-ID",
775 mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
776 ));
777
778 if !self.in_reply_to.is_empty() {
780 headers.push((
781 "In-Reply-To",
782 mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
783 ));
784 }
785 if !self.references.is_empty() {
786 headers.push((
787 "References",
788 mail_builder::headers::message_id::MessageId::<'static>::new_list(
789 self.references.iter().map(|s| s.to_string()),
790 )
791 .into(),
792 ));
793 }
794
795 if let Loaded::Mdn { .. } = self.loaded {
797 headers.push((
798 "Auto-Submitted",
799 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
800 ));
801 } else if context.get_config_bool(Config::Bot).await? {
802 headers.push((
803 "Auto-Submitted",
804 mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
805 ));
806 } else if let Loaded::Message { msg, .. } = &self.loaded {
807 if msg.param.get_cmd() == SystemMessage::SecurejoinMessage {
808 let step = msg.param.get(Param::Arg).unwrap_or_default();
809 if step != "vg-request" && step != "vc-request" {
810 headers.push((
811 "Auto-Submitted",
812 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
813 ));
814 }
815 }
816 }
817
818 if let Loaded::Message { chat, .. } = &self.loaded {
819 if chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast {
820 headers.push((
821 "List-ID",
822 mail_builder::headers::text::Text::new(format!(
823 "{} <{}>",
824 chat.name, chat.grpid
825 ))
826 .into(),
827 ));
828 }
829 }
830
831 if let Loaded::Message { msg, .. } = &self.loaded {
832 if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
833 headers.push((
834 "Chat-Edit",
835 mail_builder::headers::message_id::MessageId::new(
836 original_rfc724_mid.to_string(),
837 )
838 .into(),
839 ));
840 } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
841 headers.push((
842 "Chat-Delete",
843 mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
844 .into(),
845 ));
846 }
847 }
848
849 headers.push((
851 "Chat-Version",
852 mail_builder::headers::raw::Raw::new("1.0").into(),
853 ));
854
855 if self.req_mdn {
856 headers.push((
860 "Chat-Disposition-Notification-To",
861 mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
862 ));
863 }
864
865 let grpimage = self.grpimage();
866 let skip_autocrypt = self.should_skip_autocrypt();
867 let encrypt_helper = EncryptHelper::new(context).await?;
868
869 if !skip_autocrypt {
870 let aheader = encrypt_helper.get_aheader().to_string();
872 headers.push((
873 "Autocrypt",
874 mail_builder::headers::raw::Raw::new(aheader).into(),
875 ));
876 }
877
878 let is_encrypted = self.encryption_keys.is_some();
879
880 if let Loaded::Message { msg, .. } = &self.loaded {
884 let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
885 if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
886 headers.push((
887 "Ephemeral-Timer",
888 mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
889 ));
890 }
891 }
892
893 let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
894 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
895 } else {
896 false
897 };
898
899 let message: MimePart<'static> = match &self.loaded {
900 Loaded::Message { msg, .. } => {
901 let msg = msg.clone();
902 let (main_part, mut parts) = self
903 .render_message(context, &mut headers, &grpimage, is_encrypted)
904 .await?;
905 if parts.is_empty() {
906 main_part
908 } else {
909 parts.insert(0, main_part);
910
911 if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
913 MimePart::new("multipart/report; report-type=multi-device-sync", parts)
914 } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
915 MimePart::new("multipart/report; report-type=status-update", parts)
916 } else {
917 MimePart::new("multipart/mixed", parts)
918 }
919 }
920 }
921 Loaded::Mdn { .. } => self.render_mdn()?,
922 };
923
924 let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
933
934 let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
947
948 let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
957
958 unprotected_headers.push((
960 "MIME-Version",
961 mail_builder::headers::raw::Raw::new("1.0").into(),
962 ));
963 for header @ (original_header_name, _header_value) in &headers {
964 let header_name = original_header_name.to_lowercase();
965 if header_name == "message-id" {
966 unprotected_headers.push(header.clone());
967 hidden_headers.push(header.clone());
968 } else if is_hidden(&header_name) {
969 hidden_headers.push(header.clone());
970 } else if header_name == "autocrypt"
971 && !context.get_config_bool(Config::ProtectAutocrypt).await?
972 {
973 unprotected_headers.push(header.clone());
974 } else if header_name == "from" {
975 if is_encrypted || !is_securejoin_message {
977 protected_headers.push(header.clone());
978 }
979
980 unprotected_headers.push((
981 original_header_name,
982 Address::new_address(None::<&'static str>, self.from_addr.clone()).into(),
983 ));
984 } else if header_name == "to" {
985 protected_headers.push(header.clone());
986 if is_encrypted {
987 let mut to_without_names = to
988 .clone()
989 .into_iter()
990 .filter_map(|header| match header {
991 Address::Address(mb) => Some(Address::Address(EmailAddress {
992 name: None,
993 email: mb.email,
994 })),
995 _ => None,
996 })
997 .collect::<Vec<_>>();
998 if to_without_names.is_empty() {
999 to_without_names.push(hidden_recipients());
1000 }
1001 unprotected_headers.push((
1002 original_header_name,
1003 Address::new_list(to_without_names).into(),
1004 ));
1005 } else {
1006 unprotected_headers.push(header.clone());
1007 }
1008 } else if is_encrypted {
1009 protected_headers.push(header.clone());
1010
1011 match header_name.as_str() {
1012 "subject" => {
1013 unprotected_headers.push((
1014 "Subject",
1015 mail_builder::headers::raw::Raw::new("[...]").into(),
1016 ));
1017 }
1018 "date"
1019 | "in-reply-to"
1020 | "references"
1021 | "auto-submitted"
1022 | "chat-version"
1023 | "autocrypt-setup-message" => {
1024 unprotected_headers.push(header.clone());
1025 }
1026 _ => {
1027 }
1029 }
1030 } else {
1031 protected_headers.push(header.clone());
1035 unprotected_headers.push(header.clone())
1036 }
1037 }
1038
1039 let outer_message = if let Some(encryption_keys) = self.encryption_keys {
1040 let message = protected_headers
1042 .into_iter()
1043 .fold(message, |message, (header, value)| {
1044 message.header(header, value)
1045 });
1046
1047 let mut message: MimePart<'static> = hidden_headers
1049 .into_iter()
1050 .fold(message, |message, (header, value)| {
1051 message.header(header, value)
1052 });
1053
1054 let multiple_recipients =
1056 encryption_keys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1057
1058 let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1059 let now = time();
1060
1061 match &self.loaded {
1062 Loaded::Message { chat, msg } => {
1063 if chat.typ != Chattype::OutBroadcast {
1064 for (addr, key) in &encryption_keys {
1065 let fingerprint = key.dc_fingerprint().hex();
1066 let cmd = msg.param.get_cmd();
1067 let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1068 || cmd == SystemMessage::SecurejoinMessage
1069 || multiple_recipients && {
1070 let gossiped_timestamp: Option<i64> = context
1071 .sql
1072 .query_get_value(
1073 "SELECT timestamp
1074 FROM gossip_timestamp
1075 WHERE chat_id=? AND fingerprint=?",
1076 (chat.id, &fingerprint),
1077 )
1078 .await?;
1079
1080 gossip_period == 0
1087 || gossiped_timestamp
1088 .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1089 };
1090
1091 if !should_do_gossip {
1092 continue;
1093 }
1094
1095 let header = Aheader {
1096 addr: addr.clone(),
1097 public_key: key.clone(),
1098 prefer_encrypt: EncryptPreference::NoPreference,
1101 verified: false,
1102 }
1103 .to_string();
1104
1105 message = message.header(
1106 "Autocrypt-Gossip",
1107 mail_builder::headers::raw::Raw::new(header),
1108 );
1109
1110 context
1111 .sql
1112 .execute(
1113 "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1114 VALUES (?, ?, ?)
1115 ON CONFLICT (chat_id, fingerprint)
1116 DO UPDATE SET timestamp=excluded.timestamp",
1117 (chat.id, &fingerprint, now),
1118 )
1119 .await?;
1120 }
1121 }
1122 }
1123 Loaded::Mdn { .. } => {
1124 }
1126 }
1127
1128 for (h, v) in &mut message.headers {
1130 if h == "Content-Type" {
1131 if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1132 *ct = ct.clone().attribute("protected-headers", "v1");
1133 }
1134 }
1135 }
1136
1137 let compress = match &self.loaded {
1141 Loaded::Message { msg, .. } => {
1142 msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1143 }
1144 Loaded::Mdn { .. } => true,
1145 };
1146
1147 let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1150 encryption_keyring.extend(encryption_keys.iter().map(|(_addr, key)| (*key).clone()));
1151
1152 let encrypted = encrypt_helper
1156 .encrypt(context, encryption_keyring, message, compress)
1157 .await?
1158 + "\n";
1159
1160 MimePart::new(
1162 "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1163 vec![
1164 MimePart::new("application/pgp-encrypted", "Version: 1\r\n").header(
1166 "Content-Description",
1167 mail_builder::headers::raw::Raw::new("PGP/MIME version identification"),
1168 ),
1169 MimePart::new(
1171 "application/octet-stream; name=\"encrypted.asc\"",
1172 encrypted,
1173 )
1174 .header(
1175 "Content-Description",
1176 mail_builder::headers::raw::Raw::new("OpenPGP encrypted message"),
1177 )
1178 .header(
1179 "Content-Disposition",
1180 mail_builder::headers::raw::Raw::new("inline; filename=\"encrypted.asc\";"),
1181 ),
1182 ],
1183 )
1184 } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1185 message
1194 } else {
1195 let message = hidden_headers
1196 .into_iter()
1197 .fold(message, |message, (header, value)| {
1198 message.header(header, value)
1199 });
1200 let message = MimePart::new("multipart/mixed", vec![message]);
1201 let mut message = protected_headers
1202 .iter()
1203 .fold(message, |message, (header, value)| {
1204 message.header(*header, value.clone())
1205 });
1206
1207 if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
1208 let protected: HashSet<&str> =
1210 HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1211 unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1212
1213 message
1214 } else {
1215 for (h, v) in &mut message.headers {
1216 if h == "Content-Type" {
1217 if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1218 *ct = ct.clone().attribute("protected-headers", "v1");
1219 }
1220 }
1221 }
1222
1223 let signature = encrypt_helper.sign(context, &message).await?;
1224 MimePart::new(
1225 "multipart/signed; protocol=\"application/pgp-signature\"; protected",
1226 vec![
1227 message,
1228 MimePart::new(
1229 "application/pgp-signature; name=\"signature.asc\"",
1230 signature,
1231 )
1232 .header(
1233 "Content-Description",
1234 mail_builder::headers::raw::Raw::<'static>::new(
1235 "OpenPGP digital signature",
1236 ),
1237 )
1238 .attachment("signature"),
1239 ],
1240 )
1241 }
1242 };
1243
1244 let outer_message = unprotected_headers
1246 .into_iter()
1247 .fold(outer_message, |message, (header, value)| {
1248 message.header(header, value)
1249 });
1250
1251 let MimeFactory {
1252 last_added_location_id,
1253 ..
1254 } = self;
1255
1256 let mut buffer = Vec::new();
1257 let cursor = Cursor::new(&mut buffer);
1258 outer_message.clone().write_part(cursor).ok();
1259 let message = String::from_utf8_lossy(&buffer).to_string();
1260
1261 Ok(RenderedEmail {
1262 message,
1263 is_encrypted,
1265 last_added_location_id,
1266 sync_ids_to_delete: self.sync_ids_to_delete,
1267 rfc724_mid,
1268 subject: subject_str,
1269 })
1270 }
1271
1272 fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1274 let Loaded::Message { msg, .. } = &self.loaded else {
1275 return None;
1276 };
1277
1278 let latitude = msg.param.get_float(Param::SetLatitude)?;
1279 let longitude = msg.param.get_float(Param::SetLongitude)?;
1280
1281 let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1282 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1283 .attachment("message.kml");
1284 Some(part)
1285 }
1286
1287 async fn get_location_kml_part(
1289 &mut self,
1290 context: &Context,
1291 ) -> Result<Option<MimePart<'static>>> {
1292 let Loaded::Message { msg, .. } = &self.loaded else {
1293 return Ok(None);
1294 };
1295
1296 let Some((kml_content, last_added_location_id)) =
1297 location::get_kml(context, msg.chat_id).await?
1298 else {
1299 return Ok(None);
1300 };
1301
1302 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1303 .attachment("location.kml");
1304 if !msg.param.exists(Param::SetLatitude) {
1305 self.last_added_location_id = Some(last_added_location_id);
1307 }
1308 Ok(Some(part))
1309 }
1310
1311 async fn render_message(
1312 &mut self,
1313 context: &Context,
1314 headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1315 grpimage: &Option<String>,
1316 is_encrypted: bool,
1317 ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1318 let Loaded::Message { chat, msg } = &self.loaded else {
1319 bail!("Attempt to render MDN as a message");
1320 };
1321 let chat = chat.clone();
1322 let msg = msg.clone();
1323 let command = msg.param.get_cmd();
1324 let mut placeholdertext = None;
1325
1326 let send_verified_headers = match chat.typ {
1327 Chattype::Single => true,
1328 Chattype::Group => true,
1329 Chattype::Mailinglist => false,
1331 Chattype::OutBroadcast | Chattype::InBroadcast => false,
1332 };
1333 if chat.is_protected() && send_verified_headers {
1334 headers.push((
1335 "Chat-Verified",
1336 mail_builder::headers::raw::Raw::new("1").into(),
1337 ));
1338 }
1339
1340 if chat.typ == Chattype::Group {
1341 if !chat.grpid.is_empty() {
1343 headers.push((
1344 "Chat-Group-ID",
1345 mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1346 ));
1347 }
1348 }
1349
1350 if chat.typ == Chattype::Group
1351 || chat.typ == Chattype::OutBroadcast
1352 || chat.typ == Chattype::InBroadcast
1353 {
1354 headers.push((
1355 "Chat-Group-Name",
1356 mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1357 ));
1358 if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1359 headers.push((
1360 "Chat-Group-Name-Timestamp",
1361 mail_builder::headers::text::Text::new(ts.to_string()).into(),
1362 ));
1363 }
1364
1365 match command {
1366 SystemMessage::MemberRemovedFromGroup => {
1367 ensure!(chat.typ != Chattype::OutBroadcast);
1368 let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1369
1370 if email_to_remove
1371 == context
1372 .get_config(Config::ConfiguredAddr)
1373 .await?
1374 .unwrap_or_default()
1375 {
1376 placeholdertext = Some(stock_str::msg_group_left_remote(context).await);
1377 } else {
1378 placeholdertext =
1379 Some(stock_str::msg_del_member_remote(context, email_to_remove).await);
1380 };
1381
1382 if !email_to_remove.is_empty() {
1383 headers.push((
1384 "Chat-Group-Member-Removed",
1385 mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1386 .into(),
1387 ));
1388 }
1389 }
1390 SystemMessage::MemberAddedToGroup => {
1391 ensure!(chat.typ != Chattype::OutBroadcast);
1392 let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1395 placeholdertext =
1396 Some(stock_str::msg_add_member_remote(context, email_to_add).await);
1397
1398 if !email_to_add.is_empty() {
1399 headers.push((
1400 "Chat-Group-Member-Added",
1401 mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1402 ));
1403 }
1404 if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1405 info!(
1406 context,
1407 "Sending secure-join message {:?}.", "vg-member-added",
1408 );
1409 headers.push((
1410 "Secure-Join",
1411 mail_builder::headers::raw::Raw::new("vg-member-added".to_string())
1412 .into(),
1413 ));
1414 }
1415 }
1416 SystemMessage::GroupNameChanged => {
1417 let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1418 headers.push((
1419 "Chat-Group-Name-Changed",
1420 mail_builder::headers::text::Text::new(old_name).into(),
1421 ));
1422 }
1423 SystemMessage::GroupImageChanged => {
1424 headers.push((
1425 "Chat-Content",
1426 mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1427 ));
1428 if grpimage.is_none() {
1429 headers.push((
1430 "Chat-Group-Avatar",
1431 mail_builder::headers::raw::Raw::new("0").into(),
1432 ));
1433 }
1434 }
1435 _ => {}
1436 }
1437 }
1438
1439 match command {
1440 SystemMessage::LocationStreamingEnabled => {
1441 headers.push((
1442 "Chat-Content",
1443 mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1444 ));
1445 }
1446 SystemMessage::EphemeralTimerChanged => {
1447 headers.push((
1448 "Chat-Content",
1449 mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1450 ));
1451 }
1452 SystemMessage::LocationOnly
1453 | SystemMessage::MultiDeviceSync
1454 | SystemMessage::WebxdcStatusUpdate => {
1455 headers.push((
1464 "Auto-Submitted",
1465 mail_builder::headers::raw::Raw::new("auto-generated").into(),
1466 ));
1467 }
1468 SystemMessage::AutocryptSetupMessage => {
1469 headers.push((
1470 "Autocrypt-Setup-Message",
1471 mail_builder::headers::raw::Raw::new("v1").into(),
1472 ));
1473
1474 placeholdertext = Some(ASM_SUBJECT.to_string());
1475 }
1476 SystemMessage::SecurejoinMessage => {
1477 let step = msg.param.get(Param::Arg).unwrap_or_default();
1478 if !step.is_empty() {
1479 info!(context, "Sending secure-join message {step:?}.");
1480 headers.push((
1481 "Secure-Join",
1482 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1483 ));
1484
1485 let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1486 if !param2.is_empty() {
1487 headers.push((
1488 if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1489 "Secure-Join-Auth"
1490 } else {
1491 "Secure-Join-Invitenumber"
1492 },
1493 mail_builder::headers::text::Text::new(param2.to_string()).into(),
1494 ));
1495 }
1496
1497 let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1498 if !fingerprint.is_empty() {
1499 headers.push((
1500 "Secure-Join-Fingerprint",
1501 mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1502 ));
1503 }
1504 if let Some(id) = msg.param.get(Param::Arg4) {
1505 headers.push((
1506 "Secure-Join-Group",
1507 mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1508 ));
1509 };
1510 }
1511 }
1512 SystemMessage::ChatProtectionEnabled => {
1513 headers.push((
1514 "Chat-Content",
1515 mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1516 ));
1517 }
1518 SystemMessage::ChatProtectionDisabled => {
1519 headers.push((
1520 "Chat-Content",
1521 mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1522 ));
1523 }
1524 SystemMessage::IrohNodeAddr => {
1525 headers.push((
1526 HeaderDef::IrohNodeAddr.into(),
1527 mail_builder::headers::text::Text::new(serde_json::to_string(
1528 &context
1529 .get_or_try_init_peer_channel()
1530 .await?
1531 .get_node_addr()
1532 .await?,
1533 )?)
1534 .into(),
1535 ));
1536 }
1537 SystemMessage::CallAccepted => {
1538 headers.push((
1539 "Chat-Content",
1540 mail_builder::headers::raw::Raw::new("call-accepted").into(),
1541 ));
1542 }
1543 SystemMessage::CallEnded => {
1544 headers.push((
1545 "Chat-Content",
1546 mail_builder::headers::raw::Raw::new("call-ended").into(),
1547 ));
1548 }
1549 _ => {}
1550 }
1551
1552 if let Some(grpimage) = grpimage {
1553 info!(context, "setting group image '{}'", grpimage);
1554 let avatar = build_avatar_file(context, grpimage)
1555 .await
1556 .context("Cannot attach group image")?;
1557 headers.push((
1558 "Chat-Group-Avatar",
1559 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1560 ));
1561 }
1562
1563 if msg.viewtype == Viewtype::Sticker {
1564 headers.push((
1565 "Chat-Content",
1566 mail_builder::headers::raw::Raw::new("sticker").into(),
1567 ));
1568 } else if msg.viewtype == Viewtype::VideochatInvitation {
1569 headers.push((
1570 "Chat-Content",
1571 mail_builder::headers::raw::Raw::new("videochat-invitation").into(),
1572 ));
1573 } else if msg.viewtype == Viewtype::Call {
1574 headers.push((
1575 "Chat-Content",
1576 mail_builder::headers::raw::Raw::new("call").into(),
1577 ));
1578 placeholdertext = Some(
1579 "[This is a 'Call'. The sender uses an experiment not supported on your version yet]".to_string(),
1580 );
1581 }
1582
1583 if let Some(offer) = msg.param.get(Param::WebrtcRoom) {
1584 headers.push((
1585 "Chat-Webrtc-Room",
1586 mail_builder::headers::raw::Raw::new(b_encode(offer)).into(),
1587 ));
1588 } else if let Some(answer) = msg.param.get(Param::WebrtcAccepted) {
1589 headers.push((
1590 "Chat-Webrtc-Accepted",
1591 mail_builder::headers::raw::Raw::new(b_encode(answer)).into(),
1592 ));
1593 }
1594
1595 if msg.viewtype == Viewtype::Voice
1596 || msg.viewtype == Viewtype::Audio
1597 || msg.viewtype == Viewtype::Video
1598 {
1599 if msg.viewtype == Viewtype::Voice {
1600 headers.push((
1601 "Chat-Voice-Message",
1602 mail_builder::headers::raw::Raw::new("1").into(),
1603 ));
1604 }
1605 let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1606 if duration_ms > 0 {
1607 let dur = duration_ms.to_string();
1608 headers.push((
1609 "Chat-Duration",
1610 mail_builder::headers::raw::Raw::new(dur).into(),
1611 ));
1612 }
1613 }
1614
1615 let afwd_email = msg.param.exists(Param::Forwarded);
1621 let fwdhint = if afwd_email {
1622 Some(
1623 "---------- Forwarded message ----------\r\n\
1624 From: Delta Chat\r\n\
1625 \r\n"
1626 .to_string(),
1627 )
1628 } else {
1629 None
1630 };
1631
1632 let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1633
1634 let mut quoted_text = None;
1635 if let Some(msg_quoted_text) = msg.quoted_text() {
1636 let mut some_quoted_text = String::new();
1637 for quoted_line in msg_quoted_text.split('\n') {
1638 some_quoted_text += "> ";
1639 some_quoted_text += quoted_line;
1640 some_quoted_text += "\r\n";
1641 }
1642 some_quoted_text += "\r\n";
1643 quoted_text = Some(some_quoted_text)
1644 }
1645
1646 if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1647 quoted_text = Some("> ...\r\n\r\n".to_string());
1649 }
1650 if quoted_text.is_none() && final_text.starts_with('>') {
1651 quoted_text = Some("\r\n".to_string());
1654 }
1655
1656 let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1657
1658 let footer = if is_reaction { "" } else { &self.selfstatus };
1659
1660 let message_text = format!(
1661 "{}{}{}{}{}{}",
1662 fwdhint.unwrap_or_default(),
1663 quoted_text.unwrap_or_default(),
1664 escape_message_footer_marks(final_text),
1665 if !final_text.is_empty() && !footer.is_empty() {
1666 "\r\n\r\n"
1667 } else {
1668 ""
1669 },
1670 if !footer.is_empty() { "-- \r\n" } else { "" },
1671 footer
1672 );
1673
1674 let mut main_part = MimePart::new("text/plain", message_text);
1675 if is_reaction {
1676 main_part = main_part.header(
1677 "Content-Disposition",
1678 mail_builder::headers::raw::Raw::new("reaction"),
1679 );
1680 }
1681
1682 let mut parts = Vec::new();
1683
1684 if msg.has_html() {
1687 let html = if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded) {
1688 MsgId::new(orig_msg_id.try_into()?)
1689 .get_html(context)
1690 .await?
1691 } else {
1692 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1693 };
1694 if let Some(html) = html {
1695 main_part = MimePart::new(
1696 "multipart/alternative",
1697 vec![main_part, MimePart::new("text/html", html)],
1698 )
1699 }
1700 }
1701
1702 if msg.viewtype.has_file() {
1704 let file_part = build_body_file(context, &msg).await?;
1705 parts.push(file_part);
1706 }
1707
1708 if let Some(msg_kml_part) = self.get_message_kml_part() {
1709 parts.push(msg_kml_part);
1710 }
1711
1712 if location::is_sending_locations_to_chat(context, Some(msg.chat_id)).await? {
1713 if let Some(part) = self.get_location_kml_part(context).await? {
1714 parts.push(part);
1715 }
1716 }
1717
1718 if command == SystemMessage::MultiDeviceSync {
1721 let json = msg.param.get(Param::Arg).unwrap_or_default();
1722 let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1723 parts.push(context.build_sync_part(json.to_string()));
1724 self.sync_ids_to_delete = Some(ids.to_string());
1725 } else if command == SystemMessage::WebxdcStatusUpdate {
1726 let json = msg.param.get(Param::Arg).unwrap_or_default();
1727 parts.push(context.build_status_update_part(json));
1728 } else if msg.viewtype == Viewtype::Webxdc {
1729 let topic = self
1730 .webxdc_topic
1731 .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1732 .unwrap_or(create_iroh_header(context, msg.id).await?);
1733 headers.push((
1734 HeaderDef::IrohGossipTopic.get_headername(),
1735 mail_builder::headers::raw::Raw::new(topic).into(),
1736 ));
1737 if let (Some(json), _) = context
1738 .render_webxdc_status_update_object(
1739 msg.id,
1740 StatusUpdateSerial::MIN,
1741 StatusUpdateSerial::MAX,
1742 None,
1743 )
1744 .await?
1745 {
1746 parts.push(context.build_status_update_part(&json));
1747 }
1748 }
1749
1750 if self.attach_selfavatar {
1751 match context.get_config(Config::Selfavatar).await? {
1752 Some(path) => match build_avatar_file(context, &path).await {
1753 Ok(avatar) => headers.push((
1754 "Chat-User-Avatar",
1755 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1756 )),
1757 Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1758 },
1759 None => headers.push((
1760 "Chat-User-Avatar",
1761 mail_builder::headers::raw::Raw::new("0").into(),
1762 )),
1763 }
1764 }
1765
1766 Ok((main_part, parts))
1767 }
1768
1769 fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1771 let Loaded::Mdn {
1774 rfc724_mid,
1775 additional_msg_ids,
1776 } = &self.loaded
1777 else {
1778 bail!("Attempt to render a message as MDN");
1779 };
1780
1781 let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1785
1786 let mut message = MimePart::new(
1787 "multipart/report; report-type=disposition-notification",
1788 vec![text_part],
1789 );
1790
1791 let message_text2 = format!(
1793 "Original-Recipient: rfc822;{}\r\n\
1794 Final-Recipient: rfc822;{}\r\n\
1795 Original-Message-ID: <{}>\r\n\
1796 Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1797 self.from_addr, self.from_addr, rfc724_mid
1798 );
1799
1800 let extension_fields = if additional_msg_ids.is_empty() {
1801 "".to_string()
1802 } else {
1803 "Additional-Message-IDs: ".to_string()
1804 + &additional_msg_ids
1805 .iter()
1806 .map(|mid| render_rfc724_mid(mid))
1807 .collect::<Vec<String>>()
1808 .join(" ")
1809 + "\r\n"
1810 };
1811
1812 message.add_part(MimePart::new(
1813 "message/disposition-notification",
1814 message_text2 + &extension_fields,
1815 ));
1816
1817 Ok(message)
1818 }
1819}
1820
1821fn hidden_recipients() -> Address<'static> {
1822 Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
1823}
1824
1825async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
1826 let file_name = msg.get_filename().context("msg has no file")?;
1827 let blob = msg
1828 .param
1829 .get_file_blob(context)?
1830 .context("msg has no file")?;
1831 let mimetype = msg
1832 .param
1833 .get(Param::MimeType)
1834 .unwrap_or("application/octet-stream")
1835 .to_string();
1836 let body = fs::read(blob.to_abs_path()).await?;
1837
1838 let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
1844
1845 Ok(mail)
1846}
1847
1848async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
1849 let blob = match path.starts_with("$BLOBDIR/") {
1850 true => BlobObject::from_name(context, path)?,
1851 false => BlobObject::from_path(context, path.as_ref())?,
1852 };
1853 let body = fs::read(blob.to_abs_path()).await?;
1854 let encoded_body = base64::engine::general_purpose::STANDARD
1855 .encode(&body)
1856 .chars()
1857 .enumerate()
1858 .fold(String::new(), |mut res, (i, c)| {
1859 if i % 78 == 77 {
1860 res.push(' ')
1861 }
1862 res.push(c);
1863 res
1864 });
1865 Ok(encoded_body)
1866}
1867
1868fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
1869 let addr_lc = addr.to_lowercase();
1870 recipients
1871 .iter()
1872 .any(|(_, cur)| cur.to_lowercase() == addr_lc)
1873}
1874
1875fn render_rfc724_mid(rfc724_mid: &str) -> String {
1876 let rfc724_mid = rfc724_mid.trim().to_string();
1877
1878 if rfc724_mid.chars().next().unwrap_or_default() == '<' {
1879 rfc724_mid
1880 } else {
1881 format!("<{rfc724_mid}>")
1882 }
1883}
1884
1885fn b_encode(value: &str) -> String {
1891 format!(
1892 "=?utf-8?B?{}?=",
1893 base64::engine::general_purpose::STANDARD.encode(value)
1894 )
1895}
1896
1897#[cfg(test)]
1898mod mimefactory_tests;