1use 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::pgp::SeipdVersion;
36use crate::simplify::escape_message_footer_marks;
37use crate::stock_str;
38use crate::tools::{
39 IsNoneOrEmpty, create_outgoing_rfc724_mid, create_smeared_timestamp, remove_subject_prefix,
40 time,
41};
42use crate::webxdc::StatusUpdateSerial;
43
44pub const RECOMMENDED_FILE_SIZE: u64 = 24 * 1024 * 1024 / 4 * 3;
48
49#[derive(Debug, Clone)]
50#[expect(clippy::large_enum_variant)]
51pub enum Loaded {
52 Message {
53 chat: Chat,
54 msg: Message,
55 },
56 Mdn {
57 rfc724_mid: String,
58 additional_msg_ids: Vec<String>,
59 },
60}
61
62#[derive(Debug, Clone)]
64pub struct MimeFactory {
65 from_addr: String,
66 from_displayname: String,
67
68 sender_displayname: Option<String>,
75
76 selfstatus: String,
77
78 recipients: Vec<String>,
92
93 encryption_pubkeys: Option<Vec<(String, SignedPublicKey)>>,
99
100 to: Vec<(String, String)>,
107
108 past_members: Vec<(String, String)>,
110
111 member_fingerprints: Vec<String>,
117
118 member_timestamps: Vec<i64>,
124
125 timestamp: i64,
126 loaded: Loaded,
127 in_reply_to: String,
128
129 references: Vec<String>,
131
132 req_mdn: bool,
135
136 last_added_location_id: Option<u32>,
137
138 sync_ids_to_delete: Option<String>,
143
144 pub attach_selfavatar: bool,
146
147 webxdc_topic: Option<TopicId>,
149}
150
151#[derive(Debug, Clone)]
153pub struct RenderedEmail {
154 pub message: String,
155 pub is_encrypted: bool,
157 pub last_added_location_id: Option<u32>,
158
159 pub sync_ids_to_delete: Option<String>,
162
163 pub rfc724_mid: String,
165
166 pub subject: String,
168}
169
170fn new_address_with_name(name: &str, address: String) -> Address<'static> {
171 Address::new_address(
172 if name == address || name.is_empty() {
173 None
174 } else {
175 Some(name.to_string())
176 },
177 address,
178 )
179}
180
181impl MimeFactory {
182 pub async fn from_msg(context: &Context, msg: Message) -> Result<MimeFactory> {
183 let now = time();
184 let chat = Chat::load_from_db(context, msg.chat_id).await?;
185 let attach_profile_data = Self::should_attach_profile_data(&msg);
186 let undisclosed_recipients = should_hide_recipients(&msg, &chat);
187
188 let from_addr = context.get_primary_self_addr().await?;
189 let config_displayname = context
190 .get_config(Config::Displayname)
191 .await?
192 .unwrap_or_default();
193 let (from_displayname, sender_displayname) =
194 if let Some(override_name) = msg.param.get(Param::OverrideSenderDisplayname) {
195 (override_name.to_string(), Some(config_displayname))
196 } else {
197 let name = match attach_profile_data {
198 true => config_displayname,
199 false => "".to_string(),
200 };
201 (name, None)
202 };
203
204 let mut recipients = Vec::new();
205 let mut to = Vec::new();
206 let mut past_members = Vec::new();
207 let mut member_fingerprints = Vec::new();
208 let mut member_timestamps = Vec::new();
209 let mut recipient_ids = HashSet::new();
210 let mut req_mdn = false;
211
212 let encryption_pubkeys;
213
214 let self_fingerprint = self_fingerprint(context).await?;
215
216 if chat.is_self_talk() {
217 to.push((from_displayname.to_string(), from_addr.to_string()));
218
219 encryption_pubkeys = if msg.param.get_bool(Param::ForcePlaintext).unwrap_or(false) {
220 None
221 } else {
222 Some(Vec::new())
224 };
225 } else if chat.is_mailing_list() {
226 let list_post = chat
227 .param
228 .get(Param::ListPost)
229 .context("Can't write to mailinglist without ListPost param")?;
230 to.push(("".to_string(), list_post.to_string()));
231 recipients.push(list_post.to_string());
232
233 encryption_pubkeys = None;
235 } else {
236 let email_to_remove = if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
237 msg.param.get(Param::Arg)
238 } else {
239 None
240 };
241
242 let is_encrypted = if msg
243 .param
244 .get_bool(Param::ForcePlaintext)
245 .unwrap_or_default()
246 {
247 false
248 } else {
249 msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
250 || chat.is_encrypted(context).await?
251 };
252
253 let mut keys = Vec::new();
254 let mut missing_key_addresses = BTreeSet::new();
255 context
256 .sql
257 .query_map(
262 "SELECT
263 c.authname,
264 c.addr,
265 c.fingerprint,
266 c.id,
267 cc.add_timestamp,
268 cc.remove_timestamp,
269 k.public_key
270 FROM chats_contacts cc
271 LEFT JOIN contacts c ON cc.contact_id=c.id
272 LEFT JOIN public_keys k ON k.fingerprint=c.fingerprint
273 WHERE cc.chat_id=?
274 AND (cc.contact_id>9 OR (cc.contact_id=1 AND ?))
275 ORDER BY cc.add_timestamp DESC",
276 (msg.chat_id, chat.typ == Chattype::Group),
277 |row| {
278 let authname: String = row.get(0)?;
279 let addr: String = row.get(1)?;
280 let fingerprint: String = row.get(2)?;
281 let id: ContactId = row.get(3)?;
282 let add_timestamp: i64 = row.get(4)?;
283 let remove_timestamp: i64 = row.get(5)?;
284 let public_key_bytes_opt: Option<Vec<u8>> = row.get(6)?;
285 Ok((authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt))
286 },
287 |rows| {
288 let mut past_member_timestamps = Vec::new();
289 let mut past_member_fingerprints = Vec::new();
290
291 for row in rows {
292 let (authname, addr, fingerprint, id, add_timestamp, remove_timestamp, public_key_bytes_opt) = row?;
293
294 if let Some(fp) = must_have_only_one_recipient(&msg, &chat)
297 && fp? != fingerprint {
298 continue;
299 }
300
301 let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
302 Some(SignedPublicKey::from_slice(public_key_bytes)?)
303 } else {
304 None
305 };
306
307 let addr = if id == ContactId::SELF {
308 from_addr.to_string()
309 } else {
310 addr
311 };
312 let name = match attach_profile_data {
313 true => authname,
314 false => "".to_string(),
315 };
316 if add_timestamp >= remove_timestamp {
317 if !recipients_contain_addr(&to, &addr) {
318 if id != ContactId::SELF {
319 recipients.push(addr.clone());
320 }
321 if !undisclosed_recipients {
322 to.push((name, addr.clone()));
323
324 if is_encrypted {
325 if !fingerprint.is_empty() {
326 member_fingerprints.push(fingerprint);
327 } else if id == ContactId::SELF {
328 member_fingerprints.push(self_fingerprint.to_string());
329 } else {
330 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");
331 }
332 }
333 member_timestamps.push(add_timestamp);
334 }
335 }
336 recipient_ids.insert(id);
337
338 if let Some(public_key) = public_key_opt {
339 keys.push((addr.clone(), public_key))
340 } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
341 missing_key_addresses.insert(addr.clone());
342 if is_encrypted {
343 warn!(context, "Missing key for {addr}");
344 }
345 }
346 } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
347 if !recipients_contain_addr(&past_members, &addr) {
350 if let Some(email_to_remove) = email_to_remove
351 && email_to_remove == addr {
352 if id != ContactId::SELF {
356 recipients.push(addr.clone());
357 }
358
359 if let Some(public_key) = public_key_opt {
360 keys.push((addr.clone(), public_key))
361 } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
362 missing_key_addresses.insert(addr.clone());
363 if is_encrypted {
364 warn!(context, "Missing key for {addr}");
365 }
366 }
367 }
368 if !undisclosed_recipients {
369 past_members.push((name, addr.clone()));
370 past_member_timestamps.push(remove_timestamp);
371
372 if is_encrypted {
373 if !fingerprint.is_empty() {
374 past_member_fingerprints.push(fingerprint);
375 } else if id == ContactId::SELF {
376 past_member_fingerprints.push(self_fingerprint.to_string());
379 } else {
380 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");
381 }
382 }
383 }
384 }
385 }
386 }
387
388 ensure_and_debug_assert!(
389 member_timestamps.len() >= to.len(),
390 "member_timestamps.len() ({}) < to.len() ({})",
391 member_timestamps.len(), to.len());
392 ensure_and_debug_assert!(
393 member_fingerprints.is_empty() || member_fingerprints.len() >= to.len(),
394 "member_fingerprints.len() ({}) < to.len() ({})",
395 member_fingerprints.len(), to.len());
396
397 if to.len() > 1
398 && let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
399 to.remove(position);
400 member_timestamps.remove(position);
401 if is_encrypted {
402 member_fingerprints.remove(position);
403 }
404 }
405
406 member_timestamps.extend(past_member_timestamps);
407 if is_encrypted {
408 member_fingerprints.extend(past_member_fingerprints);
409 }
410 Ok(())
411 },
412 )
413 .await?;
414 let recipient_ids: Vec<_> = recipient_ids.into_iter().collect();
415 ContactId::scaleup_origin(context, &recipient_ids, Origin::OutgoingTo).await?;
416
417 if !msg.is_system_message()
418 && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
419 && context.should_request_mdns().await?
420 {
421 req_mdn = true;
422 }
423
424 encryption_pubkeys = if !is_encrypted {
425 None
426 } else if should_encrypt_symmetrically(&msg, &chat) {
427 Some(Vec::new())
428 } else {
429 if keys.is_empty() && !recipients.is_empty() {
430 bail!("No recipient keys are available, cannot encrypt to {recipients:?}.");
431 }
432
433 if !missing_key_addresses.is_empty() {
435 recipients.retain(|addr| !missing_key_addresses.contains(addr));
436 }
437
438 Some(keys)
439 };
440 }
441
442 let (in_reply_to, references) = context
443 .sql
444 .query_row(
445 "SELECT mime_in_reply_to, IFNULL(mime_references, '')
446 FROM msgs WHERE id=?",
447 (msg.id,),
448 |row| {
449 let in_reply_to: String = row.get(0)?;
450 let references: String = row.get(1)?;
451
452 Ok((in_reply_to, references))
453 },
454 )
455 .await?;
456 let references: Vec<String> = references
457 .trim()
458 .split_ascii_whitespace()
459 .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
460 .collect();
461 let selfstatus = match attach_profile_data {
462 true => context
463 .get_config(Config::Selfstatus)
464 .await?
465 .unwrap_or_default(),
466 false => "".to_string(),
467 };
468 let attach_selfavatar =
472 Self::should_attach_selfavatar(context, &msg).await && encryption_pubkeys.is_some();
473
474 ensure_and_debug_assert!(
475 member_timestamps.is_empty()
476 || to.len() + past_members.len() == member_timestamps.len(),
477 "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
478 to.len(),
479 past_members.len(),
480 member_timestamps.len(),
481 );
482 let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
483 let factory = MimeFactory {
484 from_addr,
485 from_displayname,
486 sender_displayname,
487 selfstatus,
488 recipients,
489 encryption_pubkeys,
490 to,
491 past_members,
492 member_fingerprints,
493 member_timestamps,
494 timestamp: msg.timestamp_sort,
495 loaded: Loaded::Message { msg, chat },
496 in_reply_to,
497 references,
498 req_mdn,
499 last_added_location_id: None,
500 sync_ids_to_delete: None,
501 attach_selfavatar,
502 webxdc_topic,
503 };
504 Ok(factory)
505 }
506
507 pub async fn from_mdn(
508 context: &Context,
509 from_id: ContactId,
510 rfc724_mid: String,
511 additional_msg_ids: Vec<String>,
512 ) -> Result<MimeFactory> {
513 let contact = Contact::get_by_id(context, from_id).await?;
514 let from_addr = context.get_primary_self_addr().await?;
515 let timestamp = create_smeared_timestamp(context);
516
517 let addr = contact.get_addr().to_string();
518 let encryption_pubkeys = if contact.is_key_contact() {
519 if let Some(key) = contact.public_key(context).await? {
520 Some(vec![(addr.clone(), key)])
521 } else {
522 Some(Vec::new())
523 }
524 } else {
525 None
526 };
527
528 let res = MimeFactory {
529 from_addr,
530 from_displayname: "".to_string(),
531 sender_displayname: None,
532 selfstatus: "".to_string(),
533 recipients: vec![addr],
534 encryption_pubkeys,
535 to: vec![("".to_string(), contact.get_addr().to_string())],
536 past_members: vec![],
537 member_fingerprints: vec![],
538 member_timestamps: vec![],
539 timestamp,
540 loaded: Loaded::Mdn {
541 rfc724_mid,
542 additional_msg_ids,
543 },
544 in_reply_to: String::default(),
545 references: Vec::new(),
546 req_mdn: false,
547 last_added_location_id: None,
548 sync_ids_to_delete: None,
549 attach_selfavatar: false,
550 webxdc_topic: None,
551 };
552
553 Ok(res)
554 }
555
556 fn should_skip_autocrypt(&self) -> bool {
557 match &self.loaded {
558 Loaded::Message { msg, .. } => {
559 msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
560 }
561 Loaded::Mdn { .. } => true,
562 }
563 }
564
565 fn should_attach_profile_data(msg: &Message) -> bool {
566 msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
567 let step = msg.param.get(Param::Arg).unwrap_or_default();
568 step == "vg-request-with-auth"
574 || step == "vc-request-with-auth"
575 || step == "vg-member-added"
580 || step == "vc-contact-confirm"
581 }
582 }
583
584 async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
585 Self::should_attach_profile_data(msg)
586 && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
587 Ok(should) => should,
588 Err(err) => {
589 warn!(
590 context,
591 "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
592 );
593 false
594 }
595 }
596 }
597
598 fn grpimage(&self) -> Option<String> {
599 match &self.loaded {
600 Loaded::Message { chat, msg } => {
601 let cmd = msg.param.get_cmd();
602
603 match cmd {
604 SystemMessage::MemberAddedToGroup => {
605 return chat.param.get(Param::ProfileImage).map(Into::into);
606 }
607 SystemMessage::GroupImageChanged => {
608 return msg.param.get(Param::Arg).map(Into::into);
609 }
610 _ => {}
611 }
612
613 if msg
614 .param
615 .get_bool(Param::AttachGroupImage)
616 .unwrap_or_default()
617 {
618 return chat.param.get(Param::ProfileImage).map(Into::into);
619 }
620
621 None
622 }
623 Loaded::Mdn { .. } => None,
624 }
625 }
626
627 async fn subject_str(&self, context: &Context) -> Result<String> {
628 let subject = match &self.loaded {
629 Loaded::Message { chat, msg } => {
630 let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
631
632 if !msg.subject.is_empty() {
633 return Ok(msg.subject.clone());
634 }
635
636 if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
637 && quoted_msg_subject.is_none_or_empty()
638 {
639 let re = if self.in_reply_to.is_empty() {
640 ""
641 } else {
642 "Re: "
643 };
644 return Ok(format!("{}{}", re, chat.name));
645 }
646
647 let parent_subject = if quoted_msg_subject.is_none_or_empty() {
648 chat.param.get(Param::LastSubject)
649 } else {
650 quoted_msg_subject.as_deref()
651 };
652 if let Some(last_subject) = parent_subject {
653 return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
654 }
655
656 let self_name = match Self::should_attach_profile_data(msg) {
657 true => context.get_config(Config::Displayname).await?,
658 false => None,
659 };
660 let self_name = &match self_name {
661 Some(name) => name,
662 None => context.get_config(Config::Addr).await?.unwrap_or_default(),
663 };
664 stock_str::subject_for_new_contact(context, self_name).await
665 }
666 Loaded::Mdn { .. } => "Receipt Notification".to_string(), };
668
669 Ok(subject)
670 }
671
672 pub fn recipients(&self) -> Vec<String> {
673 self.recipients.clone()
674 }
675
676 pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
679 let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
680
681 let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
682
683 let mut to: Vec<Address<'static>> = Vec::new();
684 for (name, addr) in &self.to {
685 to.push(Address::new_address(
686 if name.is_empty() {
687 None
688 } else {
689 Some(name.to_string())
690 },
691 addr.clone(),
692 ));
693 }
694
695 let mut past_members: Vec<Address<'static>> = Vec::new(); for (name, addr) in &self.past_members {
697 past_members.push(Address::new_address(
698 if name.is_empty() {
699 None
700 } else {
701 Some(name.to_string())
702 },
703 addr.clone(),
704 ));
705 }
706
707 ensure_and_debug_assert!(
708 self.member_timestamps.is_empty()
709 || to.len() + past_members.len() == self.member_timestamps.len(),
710 "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
711 to.len(),
712 past_members.len(),
713 self.member_timestamps.len(),
714 );
715 if to.is_empty() {
716 to.push(hidden_recipients());
717 }
718
719 headers.push(("From", from.into()));
722
723 if let Some(sender_displayname) = &self.sender_displayname {
724 let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
725 headers.push(("Sender", sender.into()));
726 }
727 headers.push((
728 "To",
729 mail_builder::headers::address::Address::new_list(to.clone()).into(),
730 ));
731 if !past_members.is_empty() {
732 headers.push((
733 "Chat-Group-Past-Members",
734 mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
735 ));
736 }
737
738 if let Loaded::Message { chat, .. } = &self.loaded
739 && chat.typ == Chattype::Group
740 {
741 if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await? {
742 headers.push((
743 "Chat-Group-Member-Timestamps",
744 mail_builder::headers::raw::Raw::new(
745 self.member_timestamps
746 .iter()
747 .map(|ts| ts.to_string())
748 .collect::<Vec<String>>()
749 .join(" "),
750 )
751 .into(),
752 ));
753 }
754
755 if !self.member_fingerprints.is_empty() {
756 headers.push((
757 "Chat-Group-Member-Fpr",
758 mail_builder::headers::raw::Raw::new(
759 self.member_fingerprints
760 .iter()
761 .map(|fp| fp.to_string())
762 .collect::<Vec<String>>()
763 .join(" "),
764 )
765 .into(),
766 ));
767 }
768 }
769
770 let subject_str = self.subject_str(context).await?;
771 headers.push((
772 "Subject",
773 mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
774 ));
775
776 let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
777 .unwrap()
778 .to_rfc2822();
779 headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
780
781 let rfc724_mid = match &self.loaded {
782 Loaded::Message { msg, .. } => msg.rfc724_mid.clone(),
783 Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
784 };
785 headers.push((
786 "Message-ID",
787 mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
788 ));
789
790 if !self.in_reply_to.is_empty() {
792 headers.push((
793 "In-Reply-To",
794 mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
795 ));
796 }
797 if !self.references.is_empty() {
798 headers.push((
799 "References",
800 mail_builder::headers::message_id::MessageId::<'static>::new_list(
801 self.references.iter().map(|s| s.to_string()),
802 )
803 .into(),
804 ));
805 }
806
807 if let Loaded::Mdn { .. } = self.loaded {
809 headers.push((
810 "Auto-Submitted",
811 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
812 ));
813 } else if context.get_config_bool(Config::Bot).await? {
814 headers.push((
815 "Auto-Submitted",
816 mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
817 ));
818 } else if let Loaded::Message { msg, .. } = &self.loaded
819 && msg.param.get_cmd() == SystemMessage::SecurejoinMessage
820 {
821 let step = msg.param.get(Param::Arg).unwrap_or_default();
822 if step != "vg-request" && step != "vc-request" {
823 headers.push((
824 "Auto-Submitted",
825 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
826 ));
827 }
828 }
829
830 if let Loaded::Message { msg, chat } = &self.loaded
831 && (chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast)
832 {
833 headers.push((
834 "Chat-List-ID",
835 mail_builder::headers::text::Text::new(format!("{} <{}>", chat.name, chat.grpid))
836 .into(),
837 ));
838
839 if msg.param.get_cmd() == SystemMessage::MemberAddedToGroup
840 && let Some(secret) = msg.param.get(PARAM_BROADCAST_SECRET)
841 {
842 headers.push((
843 "Chat-Broadcast-Secret",
844 mail_builder::headers::text::Text::new(secret.to_string()).into(),
845 ));
846 }
847 }
848
849 if let Loaded::Message { msg, .. } = &self.loaded {
850 if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
851 headers.push((
852 "Chat-Edit",
853 mail_builder::headers::message_id::MessageId::new(
854 original_rfc724_mid.to_string(),
855 )
856 .into(),
857 ));
858 } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
859 headers.push((
860 "Chat-Delete",
861 mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
862 .into(),
863 ));
864 }
865 }
866
867 headers.push((
869 "Chat-Version",
870 mail_builder::headers::raw::Raw::new("1.0").into(),
871 ));
872
873 if self.req_mdn {
874 headers.push((
878 "Chat-Disposition-Notification-To",
879 mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
880 ));
881 }
882
883 let grpimage = self.grpimage();
884 let skip_autocrypt = self.should_skip_autocrypt();
885 let encrypt_helper = EncryptHelper::new(context).await?;
886
887 if !skip_autocrypt {
888 let aheader = encrypt_helper.get_aheader().to_string();
890 headers.push((
891 "Autocrypt",
892 mail_builder::headers::raw::Raw::new(aheader).into(),
893 ));
894 }
895
896 let is_encrypted = self.encryption_pubkeys.is_some();
897
898 if let Loaded::Message { msg, .. } = &self.loaded {
902 let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
903 if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
904 headers.push((
905 "Ephemeral-Timer",
906 mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
907 ));
908 }
909 }
910
911 let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
912 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
913 } else {
914 false
915 };
916
917 let message: MimePart<'static> = match &self.loaded {
918 Loaded::Message { msg, .. } => {
919 let msg = msg.clone();
920 let (main_part, mut parts) = self
921 .render_message(context, &mut headers, &grpimage, is_encrypted)
922 .await?;
923 if parts.is_empty() {
924 main_part
926 } else {
927 parts.insert(0, main_part);
928
929 if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
931 MimePart::new("multipart/report; report-type=multi-device-sync", parts)
932 } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
933 MimePart::new("multipart/report; report-type=status-update", parts)
934 } else {
935 MimePart::new("multipart/mixed", parts)
936 }
937 }
938 }
939 Loaded::Mdn { .. } => self.render_mdn()?,
940 };
941
942 let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
951
952 let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
965
966 let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
975
976 unprotected_headers.push((
978 "MIME-Version",
979 mail_builder::headers::raw::Raw::new("1.0").into(),
980 ));
981 for header @ (original_header_name, _header_value) in &headers {
982 let header_name = original_header_name.to_lowercase();
983 if header_name == "message-id" {
984 unprotected_headers.push(header.clone());
985 hidden_headers.push(header.clone());
986 } else if is_hidden(&header_name) {
987 hidden_headers.push(header.clone());
988 } else if header_name == "from" {
989 if is_encrypted || !is_securejoin_message {
991 protected_headers.push(header.clone());
992 }
993
994 unprotected_headers.push((
995 original_header_name,
996 Address::new_address(None::<&'static str>, self.from_addr.clone()).into(),
997 ));
998 } else if header_name == "to" {
999 protected_headers.push(header.clone());
1000 if is_encrypted {
1001 unprotected_headers.push(("To", hidden_recipients().into()));
1002 } else {
1003 unprotected_headers.push(header.clone());
1004 }
1005 } else if header_name == "chat-broadcast-secret" {
1006 if is_encrypted {
1007 protected_headers.push(header.clone());
1008 } else {
1009 bail!("Message is unecrypted, cannot include broadcast secret");
1010 }
1011 } else if is_encrypted && header_name == "date" {
1012 protected_headers.push(header.clone());
1013
1014 let timestamp_offset = rand::random_range(0..518400);
1036 let protected_timestamp = self.timestamp.saturating_sub(timestamp_offset);
1037 let unprotected_date =
1038 chrono::DateTime::<chrono::Utc>::from_timestamp(protected_timestamp, 0)
1039 .unwrap()
1040 .to_rfc2822();
1041 unprotected_headers.push((
1042 "Date",
1043 mail_builder::headers::raw::Raw::new(unprotected_date).into(),
1044 ));
1045 } else if is_encrypted {
1046 protected_headers.push(header.clone());
1047
1048 match header_name.as_str() {
1049 "subject" => {
1050 unprotected_headers.push((
1051 "Subject",
1052 mail_builder::headers::raw::Raw::new("[...]").into(),
1053 ));
1054 }
1055 "in-reply-to"
1056 | "references"
1057 | "auto-submitted"
1058 | "chat-version"
1059 | "autocrypt-setup-message" => {
1060 unprotected_headers.push(header.clone());
1061 }
1062 _ => {
1063 }
1065 }
1066 } else {
1067 protected_headers.push(header.clone());
1071 unprotected_headers.push(header.clone())
1072 }
1073 }
1074
1075 let use_std_header_protection = context
1076 .get_config_bool(Config::StdHeaderProtectionComposing)
1077 .await?;
1078 let outer_message = if let Some(encryption_pubkeys) = self.encryption_pubkeys {
1079 let message = protected_headers
1081 .into_iter()
1082 .fold(message, |message, (header, value)| {
1083 message.header(header, value)
1084 });
1085
1086 let mut message: MimePart<'static> = hidden_headers
1088 .into_iter()
1089 .fold(message, |message, (header, value)| {
1090 message.header(header, value)
1091 });
1092
1093 if use_std_header_protection {
1094 message = unprotected_headers
1095 .iter()
1096 .filter(|(name, _)| {
1099 !(name.eq_ignore_ascii_case("mime-version")
1100 || name.eq_ignore_ascii_case("content-type")
1101 || name.eq_ignore_ascii_case("content-transfer-encoding")
1102 || name.eq_ignore_ascii_case("content-disposition"))
1103 })
1104 .fold(message, |message, (name, value)| {
1105 message.header(format!("HP-Outer: {name}"), value.clone())
1106 });
1107 }
1108
1109 let multiple_recipients =
1111 encryption_pubkeys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1112
1113 let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1114 let now = time();
1115
1116 match &self.loaded {
1117 Loaded::Message { chat, msg } => {
1118 if !should_hide_recipients(msg, chat) {
1119 for (addr, key) in &encryption_pubkeys {
1120 let fingerprint = key.dc_fingerprint().hex();
1121 let cmd = msg.param.get_cmd();
1122 let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1123 || cmd == SystemMessage::SecurejoinMessage
1124 || multiple_recipients && {
1125 let gossiped_timestamp: Option<i64> = context
1126 .sql
1127 .query_get_value(
1128 "SELECT timestamp
1129 FROM gossip_timestamp
1130 WHERE chat_id=? AND fingerprint=?",
1131 (chat.id, &fingerprint),
1132 )
1133 .await?;
1134
1135 gossip_period == 0
1142 || gossiped_timestamp
1143 .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1144 };
1145
1146 let verifier_id: Option<u32> = context
1147 .sql
1148 .query_get_value(
1149 "SELECT verifier FROM contacts WHERE fingerprint=?",
1150 (&fingerprint,),
1151 )
1152 .await?;
1153
1154 let is_verified =
1155 verifier_id.is_some_and(|verifier_id| verifier_id != 0);
1156
1157 if !should_do_gossip {
1158 continue;
1159 }
1160
1161 let header = Aheader {
1162 addr: addr.clone(),
1163 public_key: key.clone(),
1164 prefer_encrypt: EncryptPreference::NoPreference,
1167 verified: is_verified,
1168 }
1169 .to_string();
1170
1171 message = message.header(
1172 "Autocrypt-Gossip",
1173 mail_builder::headers::raw::Raw::new(header),
1174 );
1175
1176 context
1177 .sql
1178 .execute(
1179 "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1180 VALUES (?, ?, ?)
1181 ON CONFLICT (chat_id, fingerprint)
1182 DO UPDATE SET timestamp=excluded.timestamp",
1183 (chat.id, &fingerprint, now),
1184 )
1185 .await?;
1186 }
1187 }
1188 }
1189 Loaded::Mdn { .. } => {
1190 }
1192 }
1193
1194 for (h, v) in &mut message.headers {
1196 if h == "Content-Type"
1197 && let mail_builder::headers::HeaderType::ContentType(ct) = v
1198 {
1199 let mut ct_new = ct.clone();
1200 ct_new = ct_new.attribute("protected-headers", "v1");
1201 if use_std_header_protection {
1202 ct_new = ct_new.attribute("hp", "cipher");
1203 }
1204 *ct = ct_new;
1205 break;
1206 }
1207 }
1208
1209 let compress = match &self.loaded {
1213 Loaded::Message { msg, .. } => {
1214 msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1215 }
1216 Loaded::Mdn { .. } => true,
1217 };
1218
1219 let shared_secret: Option<String> = match &self.loaded {
1220 Loaded::Message { chat, msg }
1221 if should_encrypt_with_broadcast_secret(msg, chat) =>
1222 {
1223 let secret = load_broadcast_secret(context, chat.id).await?;
1224 if secret.is_none() {
1225 let text = BROADCAST_INCOMPATIBILITY_MSG;
1230 chat::add_info_msg(context, chat.id, text).await?;
1231 bail!(text);
1232 }
1233 secret
1234 }
1235 _ => None,
1236 };
1237
1238 let anonymous_recipients = false;
1248
1249 if context.get_config_bool(Config::TestHooks).await?
1250 && let Some(hook) = &*context.pre_encrypt_mime_hook.lock()
1251 {
1252 message = hook(context, message);
1253 }
1254
1255 let encrypted = if let Some(shared_secret) = shared_secret {
1256 encrypt_helper
1257 .encrypt_symmetrically(context, &shared_secret, message, compress)
1258 .await?
1259 } else {
1260 let seipd_version = if encryption_pubkeys.is_empty() {
1263 SeipdVersion::V2
1266 } else {
1267 SeipdVersion::V1
1271 };
1272
1273 let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1276 encryption_keyring
1277 .extend(encryption_pubkeys.iter().map(|(_addr, key)| (*key).clone()));
1278
1279 encrypt_helper
1280 .encrypt(
1281 context,
1282 encryption_keyring,
1283 message,
1284 compress,
1285 anonymous_recipients,
1286 seipd_version,
1287 )
1288 .await?
1289 };
1290
1291 let encrypted = encrypted + "\n";
1295
1296 MimePart::new(
1298 "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1299 vec![
1300 MimePart::new("application/pgp-encrypted", "Version: 1\r\n").header(
1302 "Content-Description",
1303 mail_builder::headers::raw::Raw::new("PGP/MIME version identification"),
1304 ),
1305 MimePart::new(
1307 "application/octet-stream; name=\"encrypted.asc\"",
1308 encrypted,
1309 )
1310 .header(
1311 "Content-Description",
1312 mail_builder::headers::raw::Raw::new("OpenPGP encrypted message"),
1313 )
1314 .header(
1315 "Content-Disposition",
1316 mail_builder::headers::raw::Raw::new("inline; filename=\"encrypted.asc\";"),
1317 ),
1318 ],
1319 )
1320 } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1321 message
1330 } else {
1331 let message = hidden_headers
1332 .into_iter()
1333 .fold(message, |message, (header, value)| {
1334 message.header(header, value)
1335 });
1336 let message = MimePart::new("multipart/mixed", vec![message]);
1337 let mut message = protected_headers
1338 .iter()
1339 .fold(message, |message, (header, value)| {
1340 message.header(*header, value.clone())
1341 });
1342
1343 if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
1344 let protected: HashSet<&str> =
1346 HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1347 unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1348
1349 message
1350 } else {
1351 for (h, v) in &mut message.headers {
1352 if h == "Content-Type"
1353 && let mail_builder::headers::HeaderType::ContentType(ct) = v
1354 {
1355 let mut ct_new = ct.clone();
1356 ct_new = ct_new.attribute("protected-headers", "v1");
1357 if use_std_header_protection {
1358 ct_new = ct_new.attribute("hp", "clear");
1359 }
1360 *ct = ct_new;
1361 break;
1362 }
1363 }
1364
1365 let signature = encrypt_helper.sign(context, &message).await?;
1366 MimePart::new(
1367 "multipart/signed; protocol=\"application/pgp-signature\"; protected",
1368 vec![
1369 message,
1370 MimePart::new(
1371 "application/pgp-signature; name=\"signature.asc\"",
1372 signature,
1373 )
1374 .header(
1375 "Content-Description",
1376 mail_builder::headers::raw::Raw::<'static>::new(
1377 "OpenPGP digital signature",
1378 ),
1379 )
1380 .attachment("signature"),
1381 ],
1382 )
1383 }
1384 };
1385
1386 let outer_message = unprotected_headers
1388 .into_iter()
1389 .fold(outer_message, |message, (header, value)| {
1390 message.header(header, value)
1391 });
1392
1393 let MimeFactory {
1394 last_added_location_id,
1395 ..
1396 } = self;
1397
1398 let mut buffer = Vec::new();
1399 let cursor = Cursor::new(&mut buffer);
1400 outer_message.clone().write_part(cursor).ok();
1401 let message = String::from_utf8_lossy(&buffer).to_string();
1402
1403 Ok(RenderedEmail {
1404 message,
1405 is_encrypted,
1407 last_added_location_id,
1408 sync_ids_to_delete: self.sync_ids_to_delete,
1409 rfc724_mid,
1410 subject: subject_str,
1411 })
1412 }
1413
1414 fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1416 let Loaded::Message { msg, .. } = &self.loaded else {
1417 return None;
1418 };
1419
1420 let latitude = msg.param.get_float(Param::SetLatitude)?;
1421 let longitude = msg.param.get_float(Param::SetLongitude)?;
1422
1423 let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1424 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1425 .attachment("message.kml");
1426 Some(part)
1427 }
1428
1429 async fn get_location_kml_part(
1431 &mut self,
1432 context: &Context,
1433 ) -> Result<Option<MimePart<'static>>> {
1434 let Loaded::Message { msg, .. } = &self.loaded else {
1435 return Ok(None);
1436 };
1437
1438 let Some((kml_content, last_added_location_id)) =
1439 location::get_kml(context, msg.chat_id).await?
1440 else {
1441 return Ok(None);
1442 };
1443
1444 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1445 .attachment("location.kml");
1446 if !msg.param.exists(Param::SetLatitude) {
1447 self.last_added_location_id = Some(last_added_location_id);
1449 }
1450 Ok(Some(part))
1451 }
1452
1453 async fn render_message(
1454 &mut self,
1455 context: &Context,
1456 headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1457 grpimage: &Option<String>,
1458 is_encrypted: bool,
1459 ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1460 let Loaded::Message { chat, msg } = &self.loaded else {
1461 bail!("Attempt to render MDN as a message");
1462 };
1463 let chat = chat.clone();
1464 let msg = msg.clone();
1465 let command = msg.param.get_cmd();
1466 let mut placeholdertext = None;
1467
1468 let send_verified_headers = match chat.typ {
1469 Chattype::Single => true,
1470 Chattype::Group => true,
1471 Chattype::Mailinglist => false,
1473 Chattype::OutBroadcast | Chattype::InBroadcast => false,
1474 };
1475
1476 if send_verified_headers {
1477 let was_protected: bool = context
1478 .sql
1479 .query_get_value("SELECT protected FROM chats WHERE id=?", (chat.id,))
1480 .await?
1481 .unwrap_or_default();
1482
1483 if was_protected {
1484 let unverified_member_exists = context
1485 .sql
1486 .exists(
1487 "SELECT COUNT(*)
1488 FROM contacts, chats_contacts
1489 WHERE chats_contacts.contact_id=contacts.id AND chats_contacts.chat_id=?
1490 AND contacts.id>9
1491 AND contacts.verifier=0",
1492 (chat.id,),
1493 )
1494 .await?;
1495
1496 if !unverified_member_exists {
1497 headers.push((
1498 "Chat-Verified",
1499 mail_builder::headers::raw::Raw::new("1").into(),
1500 ));
1501 }
1502 }
1503 }
1504
1505 if chat.typ == Chattype::Group {
1506 if !chat.grpid.is_empty() {
1508 headers.push((
1509 "Chat-Group-ID",
1510 mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1511 ));
1512 }
1513 }
1514
1515 if chat.typ == Chattype::Group
1516 || chat.typ == Chattype::OutBroadcast
1517 || chat.typ == Chattype::InBroadcast
1518 {
1519 headers.push((
1520 "Chat-Group-Name",
1521 mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1522 ));
1523 if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1524 headers.push((
1525 "Chat-Group-Name-Timestamp",
1526 mail_builder::headers::text::Text::new(ts.to_string()).into(),
1527 ));
1528 }
1529
1530 match command {
1531 SystemMessage::MemberRemovedFromGroup => {
1532 let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1533 let fingerprint_to_remove = msg.param.get(Param::Arg4).unwrap_or_default();
1534
1535 if email_to_remove
1536 == context
1537 .get_config(Config::ConfiguredAddr)
1538 .await?
1539 .unwrap_or_default()
1540 {
1541 placeholdertext = Some("I left the group.".to_string());
1542 } else {
1543 placeholdertext = Some(format!("I removed member {email_to_remove}."));
1544 };
1545
1546 if !email_to_remove.is_empty() {
1547 headers.push((
1548 "Chat-Group-Member-Removed",
1549 mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1550 .into(),
1551 ));
1552 }
1553
1554 if !fingerprint_to_remove.is_empty() {
1555 headers.push((
1556 "Chat-Group-Member-Removed-Fpr",
1557 mail_builder::headers::raw::Raw::new(fingerprint_to_remove.to_string())
1558 .into(),
1559 ));
1560 }
1561 }
1562 SystemMessage::MemberAddedToGroup => {
1563 let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1564 let fingerprint_to_add = msg.param.get(Param::Arg4).unwrap_or_default();
1565
1566 placeholdertext = Some(format!("I added member {email_to_add}."));
1567
1568 if !email_to_add.is_empty() {
1569 headers.push((
1570 "Chat-Group-Member-Added",
1571 mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1572 ));
1573 }
1574 if !fingerprint_to_add.is_empty() {
1575 headers.push((
1576 "Chat-Group-Member-Added-Fpr",
1577 mail_builder::headers::raw::Raw::new(fingerprint_to_add.to_string())
1578 .into(),
1579 ));
1580 }
1581 if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1582 let step = "vg-member-added";
1583 info!(context, "Sending secure-join message {:?}.", step);
1584 headers.push((
1585 "Secure-Join",
1586 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1587 ));
1588 }
1589 }
1590 SystemMessage::GroupNameChanged => {
1591 let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1592 headers.push((
1593 "Chat-Group-Name-Changed",
1594 mail_builder::headers::text::Text::new(old_name).into(),
1595 ));
1596 }
1597 SystemMessage::GroupImageChanged => {
1598 headers.push((
1599 "Chat-Content",
1600 mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1601 ));
1602 if grpimage.is_none() && is_encrypted {
1603 headers.push((
1604 "Chat-Group-Avatar",
1605 mail_builder::headers::raw::Raw::new("0").into(),
1606 ));
1607 }
1608 }
1609 _ => {}
1610 }
1611 }
1612
1613 match command {
1614 SystemMessage::LocationStreamingEnabled => {
1615 headers.push((
1616 "Chat-Content",
1617 mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1618 ));
1619 }
1620 SystemMessage::EphemeralTimerChanged => {
1621 headers.push((
1622 "Chat-Content",
1623 mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1624 ));
1625 }
1626 SystemMessage::LocationOnly
1627 | SystemMessage::MultiDeviceSync
1628 | SystemMessage::WebxdcStatusUpdate => {
1629 headers.push((
1638 "Auto-Submitted",
1639 mail_builder::headers::raw::Raw::new("auto-generated").into(),
1640 ));
1641 }
1642 SystemMessage::AutocryptSetupMessage => {
1643 headers.push((
1644 "Autocrypt-Setup-Message",
1645 mail_builder::headers::raw::Raw::new("v1").into(),
1646 ));
1647
1648 placeholdertext = Some(ASM_SUBJECT.to_string());
1649 }
1650 SystemMessage::SecurejoinMessage => {
1651 let step = msg.param.get(Param::Arg).unwrap_or_default();
1652 if !step.is_empty() {
1653 info!(context, "Sending secure-join message {step:?}.");
1654 headers.push((
1655 "Secure-Join",
1656 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1657 ));
1658
1659 let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1660 if !param2.is_empty() {
1661 headers.push((
1662 if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1663 "Secure-Join-Auth"
1664 } else {
1665 "Secure-Join-Invitenumber"
1666 },
1667 mail_builder::headers::text::Text::new(param2.to_string()).into(),
1668 ));
1669 }
1670
1671 let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1672 if !fingerprint.is_empty() {
1673 headers.push((
1674 "Secure-Join-Fingerprint",
1675 mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1676 ));
1677 }
1678 if let Some(id) = msg.param.get(Param::Arg4) {
1679 headers.push((
1680 "Secure-Join-Group",
1681 mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1682 ));
1683 };
1684 }
1685 }
1686 SystemMessage::ChatProtectionEnabled => {
1687 headers.push((
1688 "Chat-Content",
1689 mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1690 ));
1691 }
1692 SystemMessage::ChatProtectionDisabled => {
1693 headers.push((
1694 "Chat-Content",
1695 mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1696 ));
1697 }
1698 SystemMessage::IrohNodeAddr => {
1699 let node_addr = context
1700 .get_or_try_init_peer_channel()
1701 .await?
1702 .get_node_addr()
1703 .await?;
1704
1705 debug_assert!(node_addr.relay_url().is_some());
1708 headers.push((
1709 HeaderDef::IrohNodeAddr.into(),
1710 mail_builder::headers::text::Text::new(serde_json::to_string(&node_addr)?)
1711 .into(),
1712 ));
1713 }
1714 SystemMessage::CallAccepted => {
1715 headers.push((
1716 "Chat-Content",
1717 mail_builder::headers::raw::Raw::new("call-accepted").into(),
1718 ));
1719 }
1720 SystemMessage::CallEnded => {
1721 headers.push((
1722 "Chat-Content",
1723 mail_builder::headers::raw::Raw::new("call-ended").into(),
1724 ));
1725 }
1726 _ => {}
1727 }
1728
1729 if let Some(grpimage) = grpimage
1730 && is_encrypted
1731 {
1732 info!(context, "setting group image '{}'", grpimage);
1733 let avatar = build_avatar_file(context, grpimage)
1734 .await
1735 .context("Cannot attach group image")?;
1736 headers.push((
1737 "Chat-Group-Avatar",
1738 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1739 ));
1740 }
1741
1742 if msg.viewtype == Viewtype::Sticker {
1743 headers.push((
1744 "Chat-Content",
1745 mail_builder::headers::raw::Raw::new("sticker").into(),
1746 ));
1747 } else if msg.viewtype == Viewtype::Call {
1748 headers.push((
1749 "Chat-Content",
1750 mail_builder::headers::raw::Raw::new("call").into(),
1751 ));
1752 placeholdertext = Some(
1753 "[This is a 'Call'. The sender uses an experiment not supported on your version yet]".to_string(),
1754 );
1755 }
1756
1757 if let Some(offer) = msg.param.get(Param::WebrtcRoom) {
1758 headers.push((
1759 "Chat-Webrtc-Room",
1760 mail_builder::headers::raw::Raw::new(b_encode(offer)).into(),
1761 ));
1762 } else if let Some(answer) = msg.param.get(Param::WebrtcAccepted) {
1763 headers.push((
1764 "Chat-Webrtc-Accepted",
1765 mail_builder::headers::raw::Raw::new(b_encode(answer)).into(),
1766 ));
1767 }
1768
1769 if msg.viewtype == Viewtype::Voice
1770 || msg.viewtype == Viewtype::Audio
1771 || msg.viewtype == Viewtype::Video
1772 {
1773 if msg.viewtype == Viewtype::Voice {
1774 headers.push((
1775 "Chat-Voice-Message",
1776 mail_builder::headers::raw::Raw::new("1").into(),
1777 ));
1778 }
1779 let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1780 if duration_ms > 0 {
1781 let dur = duration_ms.to_string();
1782 headers.push((
1783 "Chat-Duration",
1784 mail_builder::headers::raw::Raw::new(dur).into(),
1785 ));
1786 }
1787 }
1788
1789 let afwd_email = msg.param.exists(Param::Forwarded);
1795 let fwdhint = if afwd_email {
1796 Some(
1797 "---------- Forwarded message ----------\r\n\
1798 From: Delta Chat\r\n\
1799 \r\n"
1800 .to_string(),
1801 )
1802 } else {
1803 None
1804 };
1805
1806 let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1807
1808 let mut quoted_text = None;
1809 if let Some(msg_quoted_text) = msg.quoted_text() {
1810 let mut some_quoted_text = String::new();
1811 for quoted_line in msg_quoted_text.split('\n') {
1812 some_quoted_text += "> ";
1813 some_quoted_text += quoted_line;
1814 some_quoted_text += "\r\n";
1815 }
1816 some_quoted_text += "\r\n";
1817 quoted_text = Some(some_quoted_text)
1818 }
1819
1820 if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1821 quoted_text = Some("> ...\r\n\r\n".to_string());
1823 }
1824 if quoted_text.is_none() && final_text.starts_with('>') {
1825 quoted_text = Some("\r\n".to_string());
1828 }
1829
1830 let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1831
1832 let footer = if is_reaction { "" } else { &self.selfstatus };
1833
1834 let message_text = format!(
1835 "{}{}{}{}{}{}",
1836 fwdhint.unwrap_or_default(),
1837 quoted_text.unwrap_or_default(),
1838 escape_message_footer_marks(final_text),
1839 if !final_text.is_empty() && !footer.is_empty() {
1840 "\r\n\r\n"
1841 } else {
1842 ""
1843 },
1844 if !footer.is_empty() { "-- \r\n" } else { "" },
1845 footer
1846 );
1847
1848 let mut main_part = MimePart::new("text/plain", message_text);
1849 if is_reaction {
1850 main_part = main_part.header(
1851 "Content-Disposition",
1852 mail_builder::headers::raw::Raw::new("reaction"),
1853 );
1854 }
1855
1856 let mut parts = Vec::new();
1857
1858 if msg.has_html() {
1861 let html = if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded) {
1862 MsgId::new(orig_msg_id.try_into()?)
1863 .get_html(context)
1864 .await?
1865 } else {
1866 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1867 };
1868 if let Some(html) = html {
1869 main_part = MimePart::new(
1870 "multipart/alternative",
1871 vec![main_part, MimePart::new("text/html", html)],
1872 )
1873 }
1874 }
1875
1876 if msg.viewtype.has_file() {
1878 let file_part = build_body_file(context, &msg).await?;
1879 parts.push(file_part);
1880 }
1881
1882 if let Some(msg_kml_part) = self.get_message_kml_part() {
1883 parts.push(msg_kml_part);
1884 }
1885
1886 if location::is_sending_locations_to_chat(context, Some(msg.chat_id)).await?
1887 && let Some(part) = self.get_location_kml_part(context).await?
1888 {
1889 parts.push(part);
1890 }
1891
1892 if command == SystemMessage::MultiDeviceSync {
1895 let json = msg.param.get(Param::Arg).unwrap_or_default();
1896 let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1897 parts.push(context.build_sync_part(json.to_string()));
1898 self.sync_ids_to_delete = Some(ids.to_string());
1899 } else if command == SystemMessage::WebxdcStatusUpdate {
1900 let json = msg.param.get(Param::Arg).unwrap_or_default();
1901 parts.push(context.build_status_update_part(json));
1902 } else if msg.viewtype == Viewtype::Webxdc {
1903 let topic = self
1904 .webxdc_topic
1905 .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1906 .unwrap_or(create_iroh_header(context, msg.id).await?);
1907 headers.push((
1908 HeaderDef::IrohGossipTopic.get_headername(),
1909 mail_builder::headers::raw::Raw::new(topic).into(),
1910 ));
1911 if let (Some(json), _) = context
1912 .render_webxdc_status_update_object(
1913 msg.id,
1914 StatusUpdateSerial::MIN,
1915 StatusUpdateSerial::MAX,
1916 None,
1917 )
1918 .await?
1919 {
1920 parts.push(context.build_status_update_part(&json));
1921 }
1922 }
1923
1924 if self.attach_selfavatar {
1925 match context.get_config(Config::Selfavatar).await? {
1926 Some(path) => match build_avatar_file(context, &path).await {
1927 Ok(avatar) => headers.push((
1928 "Chat-User-Avatar",
1929 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1930 )),
1931 Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1932 },
1933 None => headers.push((
1934 "Chat-User-Avatar",
1935 mail_builder::headers::raw::Raw::new("0").into(),
1936 )),
1937 }
1938 }
1939
1940 Ok((main_part, parts))
1941 }
1942
1943 fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1945 let Loaded::Mdn {
1948 rfc724_mid,
1949 additional_msg_ids,
1950 } = &self.loaded
1951 else {
1952 bail!("Attempt to render a message as MDN");
1953 };
1954
1955 let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1959
1960 let mut message = MimePart::new(
1961 "multipart/report; report-type=disposition-notification",
1962 vec![text_part],
1963 );
1964
1965 let message_text2 = format!(
1967 "Original-Recipient: rfc822;{}\r\n\
1968 Final-Recipient: rfc822;{}\r\n\
1969 Original-Message-ID: <{}>\r\n\
1970 Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1971 self.from_addr, self.from_addr, rfc724_mid
1972 );
1973
1974 let extension_fields = if additional_msg_ids.is_empty() {
1975 "".to_string()
1976 } else {
1977 "Additional-Message-IDs: ".to_string()
1978 + &additional_msg_ids
1979 .iter()
1980 .map(|mid| render_rfc724_mid(mid))
1981 .collect::<Vec<String>>()
1982 .join(" ")
1983 + "\r\n"
1984 };
1985
1986 message.add_part(MimePart::new(
1987 "message/disposition-notification",
1988 message_text2 + &extension_fields,
1989 ));
1990
1991 Ok(message)
1992 }
1993}
1994
1995fn hidden_recipients() -> Address<'static> {
1996 Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
1997}
1998
1999fn should_encrypt_with_broadcast_secret(msg: &Message, chat: &Chat) -> bool {
2000 chat.typ == Chattype::OutBroadcast && must_have_only_one_recipient(msg, chat).is_none()
2001}
2002
2003fn should_hide_recipients(msg: &Message, chat: &Chat) -> bool {
2004 should_encrypt_with_broadcast_secret(msg, chat)
2005}
2006
2007fn should_encrypt_symmetrically(msg: &Message, chat: &Chat) -> bool {
2008 should_encrypt_with_broadcast_secret(msg, chat)
2009}
2010
2011fn must_have_only_one_recipient<'a>(msg: &'a Message, chat: &Chat) -> Option<Result<&'a str>> {
2016 if chat.typ == Chattype::OutBroadcast
2017 && matches!(
2018 msg.param.get_cmd(),
2019 SystemMessage::MemberRemovedFromGroup | SystemMessage::MemberAddedToGroup
2020 )
2021 {
2022 let Some(fp) = msg.param.get(Param::Arg4) else {
2023 return Some(Err(format_err!("Missing removed/added member")));
2024 };
2025 return Some(Ok(fp));
2026 }
2027 None
2028}
2029
2030async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
2031 let file_name = msg.get_filename().context("msg has no file")?;
2032 let blob = msg
2033 .param
2034 .get_file_blob(context)?
2035 .context("msg has no file")?;
2036 let mimetype = msg
2037 .param
2038 .get(Param::MimeType)
2039 .unwrap_or("application/octet-stream")
2040 .to_string();
2041 let body = fs::read(blob.to_abs_path()).await?;
2042
2043 let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
2049
2050 Ok(mail)
2051}
2052
2053async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
2054 let blob = match path.starts_with("$BLOBDIR/") {
2055 true => BlobObject::from_name(context, path)?,
2056 false => BlobObject::from_path(context, path.as_ref())?,
2057 };
2058 let body = fs::read(blob.to_abs_path()).await?;
2059 let encoded_body = base64::engine::general_purpose::STANDARD
2060 .encode(&body)
2061 .chars()
2062 .enumerate()
2063 .fold(String::new(), |mut res, (i, c)| {
2064 if i % 78 == 77 {
2065 res.push(' ')
2066 }
2067 res.push(c);
2068 res
2069 });
2070 Ok(encoded_body)
2071}
2072
2073fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
2074 let addr_lc = addr.to_lowercase();
2075 recipients
2076 .iter()
2077 .any(|(_, cur)| cur.to_lowercase() == addr_lc)
2078}
2079
2080fn render_rfc724_mid(rfc724_mid: &str) -> String {
2081 let rfc724_mid = rfc724_mid.trim().to_string();
2082
2083 if rfc724_mid.chars().next().unwrap_or_default() == '<' {
2084 rfc724_mid
2085 } else {
2086 format!("<{rfc724_mid}>")
2087 }
2088}
2089
2090fn b_encode(value: &str) -> String {
2096 format!(
2097 "=?utf-8?B?{}?=",
2098 base64::engine::general_purpose::STANDARD.encode(value)
2099 )
2100}
2101
2102#[cfg(test)]
2103mod mimefactory_tests;