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, EmailAddress};
13use mail_builder::mime::MimePart;
14use tokio::fs;
15
16use crate::aheader::{Aheader, EncryptPreference};
17use crate::blob::BlobObject;
18use crate::chat::{self, Chat, PARAM_BROADCAST_SECRET, load_broadcast_secret};
19use crate::config::Config;
20use crate::constants::{ASM_SUBJECT, BROADCAST_INCOMPATIBILITY_MSG};
21use crate::constants::{Chattype, DC_FROM_HANDSHAKE};
22use crate::contact::{Contact, ContactId, Origin};
23use crate::context::Context;
24use crate::e2ee::EncryptHelper;
25use crate::ensure_and_debug_assert;
26use crate::ephemeral::Timer as EphemeralTimer;
27use crate::headerdef::HeaderDef;
28use crate::key::{DcKey, SignedPublicKey, self_fingerprint};
29use crate::location;
30use crate::log::warn;
31use crate::message::{Message, MsgId, Viewtype};
32use crate::mimeparser::{SystemMessage, is_hidden};
33use crate::param::Param;
34use crate::peer_channels::{create_iroh_header, get_iroh_topic_for_msg};
35use crate::simplify::escape_message_footer_marks;
36use crate::stock_str;
37use crate::tools::{
38 IsNoneOrEmpty, create_outgoing_rfc724_mid, create_smeared_timestamp, remove_subject_prefix,
39 time,
40};
41use crate::webxdc::StatusUpdateSerial;
42
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_pubkeys: 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 = should_hide_recipients(&msg, &chat);
186
187 let from_addr = context.get_primary_self_addr().await?;
188 let config_displayname = context
189 .get_config(Config::Displayname)
190 .await?
191 .unwrap_or_default();
192 let (from_displayname, sender_displayname) =
193 if let Some(override_name) = msg.param.get(Param::OverrideSenderDisplayname) {
194 (override_name.to_string(), Some(config_displayname))
195 } else {
196 let name = match attach_profile_data {
197 true => config_displayname,
198 false => "".to_string(),
199 };
200 (name, None)
201 };
202
203 let mut recipients = Vec::new();
204 let mut to = Vec::new();
205 let mut past_members = Vec::new();
206 let mut member_fingerprints = Vec::new();
207 let mut member_timestamps = Vec::new();
208 let mut recipient_ids = HashSet::new();
209 let mut req_mdn = false;
210
211 let encryption_pubkeys;
212
213 let self_fingerprint = self_fingerprint(context).await?;
214
215 if chat.is_self_talk() {
216 to.push((from_displayname.to_string(), from_addr.to_string()));
217
218 encryption_pubkeys = if msg.param.get_bool(Param::ForcePlaintext).unwrap_or(false) {
219 None
220 } else {
221 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_pubkeys = None;
234 } else {
235 let email_to_remove = if msg.param.get_cmd() == SystemMessage::MemberRemovedFromGroup {
236 msg.param.get(Param::Arg)
237 } else {
238 None
239 };
240
241 let is_encrypted = if msg
242 .param
243 .get_bool(Param::ForcePlaintext)
244 .unwrap_or_default()
245 {
246 false
247 } else {
248 msg.param.get_bool(Param::GuaranteeE2ee).unwrap_or_default()
249 || chat.is_encrypted(context).await?
250 };
251
252 let mut keys = Vec::new();
253 let mut missing_key_addresses = BTreeSet::new();
254 context
255 .sql
256 .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 if let Some(fp) = must_have_only_one_recipient(&msg, &chat)
296 && fp? != fingerprint {
297 continue;
298 }
299
300 let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
301 Some(SignedPublicKey::from_slice(public_key_bytes)?)
302 } else {
303 None
304 };
305
306 let addr = if id == ContactId::SELF {
307 from_addr.to_string()
308 } else {
309 addr
310 };
311 let name = match attach_profile_data {
312 true => authname,
313 false => "".to_string(),
314 };
315 if add_timestamp >= remove_timestamp {
316 if !recipients_contain_addr(&to, &addr) {
317 if id != ContactId::SELF {
318 recipients.push(addr.clone());
319 }
320 if !undisclosed_recipients {
321 to.push((name, addr.clone()));
322
323 if is_encrypted {
324 if !fingerprint.is_empty() {
325 member_fingerprints.push(fingerprint);
326 } else if id == ContactId::SELF {
327 member_fingerprints.push(self_fingerprint.to_string());
328 } else {
329 ensure_and_debug_assert!(member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
330 }
331 }
332 member_timestamps.push(add_timestamp);
333 }
334 }
335 recipient_ids.insert(id);
336
337 if let Some(public_key) = public_key_opt {
338 keys.push((addr.clone(), public_key))
339 } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
340 missing_key_addresses.insert(addr.clone());
341 if is_encrypted {
342 warn!(context, "Missing key for {addr}");
343 }
344 }
345 } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
346 if !recipients_contain_addr(&past_members, &addr) {
349 if let Some(email_to_remove) = email_to_remove
350 && email_to_remove == addr {
351 if id != ContactId::SELF {
355 recipients.push(addr.clone());
356 }
357
358 if let Some(public_key) = public_key_opt {
359 keys.push((addr.clone(), public_key))
360 } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
361 missing_key_addresses.insert(addr.clone());
362 if is_encrypted {
363 warn!(context, "Missing key for {addr}");
364 }
365 }
366 }
367 if !undisclosed_recipients {
368 past_members.push((name, addr.clone()));
369 past_member_timestamps.push(remove_timestamp);
370
371 if is_encrypted {
372 if !fingerprint.is_empty() {
373 past_member_fingerprints.push(fingerprint);
374 } else if id == ContactId::SELF {
375 past_member_fingerprints.push(self_fingerprint.to_string());
378 } else {
379 ensure_and_debug_assert!(past_member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
380 }
381 }
382 }
383 }
384 }
385 }
386
387 ensure_and_debug_assert!(
388 member_timestamps.len() >= to.len(),
389 "member_timestamps.len() ({}) < to.len() ({})",
390 member_timestamps.len(), to.len());
391 ensure_and_debug_assert!(
392 member_fingerprints.is_empty() || member_fingerprints.len() >= to.len(),
393 "member_fingerprints.len() ({}) < to.len() ({})",
394 member_fingerprints.len(), to.len());
395
396 if to.len() > 1
397 && let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
398 to.remove(position);
399 member_timestamps.remove(position);
400 if is_encrypted {
401 member_fingerprints.remove(position);
402 }
403 }
404
405 member_timestamps.extend(past_member_timestamps);
406 if is_encrypted {
407 member_fingerprints.extend(past_member_fingerprints);
408 }
409 Ok(())
410 },
411 )
412 .await?;
413 let recipient_ids: Vec<_> = recipient_ids.into_iter().collect();
414 ContactId::scaleup_origin(context, &recipient_ids, Origin::OutgoingTo).await?;
415
416 if !msg.is_system_message()
417 && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
418 && context.should_request_mdns().await?
419 {
420 req_mdn = true;
421 }
422
423 encryption_pubkeys = if !is_encrypted {
424 None
425 } else if should_encrypt_symmetrically(&msg, &chat) {
426 Some(Vec::new())
427 } else {
428 if keys.is_empty() && !recipients.is_empty() {
429 bail!("No recipient keys are available, cannot encrypt to {recipients:?}.");
430 }
431
432 if !missing_key_addresses.is_empty() {
434 recipients.retain(|addr| !missing_key_addresses.contains(addr));
435 }
436
437 Some(keys)
438 };
439 }
440
441 let (in_reply_to, references) = context
442 .sql
443 .query_row(
444 "SELECT mime_in_reply_to, IFNULL(mime_references, '')
445 FROM msgs WHERE id=?",
446 (msg.id,),
447 |row| {
448 let in_reply_to: String = row.get(0)?;
449 let references: String = row.get(1)?;
450
451 Ok((in_reply_to, references))
452 },
453 )
454 .await?;
455 let references: Vec<String> = references
456 .trim()
457 .split_ascii_whitespace()
458 .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
459 .collect();
460 let selfstatus = match attach_profile_data {
461 true => context
462 .get_config(Config::Selfstatus)
463 .await?
464 .unwrap_or_default(),
465 false => "".to_string(),
466 };
467 let attach_selfavatar = Self::should_attach_selfavatar(context, &msg).await;
468
469 ensure_and_debug_assert!(
470 member_timestamps.is_empty()
471 || to.len() + past_members.len() == member_timestamps.len(),
472 "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
473 to.len(),
474 past_members.len(),
475 member_timestamps.len(),
476 );
477 let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
478 let factory = MimeFactory {
479 from_addr,
480 from_displayname,
481 sender_displayname,
482 selfstatus,
483 recipients,
484 encryption_pubkeys,
485 to,
486 past_members,
487 member_fingerprints,
488 member_timestamps,
489 timestamp: msg.timestamp_sort,
490 loaded: Loaded::Message { msg, chat },
491 in_reply_to,
492 references,
493 req_mdn,
494 last_added_location_id: None,
495 sync_ids_to_delete: None,
496 attach_selfavatar,
497 webxdc_topic,
498 };
499 Ok(factory)
500 }
501
502 pub async fn from_mdn(
503 context: &Context,
504 from_id: ContactId,
505 rfc724_mid: String,
506 additional_msg_ids: Vec<String>,
507 ) -> Result<MimeFactory> {
508 let contact = Contact::get_by_id(context, from_id).await?;
509 let from_addr = context.get_primary_self_addr().await?;
510 let timestamp = create_smeared_timestamp(context);
511
512 let addr = contact.get_addr().to_string();
513 let encryption_pubkeys = if contact.is_key_contact() {
514 if let Some(key) = contact.public_key(context).await? {
515 Some(vec![(addr.clone(), key)])
516 } else {
517 Some(Vec::new())
518 }
519 } else {
520 None
521 };
522
523 let res = MimeFactory {
524 from_addr,
525 from_displayname: "".to_string(),
526 sender_displayname: None,
527 selfstatus: "".to_string(),
528 recipients: vec![addr],
529 encryption_pubkeys,
530 to: vec![("".to_string(), contact.get_addr().to_string())],
531 past_members: vec![],
532 member_fingerprints: vec![],
533 member_timestamps: vec![],
534 timestamp,
535 loaded: Loaded::Mdn {
536 rfc724_mid,
537 additional_msg_ids,
538 },
539 in_reply_to: String::default(),
540 references: Vec::new(),
541 req_mdn: false,
542 last_added_location_id: None,
543 sync_ids_to_delete: None,
544 attach_selfavatar: false,
545 webxdc_topic: None,
546 };
547
548 Ok(res)
549 }
550
551 fn should_skip_autocrypt(&self) -> bool {
552 match &self.loaded {
553 Loaded::Message { msg, .. } => {
554 msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
555 }
556 Loaded::Mdn { .. } => true,
557 }
558 }
559
560 fn should_attach_profile_data(msg: &Message) -> bool {
561 msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
562 let step = msg.param.get(Param::Arg).unwrap_or_default();
563 step == "vg-request-with-auth"
569 || step == "vc-request-with-auth"
570 || step == "vg-member-added"
575 || step == "vc-contact-confirm"
576 }
577 }
578
579 async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
580 Self::should_attach_profile_data(msg)
581 && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
582 Ok(should) => should,
583 Err(err) => {
584 warn!(
585 context,
586 "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
587 );
588 false
589 }
590 }
591 }
592
593 fn grpimage(&self) -> Option<String> {
594 match &self.loaded {
595 Loaded::Message { chat, msg } => {
596 let cmd = msg.param.get_cmd();
597
598 match cmd {
599 SystemMessage::MemberAddedToGroup => {
600 return chat.param.get(Param::ProfileImage).map(Into::into);
601 }
602 SystemMessage::GroupImageChanged => {
603 return msg.param.get(Param::Arg).map(Into::into);
604 }
605 _ => {}
606 }
607
608 if msg
609 .param
610 .get_bool(Param::AttachGroupImage)
611 .unwrap_or_default()
612 {
613 return chat.param.get(Param::ProfileImage).map(Into::into);
614 }
615
616 None
617 }
618 Loaded::Mdn { .. } => None,
619 }
620 }
621
622 async fn subject_str(&self, context: &Context) -> Result<String> {
623 let subject = match &self.loaded {
624 Loaded::Message { chat, msg } => {
625 let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
626
627 if !msg.subject.is_empty() {
628 return Ok(msg.subject.clone());
629 }
630
631 if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
632 && quoted_msg_subject.is_none_or_empty()
633 {
634 let re = if self.in_reply_to.is_empty() {
635 ""
636 } else {
637 "Re: "
638 };
639 return Ok(format!("{}{}", re, chat.name));
640 }
641
642 let parent_subject = if quoted_msg_subject.is_none_or_empty() {
643 chat.param.get(Param::LastSubject)
644 } else {
645 quoted_msg_subject.as_deref()
646 };
647 if let Some(last_subject) = parent_subject {
648 return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
649 }
650
651 let self_name = match Self::should_attach_profile_data(msg) {
652 true => context.get_config(Config::Displayname).await?,
653 false => None,
654 };
655 let self_name = &match self_name {
656 Some(name) => name,
657 None => context.get_config(Config::Addr).await?.unwrap_or_default(),
658 };
659 stock_str::subject_for_new_contact(context, self_name).await
660 }
661 Loaded::Mdn { .. } => "Receipt Notification".to_string(), };
663
664 Ok(subject)
665 }
666
667 pub fn recipients(&self) -> Vec<String> {
668 self.recipients.clone()
669 }
670
671 pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
674 let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
675
676 let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
677
678 let mut to: Vec<Address<'static>> = Vec::new();
679 for (name, addr) in &self.to {
680 to.push(Address::new_address(
681 if name.is_empty() {
682 None
683 } else {
684 Some(name.to_string())
685 },
686 addr.clone(),
687 ));
688 }
689
690 let mut past_members: Vec<Address<'static>> = Vec::new(); for (name, addr) in &self.past_members {
692 past_members.push(Address::new_address(
693 if name.is_empty() {
694 None
695 } else {
696 Some(name.to_string())
697 },
698 addr.clone(),
699 ));
700 }
701
702 ensure_and_debug_assert!(
703 self.member_timestamps.is_empty()
704 || to.len() + past_members.len() == self.member_timestamps.len(),
705 "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
706 to.len(),
707 past_members.len(),
708 self.member_timestamps.len(),
709 );
710 if to.is_empty() {
711 to.push(hidden_recipients());
712 }
713
714 headers.push(("From", from.into()));
717
718 if let Some(sender_displayname) = &self.sender_displayname {
719 let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
720 headers.push(("Sender", sender.into()));
721 }
722 headers.push((
723 "To",
724 mail_builder::headers::address::Address::new_list(to.clone()).into(),
725 ));
726 if !past_members.is_empty() {
727 headers.push((
728 "Chat-Group-Past-Members",
729 mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
730 ));
731 }
732
733 if let Loaded::Message { chat, .. } = &self.loaded
734 && chat.typ == Chattype::Group
735 {
736 if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await? {
737 headers.push((
738 "Chat-Group-Member-Timestamps",
739 mail_builder::headers::raw::Raw::new(
740 self.member_timestamps
741 .iter()
742 .map(|ts| ts.to_string())
743 .collect::<Vec<String>>()
744 .join(" "),
745 )
746 .into(),
747 ));
748 }
749
750 if !self.member_fingerprints.is_empty() {
751 headers.push((
752 "Chat-Group-Member-Fpr",
753 mail_builder::headers::raw::Raw::new(
754 self.member_fingerprints
755 .iter()
756 .map(|fp| fp.to_string())
757 .collect::<Vec<String>>()
758 .join(" "),
759 )
760 .into(),
761 ));
762 }
763 }
764
765 let subject_str = self.subject_str(context).await?;
766 headers.push((
767 "Subject",
768 mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
769 ));
770
771 let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
772 .unwrap()
773 .to_rfc2822();
774 headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
775
776 let rfc724_mid = match &self.loaded {
777 Loaded::Message { msg, .. } => msg.rfc724_mid.clone(),
778 Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
779 };
780 headers.push((
781 "Message-ID",
782 mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
783 ));
784
785 if !self.in_reply_to.is_empty() {
787 headers.push((
788 "In-Reply-To",
789 mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
790 ));
791 }
792 if !self.references.is_empty() {
793 headers.push((
794 "References",
795 mail_builder::headers::message_id::MessageId::<'static>::new_list(
796 self.references.iter().map(|s| s.to_string()),
797 )
798 .into(),
799 ));
800 }
801
802 if let Loaded::Mdn { .. } = self.loaded {
804 headers.push((
805 "Auto-Submitted",
806 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
807 ));
808 } else if context.get_config_bool(Config::Bot).await? {
809 headers.push((
810 "Auto-Submitted",
811 mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
812 ));
813 } else if let Loaded::Message { msg, .. } = &self.loaded
814 && msg.param.get_cmd() == SystemMessage::SecurejoinMessage
815 {
816 let step = msg.param.get(Param::Arg).unwrap_or_default();
817 if step != "vg-request" && step != "vc-request" {
818 headers.push((
819 "Auto-Submitted",
820 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
821 ));
822 }
823 }
824
825 if let Loaded::Message { msg, chat } = &self.loaded
826 && (chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast)
827 {
828 headers.push((
829 "Chat-List-ID",
830 mail_builder::headers::text::Text::new(format!("{} <{}>", chat.name, chat.grpid))
831 .into(),
832 ));
833
834 if msg.param.get_cmd() == SystemMessage::MemberAddedToGroup
835 && let Some(secret) = msg.param.get(PARAM_BROADCAST_SECRET)
836 {
837 headers.push((
838 "Chat-Broadcast-Secret",
839 mail_builder::headers::text::Text::new(secret.to_string()).into(),
840 ));
841 }
842 }
843
844 if let Loaded::Message { msg, .. } = &self.loaded {
845 if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
846 headers.push((
847 "Chat-Edit",
848 mail_builder::headers::message_id::MessageId::new(
849 original_rfc724_mid.to_string(),
850 )
851 .into(),
852 ));
853 } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
854 headers.push((
855 "Chat-Delete",
856 mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
857 .into(),
858 ));
859 }
860 }
861
862 headers.push((
864 "Chat-Version",
865 mail_builder::headers::raw::Raw::new("1.0").into(),
866 ));
867
868 if self.req_mdn {
869 headers.push((
873 "Chat-Disposition-Notification-To",
874 mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
875 ));
876 }
877
878 let grpimage = self.grpimage();
879 let skip_autocrypt = self.should_skip_autocrypt();
880 let encrypt_helper = EncryptHelper::new(context).await?;
881
882 if !skip_autocrypt {
883 let aheader = encrypt_helper.get_aheader().to_string();
885 headers.push((
886 "Autocrypt",
887 mail_builder::headers::raw::Raw::new(aheader).into(),
888 ));
889 }
890
891 let is_encrypted = self.encryption_pubkeys.is_some();
892
893 if let Loaded::Message { msg, .. } = &self.loaded {
897 let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
898 if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
899 headers.push((
900 "Ephemeral-Timer",
901 mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
902 ));
903 }
904 }
905
906 let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
907 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
908 } else {
909 false
910 };
911
912 let message: MimePart<'static> = match &self.loaded {
913 Loaded::Message { msg, .. } => {
914 let msg = msg.clone();
915 let (main_part, mut parts) = self
916 .render_message(context, &mut headers, &grpimage, is_encrypted)
917 .await?;
918 if parts.is_empty() {
919 main_part
921 } else {
922 parts.insert(0, main_part);
923
924 if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
926 MimePart::new("multipart/report; report-type=multi-device-sync", parts)
927 } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
928 MimePart::new("multipart/report; report-type=status-update", parts)
929 } else {
930 MimePart::new("multipart/mixed", parts)
931 }
932 }
933 }
934 Loaded::Mdn { .. } => self.render_mdn()?,
935 };
936
937 let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
946
947 let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
960
961 let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
970
971 unprotected_headers.push((
973 "MIME-Version",
974 mail_builder::headers::raw::Raw::new("1.0").into(),
975 ));
976 for header @ (original_header_name, _header_value) in &headers {
977 let header_name = original_header_name.to_lowercase();
978 if header_name == "message-id" {
979 unprotected_headers.push(header.clone());
980 hidden_headers.push(header.clone());
981 } else if is_hidden(&header_name) {
982 hidden_headers.push(header.clone());
983 } else if header_name == "from" {
984 if is_encrypted || !is_securejoin_message {
986 protected_headers.push(header.clone());
987 }
988
989 unprotected_headers.push((
990 original_header_name,
991 Address::new_address(None::<&'static str>, self.from_addr.clone()).into(),
992 ));
993 } else if header_name == "to" {
994 protected_headers.push(header.clone());
995 if is_encrypted {
996 let mut to_without_names = to
997 .clone()
998 .into_iter()
999 .filter_map(|header| match header {
1000 Address::Address(mb) => Some(Address::Address(EmailAddress {
1001 name: None,
1002 email: mb.email,
1003 })),
1004 _ => None,
1005 })
1006 .collect::<Vec<_>>();
1007 if to_without_names.is_empty() {
1008 to_without_names.push(hidden_recipients());
1009 }
1010 unprotected_headers.push((
1011 original_header_name,
1012 Address::new_list(to_without_names).into(),
1013 ));
1014 } else {
1015 unprotected_headers.push(header.clone());
1016 }
1017 } else if header_name == "chat-broadcast-secret" {
1018 if is_encrypted {
1019 protected_headers.push(header.clone());
1020 } else {
1021 bail!("Message is unecrypted, cannot include broadcast secret");
1022 }
1023 } else if is_encrypted && header_name == "date" {
1024 protected_headers.push(header.clone());
1025
1026 let timestamp_offset = rand::random_range(0..518400);
1048 let protected_timestamp = self.timestamp.saturating_sub(timestamp_offset);
1049 let unprotected_date =
1050 chrono::DateTime::<chrono::Utc>::from_timestamp(protected_timestamp, 0)
1051 .unwrap()
1052 .to_rfc2822();
1053 unprotected_headers.push((
1054 "Date",
1055 mail_builder::headers::raw::Raw::new(unprotected_date).into(),
1056 ));
1057 } else if is_encrypted {
1058 protected_headers.push(header.clone());
1059
1060 match header_name.as_str() {
1061 "subject" => {
1062 unprotected_headers.push((
1063 "Subject",
1064 mail_builder::headers::raw::Raw::new("[...]").into(),
1065 ));
1066 }
1067 "in-reply-to"
1068 | "references"
1069 | "auto-submitted"
1070 | "chat-version"
1071 | "autocrypt-setup-message" => {
1072 unprotected_headers.push(header.clone());
1073 }
1074 _ => {
1075 }
1077 }
1078 } else {
1079 protected_headers.push(header.clone());
1083 unprotected_headers.push(header.clone())
1084 }
1085 }
1086
1087 let use_std_header_protection = context
1088 .get_config_bool(Config::StdHeaderProtectionComposing)
1089 .await?;
1090 let outer_message = if let Some(encryption_pubkeys) = self.encryption_pubkeys {
1091 let message = protected_headers
1093 .into_iter()
1094 .fold(message, |message, (header, value)| {
1095 message.header(header, value)
1096 });
1097
1098 let mut message: MimePart<'static> = hidden_headers
1100 .into_iter()
1101 .fold(message, |message, (header, value)| {
1102 message.header(header, value)
1103 });
1104
1105 if use_std_header_protection {
1106 message = unprotected_headers
1107 .iter()
1108 .filter(|(name, _)| {
1111 !(name.eq_ignore_ascii_case("mime-version")
1112 || name.eq_ignore_ascii_case("content-type")
1113 || name.eq_ignore_ascii_case("content-transfer-encoding")
1114 || name.eq_ignore_ascii_case("content-disposition"))
1115 })
1116 .fold(message, |message, (name, value)| {
1117 message.header(format!("HP-Outer: {name}"), value.clone())
1118 });
1119 }
1120
1121 let multiple_recipients =
1123 encryption_pubkeys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1124
1125 let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1126 let now = time();
1127
1128 match &self.loaded {
1129 Loaded::Message { chat, msg } => {
1130 if !should_hide_recipients(msg, chat) {
1131 for (addr, key) in &encryption_pubkeys {
1132 let fingerprint = key.dc_fingerprint().hex();
1133 let cmd = msg.param.get_cmd();
1134 let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1135 || cmd == SystemMessage::SecurejoinMessage
1136 || multiple_recipients && {
1137 let gossiped_timestamp: Option<i64> = context
1138 .sql
1139 .query_get_value(
1140 "SELECT timestamp
1141 FROM gossip_timestamp
1142 WHERE chat_id=? AND fingerprint=?",
1143 (chat.id, &fingerprint),
1144 )
1145 .await?;
1146
1147 gossip_period == 0
1154 || gossiped_timestamp
1155 .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1156 };
1157
1158 let verifier_id: Option<u32> = context
1159 .sql
1160 .query_get_value(
1161 "SELECT verifier FROM contacts WHERE fingerprint=?",
1162 (&fingerprint,),
1163 )
1164 .await?;
1165
1166 let is_verified =
1167 verifier_id.is_some_and(|verifier_id| verifier_id != 0);
1168
1169 if !should_do_gossip {
1170 continue;
1171 }
1172
1173 let header = Aheader {
1174 addr: addr.clone(),
1175 public_key: key.clone(),
1176 prefer_encrypt: EncryptPreference::NoPreference,
1179 verified: is_verified,
1180 }
1181 .to_string();
1182
1183 message = message.header(
1184 "Autocrypt-Gossip",
1185 mail_builder::headers::raw::Raw::new(header),
1186 );
1187
1188 context
1189 .sql
1190 .execute(
1191 "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1192 VALUES (?, ?, ?)
1193 ON CONFLICT (chat_id, fingerprint)
1194 DO UPDATE SET timestamp=excluded.timestamp",
1195 (chat.id, &fingerprint, now),
1196 )
1197 .await?;
1198 }
1199 }
1200 }
1201 Loaded::Mdn { .. } => {
1202 }
1204 }
1205
1206 for (h, v) in &mut message.headers {
1208 if h == "Content-Type"
1209 && let mail_builder::headers::HeaderType::ContentType(ct) = v
1210 {
1211 let mut ct_new = ct.clone();
1212 ct_new = ct_new.attribute("protected-headers", "v1");
1213 if use_std_header_protection {
1214 ct_new = ct_new.attribute("hp", "cipher");
1215 }
1216 *ct = ct_new;
1217 break;
1218 }
1219 }
1220
1221 let compress = match &self.loaded {
1225 Loaded::Message { msg, .. } => {
1226 msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1227 }
1228 Loaded::Mdn { .. } => true,
1229 };
1230
1231 let shared_secret: Option<String> = match &self.loaded {
1232 Loaded::Message { chat, msg }
1233 if should_encrypt_with_broadcast_secret(msg, chat) =>
1234 {
1235 let secret = load_broadcast_secret(context, chat.id).await?;
1236 if secret.is_none() {
1237 let text = BROADCAST_INCOMPATIBILITY_MSG;
1242 chat::add_info_msg(context, chat.id, text).await?;
1243 bail!(text);
1244 }
1245 secret
1246 }
1247 _ => None,
1248 };
1249
1250 let anonymous_recipients = false;
1260
1261 if context.get_config_bool(Config::TestHooks).await?
1262 && let Some(hook) = &*context.pre_encrypt_mime_hook.lock()
1263 {
1264 message = hook(context, message);
1265 }
1266
1267 let encrypted = if let Some(shared_secret) = shared_secret {
1268 encrypt_helper
1269 .encrypt_symmetrically(context, &shared_secret, message, compress)
1270 .await?
1271 } else {
1272 let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1277 encryption_keyring
1278 .extend(encryption_pubkeys.iter().map(|(_addr, key)| (*key).clone()));
1279
1280 encrypt_helper
1281 .encrypt(
1282 context,
1283 encryption_keyring,
1284 message,
1285 compress,
1286 anonymous_recipients,
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(stock_str::msg_group_left_remote(context).await);
1542 } else {
1543 placeholdertext =
1544 Some(stock_str::msg_del_member_remote(context, email_to_remove).await);
1545 };
1546
1547 if !email_to_remove.is_empty() {
1548 headers.push((
1549 "Chat-Group-Member-Removed",
1550 mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1551 .into(),
1552 ));
1553 }
1554
1555 if !fingerprint_to_remove.is_empty() {
1556 headers.push((
1557 "Chat-Group-Member-Removed-Fpr",
1558 mail_builder::headers::raw::Raw::new(fingerprint_to_remove.to_string())
1559 .into(),
1560 ));
1561 }
1562 }
1563 SystemMessage::MemberAddedToGroup => {
1564 let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1565 let fingerprint_to_add = msg.param.get(Param::Arg4).unwrap_or_default();
1566
1567 placeholdertext =
1568 Some(stock_str::msg_add_member_remote(context, email_to_add).await);
1569
1570 if !email_to_add.is_empty() {
1571 headers.push((
1572 "Chat-Group-Member-Added",
1573 mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1574 ));
1575 }
1576 if !fingerprint_to_add.is_empty() {
1577 headers.push((
1578 "Chat-Group-Member-Added-Fpr",
1579 mail_builder::headers::raw::Raw::new(fingerprint_to_add.to_string())
1580 .into(),
1581 ));
1582 }
1583 if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1584 let step = "vg-member-added";
1585 info!(context, "Sending secure-join message {:?}.", step);
1586 headers.push((
1587 "Secure-Join",
1588 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1589 ));
1590 }
1591 }
1592 SystemMessage::GroupNameChanged => {
1593 let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1594 headers.push((
1595 "Chat-Group-Name-Changed",
1596 mail_builder::headers::text::Text::new(old_name).into(),
1597 ));
1598 }
1599 SystemMessage::GroupImageChanged => {
1600 headers.push((
1601 "Chat-Content",
1602 mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1603 ));
1604 if grpimage.is_none() {
1605 headers.push((
1606 "Chat-Group-Avatar",
1607 mail_builder::headers::raw::Raw::new("0").into(),
1608 ));
1609 }
1610 }
1611 _ => {}
1612 }
1613 }
1614
1615 match command {
1616 SystemMessage::LocationStreamingEnabled => {
1617 headers.push((
1618 "Chat-Content",
1619 mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1620 ));
1621 }
1622 SystemMessage::EphemeralTimerChanged => {
1623 headers.push((
1624 "Chat-Content",
1625 mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1626 ));
1627 }
1628 SystemMessage::LocationOnly
1629 | SystemMessage::MultiDeviceSync
1630 | SystemMessage::WebxdcStatusUpdate => {
1631 headers.push((
1640 "Auto-Submitted",
1641 mail_builder::headers::raw::Raw::new("auto-generated").into(),
1642 ));
1643 }
1644 SystemMessage::AutocryptSetupMessage => {
1645 headers.push((
1646 "Autocrypt-Setup-Message",
1647 mail_builder::headers::raw::Raw::new("v1").into(),
1648 ));
1649
1650 placeholdertext = Some(ASM_SUBJECT.to_string());
1651 }
1652 SystemMessage::SecurejoinMessage => {
1653 let step = msg.param.get(Param::Arg).unwrap_or_default();
1654 if !step.is_empty() {
1655 info!(context, "Sending secure-join message {step:?}.");
1656 headers.push((
1657 "Secure-Join",
1658 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1659 ));
1660
1661 let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1662 if !param2.is_empty() {
1663 headers.push((
1664 if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1665 "Secure-Join-Auth"
1666 } else {
1667 "Secure-Join-Invitenumber"
1668 },
1669 mail_builder::headers::text::Text::new(param2.to_string()).into(),
1670 ));
1671 }
1672
1673 let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1674 if !fingerprint.is_empty() {
1675 headers.push((
1676 "Secure-Join-Fingerprint",
1677 mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1678 ));
1679 }
1680 if let Some(id) = msg.param.get(Param::Arg4) {
1681 headers.push((
1682 "Secure-Join-Group",
1683 mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1684 ));
1685 };
1686 }
1687 }
1688 SystemMessage::ChatProtectionEnabled => {
1689 headers.push((
1690 "Chat-Content",
1691 mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1692 ));
1693 }
1694 SystemMessage::ChatProtectionDisabled => {
1695 headers.push((
1696 "Chat-Content",
1697 mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1698 ));
1699 }
1700 SystemMessage::IrohNodeAddr => {
1701 let node_addr = context
1702 .get_or_try_init_peer_channel()
1703 .await?
1704 .get_node_addr()
1705 .await?;
1706
1707 debug_assert!(node_addr.relay_url().is_some());
1710 headers.push((
1711 HeaderDef::IrohNodeAddr.into(),
1712 mail_builder::headers::text::Text::new(serde_json::to_string(&node_addr)?)
1713 .into(),
1714 ));
1715 }
1716 SystemMessage::CallAccepted => {
1717 headers.push((
1718 "Chat-Content",
1719 mail_builder::headers::raw::Raw::new("call-accepted").into(),
1720 ));
1721 }
1722 SystemMessage::CallEnded => {
1723 headers.push((
1724 "Chat-Content",
1725 mail_builder::headers::raw::Raw::new("call-ended").into(),
1726 ));
1727 }
1728 _ => {}
1729 }
1730
1731 if let Some(grpimage) = grpimage {
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;