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::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 =
471 Self::should_attach_selfavatar(context, &msg).await && encryption_pubkeys.is_some();
472
473 ensure_and_debug_assert!(
474 member_timestamps.is_empty()
475 || to.len() + past_members.len() == member_timestamps.len(),
476 "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
477 to.len(),
478 past_members.len(),
479 member_timestamps.len(),
480 );
481 let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
482 let factory = MimeFactory {
483 from_addr,
484 from_displayname,
485 sender_displayname,
486 selfstatus,
487 recipients,
488 encryption_pubkeys,
489 to,
490 past_members,
491 member_fingerprints,
492 member_timestamps,
493 timestamp: msg.timestamp_sort,
494 loaded: Loaded::Message { msg, chat },
495 in_reply_to,
496 references,
497 req_mdn,
498 last_added_location_id: None,
499 sync_ids_to_delete: None,
500 attach_selfavatar,
501 webxdc_topic,
502 };
503 Ok(factory)
504 }
505
506 pub async fn from_mdn(
507 context: &Context,
508 from_id: ContactId,
509 rfc724_mid: String,
510 additional_msg_ids: Vec<String>,
511 ) -> Result<MimeFactory> {
512 let contact = Contact::get_by_id(context, from_id).await?;
513 let from_addr = context.get_primary_self_addr().await?;
514 let timestamp = create_smeared_timestamp(context);
515
516 let addr = contact.get_addr().to_string();
517 let encryption_pubkeys = if contact.is_key_contact() {
518 if let Some(key) = contact.public_key(context).await? {
519 Some(vec![(addr.clone(), key)])
520 } else {
521 Some(Vec::new())
522 }
523 } else {
524 None
525 };
526
527 let res = MimeFactory {
528 from_addr,
529 from_displayname: "".to_string(),
530 sender_displayname: None,
531 selfstatus: "".to_string(),
532 recipients: vec![addr],
533 encryption_pubkeys,
534 to: vec![("".to_string(), contact.get_addr().to_string())],
535 past_members: vec![],
536 member_fingerprints: vec![],
537 member_timestamps: vec![],
538 timestamp,
539 loaded: Loaded::Mdn {
540 rfc724_mid,
541 additional_msg_ids,
542 },
543 in_reply_to: String::default(),
544 references: Vec::new(),
545 req_mdn: false,
546 last_added_location_id: None,
547 sync_ids_to_delete: None,
548 attach_selfavatar: false,
549 webxdc_topic: None,
550 };
551
552 Ok(res)
553 }
554
555 fn should_skip_autocrypt(&self) -> bool {
556 match &self.loaded {
557 Loaded::Message { msg, .. } => {
558 msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
559 }
560 Loaded::Mdn { .. } => true,
561 }
562 }
563
564 fn should_attach_profile_data(msg: &Message) -> bool {
565 msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
566 let step = msg.param.get(Param::Arg).unwrap_or_default();
567 step == "vg-request-with-auth"
573 || step == "vc-request-with-auth"
574 || step == "vg-member-added"
579 || step == "vc-contact-confirm"
580 }
581 }
582
583 async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
584 Self::should_attach_profile_data(msg)
585 && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
586 Ok(should) => should,
587 Err(err) => {
588 warn!(
589 context,
590 "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
591 );
592 false
593 }
594 }
595 }
596
597 fn grpimage(&self) -> Option<String> {
598 match &self.loaded {
599 Loaded::Message { chat, msg } => {
600 let cmd = msg.param.get_cmd();
601
602 match cmd {
603 SystemMessage::MemberAddedToGroup => {
604 return chat.param.get(Param::ProfileImage).map(Into::into);
605 }
606 SystemMessage::GroupImageChanged => {
607 return msg.param.get(Param::Arg).map(Into::into);
608 }
609 _ => {}
610 }
611
612 if msg
613 .param
614 .get_bool(Param::AttachGroupImage)
615 .unwrap_or_default()
616 {
617 return chat.param.get(Param::ProfileImage).map(Into::into);
618 }
619
620 None
621 }
622 Loaded::Mdn { .. } => None,
623 }
624 }
625
626 async fn subject_str(&self, context: &Context) -> Result<String> {
627 let subject = match &self.loaded {
628 Loaded::Message { chat, msg } => {
629 let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
630
631 if !msg.subject.is_empty() {
632 return Ok(msg.subject.clone());
633 }
634
635 if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
636 && quoted_msg_subject.is_none_or_empty()
637 {
638 let re = if self.in_reply_to.is_empty() {
639 ""
640 } else {
641 "Re: "
642 };
643 return Ok(format!("{}{}", re, chat.name));
644 }
645
646 let parent_subject = if quoted_msg_subject.is_none_or_empty() {
647 chat.param.get(Param::LastSubject)
648 } else {
649 quoted_msg_subject.as_deref()
650 };
651 if let Some(last_subject) = parent_subject {
652 return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
653 }
654
655 let self_name = match Self::should_attach_profile_data(msg) {
656 true => context.get_config(Config::Displayname).await?,
657 false => None,
658 };
659 let self_name = &match self_name {
660 Some(name) => name,
661 None => context.get_config(Config::Addr).await?.unwrap_or_default(),
662 };
663 stock_str::subject_for_new_contact(context, self_name).await
664 }
665 Loaded::Mdn { .. } => "Receipt Notification".to_string(), };
667
668 Ok(subject)
669 }
670
671 pub fn recipients(&self) -> Vec<String> {
672 self.recipients.clone()
673 }
674
675 pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
678 let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
679
680 let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
681
682 let mut to: Vec<Address<'static>> = Vec::new();
683 for (name, addr) in &self.to {
684 to.push(Address::new_address(
685 if name.is_empty() {
686 None
687 } else {
688 Some(name.to_string())
689 },
690 addr.clone(),
691 ));
692 }
693
694 let mut past_members: Vec<Address<'static>> = Vec::new(); for (name, addr) in &self.past_members {
696 past_members.push(Address::new_address(
697 if name.is_empty() {
698 None
699 } else {
700 Some(name.to_string())
701 },
702 addr.clone(),
703 ));
704 }
705
706 ensure_and_debug_assert!(
707 self.member_timestamps.is_empty()
708 || to.len() + past_members.len() == self.member_timestamps.len(),
709 "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
710 to.len(),
711 past_members.len(),
712 self.member_timestamps.len(),
713 );
714 if to.is_empty() {
715 to.push(hidden_recipients());
716 }
717
718 headers.push(("From", from.into()));
721
722 if let Some(sender_displayname) = &self.sender_displayname {
723 let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
724 headers.push(("Sender", sender.into()));
725 }
726 headers.push((
727 "To",
728 mail_builder::headers::address::Address::new_list(to.clone()).into(),
729 ));
730 if !past_members.is_empty() {
731 headers.push((
732 "Chat-Group-Past-Members",
733 mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
734 ));
735 }
736
737 if let Loaded::Message { chat, .. } = &self.loaded
738 && chat.typ == Chattype::Group
739 {
740 if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await? {
741 headers.push((
742 "Chat-Group-Member-Timestamps",
743 mail_builder::headers::raw::Raw::new(
744 self.member_timestamps
745 .iter()
746 .map(|ts| ts.to_string())
747 .collect::<Vec<String>>()
748 .join(" "),
749 )
750 .into(),
751 ));
752 }
753
754 if !self.member_fingerprints.is_empty() {
755 headers.push((
756 "Chat-Group-Member-Fpr",
757 mail_builder::headers::raw::Raw::new(
758 self.member_fingerprints
759 .iter()
760 .map(|fp| fp.to_string())
761 .collect::<Vec<String>>()
762 .join(" "),
763 )
764 .into(),
765 ));
766 }
767 }
768
769 let subject_str = self.subject_str(context).await?;
770 headers.push((
771 "Subject",
772 mail_builder::headers::text::Text::new(subject_str.to_string()).into(),
773 ));
774
775 let date = chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp, 0)
776 .unwrap()
777 .to_rfc2822();
778 headers.push(("Date", mail_builder::headers::raw::Raw::new(date).into()));
779
780 let rfc724_mid = match &self.loaded {
781 Loaded::Message { msg, .. } => msg.rfc724_mid.clone(),
782 Loaded::Mdn { .. } => create_outgoing_rfc724_mid(),
783 };
784 headers.push((
785 "Message-ID",
786 mail_builder::headers::message_id::MessageId::new(rfc724_mid.clone()).into(),
787 ));
788
789 if !self.in_reply_to.is_empty() {
791 headers.push((
792 "In-Reply-To",
793 mail_builder::headers::message_id::MessageId::new(self.in_reply_to.clone()).into(),
794 ));
795 }
796 if !self.references.is_empty() {
797 headers.push((
798 "References",
799 mail_builder::headers::message_id::MessageId::<'static>::new_list(
800 self.references.iter().map(|s| s.to_string()),
801 )
802 .into(),
803 ));
804 }
805
806 if let Loaded::Mdn { .. } = self.loaded {
808 headers.push((
809 "Auto-Submitted",
810 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
811 ));
812 } else if context.get_config_bool(Config::Bot).await? {
813 headers.push((
814 "Auto-Submitted",
815 mail_builder::headers::raw::Raw::new("auto-generated".to_string()).into(),
816 ));
817 } else if let Loaded::Message { msg, .. } = &self.loaded
818 && msg.param.get_cmd() == SystemMessage::SecurejoinMessage
819 {
820 let step = msg.param.get(Param::Arg).unwrap_or_default();
821 if step != "vg-request" && step != "vc-request" {
822 headers.push((
823 "Auto-Submitted",
824 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
825 ));
826 }
827 }
828
829 if let Loaded::Message { msg, chat } = &self.loaded
830 && (chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast)
831 {
832 headers.push((
833 "Chat-List-ID",
834 mail_builder::headers::text::Text::new(format!("{} <{}>", chat.name, chat.grpid))
835 .into(),
836 ));
837
838 if msg.param.get_cmd() == SystemMessage::MemberAddedToGroup
839 && let Some(secret) = msg.param.get(PARAM_BROADCAST_SECRET)
840 {
841 headers.push((
842 "Chat-Broadcast-Secret",
843 mail_builder::headers::text::Text::new(secret.to_string()).into(),
844 ));
845 }
846 }
847
848 if let Loaded::Message { msg, .. } = &self.loaded {
849 if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
850 headers.push((
851 "Chat-Edit",
852 mail_builder::headers::message_id::MessageId::new(
853 original_rfc724_mid.to_string(),
854 )
855 .into(),
856 ));
857 } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
858 headers.push((
859 "Chat-Delete",
860 mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
861 .into(),
862 ));
863 }
864 }
865
866 headers.push((
868 "Chat-Version",
869 mail_builder::headers::raw::Raw::new("1.0").into(),
870 ));
871
872 if self.req_mdn {
873 headers.push((
877 "Chat-Disposition-Notification-To",
878 mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
879 ));
880 }
881
882 let grpimage = self.grpimage();
883 let skip_autocrypt = self.should_skip_autocrypt();
884 let encrypt_helper = EncryptHelper::new(context).await?;
885
886 if !skip_autocrypt {
887 let aheader = encrypt_helper.get_aheader().to_string();
889 headers.push((
890 "Autocrypt",
891 mail_builder::headers::raw::Raw::new(aheader).into(),
892 ));
893 }
894
895 let is_encrypted = self.encryption_pubkeys.is_some();
896
897 if let Loaded::Message { msg, .. } = &self.loaded {
901 let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
902 if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
903 headers.push((
904 "Ephemeral-Timer",
905 mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
906 ));
907 }
908 }
909
910 let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
911 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
912 } else {
913 false
914 };
915
916 let message: MimePart<'static> = match &self.loaded {
917 Loaded::Message { msg, .. } => {
918 let msg = msg.clone();
919 let (main_part, mut parts) = self
920 .render_message(context, &mut headers, &grpimage, is_encrypted)
921 .await?;
922 if parts.is_empty() {
923 main_part
925 } else {
926 parts.insert(0, main_part);
927
928 if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
930 MimePart::new("multipart/report; report-type=multi-device-sync", parts)
931 } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
932 MimePart::new("multipart/report; report-type=status-update", parts)
933 } else {
934 MimePart::new("multipart/mixed", parts)
935 }
936 }
937 }
938 Loaded::Mdn { .. } => self.render_mdn()?,
939 };
940
941 let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
950
951 let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
964
965 let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
974
975 unprotected_headers.push((
977 "MIME-Version",
978 mail_builder::headers::raw::Raw::new("1.0").into(),
979 ));
980 for header @ (original_header_name, _header_value) in &headers {
981 let header_name = original_header_name.to_lowercase();
982 if header_name == "message-id" {
983 unprotected_headers.push(header.clone());
984 hidden_headers.push(header.clone());
985 } else if is_hidden(&header_name) {
986 hidden_headers.push(header.clone());
987 } else if header_name == "from" {
988 if is_encrypted || !is_securejoin_message {
990 protected_headers.push(header.clone());
991 }
992
993 unprotected_headers.push((
994 original_header_name,
995 Address::new_address(None::<&'static str>, self.from_addr.clone()).into(),
996 ));
997 } else if header_name == "to" {
998 protected_headers.push(header.clone());
999 if is_encrypted {
1000 unprotected_headers.push(("To", hidden_recipients().into()));
1001 } else {
1002 unprotected_headers.push(header.clone());
1003 }
1004 } else if header_name == "chat-broadcast-secret" {
1005 if is_encrypted {
1006 protected_headers.push(header.clone());
1007 } else {
1008 bail!("Message is unecrypted, cannot include broadcast secret");
1009 }
1010 } else if is_encrypted && header_name == "date" {
1011 protected_headers.push(header.clone());
1012
1013 let timestamp_offset = rand::random_range(0..518400);
1035 let protected_timestamp = self.timestamp.saturating_sub(timestamp_offset);
1036 let unprotected_date =
1037 chrono::DateTime::<chrono::Utc>::from_timestamp(protected_timestamp, 0)
1038 .unwrap()
1039 .to_rfc2822();
1040 unprotected_headers.push((
1041 "Date",
1042 mail_builder::headers::raw::Raw::new(unprotected_date).into(),
1043 ));
1044 } else if is_encrypted {
1045 protected_headers.push(header.clone());
1046
1047 match header_name.as_str() {
1048 "subject" => {
1049 unprotected_headers.push((
1050 "Subject",
1051 mail_builder::headers::raw::Raw::new("[...]").into(),
1052 ));
1053 }
1054 "in-reply-to"
1055 | "references"
1056 | "auto-submitted"
1057 | "chat-version"
1058 | "autocrypt-setup-message" => {
1059 unprotected_headers.push(header.clone());
1060 }
1061 _ => {
1062 }
1064 }
1065 } else {
1066 protected_headers.push(header.clone());
1070 unprotected_headers.push(header.clone())
1071 }
1072 }
1073
1074 let use_std_header_protection = context
1075 .get_config_bool(Config::StdHeaderProtectionComposing)
1076 .await?;
1077 let outer_message = if let Some(encryption_pubkeys) = self.encryption_pubkeys {
1078 let message = protected_headers
1080 .into_iter()
1081 .fold(message, |message, (header, value)| {
1082 message.header(header, value)
1083 });
1084
1085 let mut message: MimePart<'static> = hidden_headers
1087 .into_iter()
1088 .fold(message, |message, (header, value)| {
1089 message.header(header, value)
1090 });
1091
1092 if use_std_header_protection {
1093 message = unprotected_headers
1094 .iter()
1095 .filter(|(name, _)| {
1098 !(name.eq_ignore_ascii_case("mime-version")
1099 || name.eq_ignore_ascii_case("content-type")
1100 || name.eq_ignore_ascii_case("content-transfer-encoding")
1101 || name.eq_ignore_ascii_case("content-disposition"))
1102 })
1103 .fold(message, |message, (name, value)| {
1104 message.header(format!("HP-Outer: {name}"), value.clone())
1105 });
1106 }
1107
1108 let multiple_recipients =
1110 encryption_pubkeys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1111
1112 let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1113 let now = time();
1114
1115 match &self.loaded {
1116 Loaded::Message { chat, msg } => {
1117 if !should_hide_recipients(msg, chat) {
1118 for (addr, key) in &encryption_pubkeys {
1119 let fingerprint = key.dc_fingerprint().hex();
1120 let cmd = msg.param.get_cmd();
1121 let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1122 || cmd == SystemMessage::SecurejoinMessage
1123 || multiple_recipients && {
1124 let gossiped_timestamp: Option<i64> = context
1125 .sql
1126 .query_get_value(
1127 "SELECT timestamp
1128 FROM gossip_timestamp
1129 WHERE chat_id=? AND fingerprint=?",
1130 (chat.id, &fingerprint),
1131 )
1132 .await?;
1133
1134 gossip_period == 0
1141 || gossiped_timestamp
1142 .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1143 };
1144
1145 let verifier_id: Option<u32> = context
1146 .sql
1147 .query_get_value(
1148 "SELECT verifier FROM contacts WHERE fingerprint=?",
1149 (&fingerprint,),
1150 )
1151 .await?;
1152
1153 let is_verified =
1154 verifier_id.is_some_and(|verifier_id| verifier_id != 0);
1155
1156 if !should_do_gossip {
1157 continue;
1158 }
1159
1160 let header = Aheader {
1161 addr: addr.clone(),
1162 public_key: key.clone(),
1163 prefer_encrypt: EncryptPreference::NoPreference,
1166 verified: is_verified,
1167 }
1168 .to_string();
1169
1170 message = message.header(
1171 "Autocrypt-Gossip",
1172 mail_builder::headers::raw::Raw::new(header),
1173 );
1174
1175 context
1176 .sql
1177 .execute(
1178 "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1179 VALUES (?, ?, ?)
1180 ON CONFLICT (chat_id, fingerprint)
1181 DO UPDATE SET timestamp=excluded.timestamp",
1182 (chat.id, &fingerprint, now),
1183 )
1184 .await?;
1185 }
1186 }
1187 }
1188 Loaded::Mdn { .. } => {
1189 }
1191 }
1192
1193 for (h, v) in &mut message.headers {
1195 if h == "Content-Type"
1196 && let mail_builder::headers::HeaderType::ContentType(ct) = v
1197 {
1198 let mut ct_new = ct.clone();
1199 ct_new = ct_new.attribute("protected-headers", "v1");
1200 if use_std_header_protection {
1201 ct_new = ct_new.attribute("hp", "cipher");
1202 }
1203 *ct = ct_new;
1204 break;
1205 }
1206 }
1207
1208 let compress = match &self.loaded {
1212 Loaded::Message { msg, .. } => {
1213 msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1214 }
1215 Loaded::Mdn { .. } => true,
1216 };
1217
1218 let shared_secret: Option<String> = match &self.loaded {
1219 Loaded::Message { chat, msg }
1220 if should_encrypt_with_broadcast_secret(msg, chat) =>
1221 {
1222 let secret = load_broadcast_secret(context, chat.id).await?;
1223 if secret.is_none() {
1224 let text = BROADCAST_INCOMPATIBILITY_MSG;
1229 chat::add_info_msg(context, chat.id, text).await?;
1230 bail!(text);
1231 }
1232 secret
1233 }
1234 _ => None,
1235 };
1236
1237 let anonymous_recipients = false;
1247
1248 if context.get_config_bool(Config::TestHooks).await?
1249 && let Some(hook) = &*context.pre_encrypt_mime_hook.lock()
1250 {
1251 message = hook(context, message);
1252 }
1253
1254 let encrypted = if let Some(shared_secret) = shared_secret {
1255 encrypt_helper
1256 .encrypt_symmetrically(context, &shared_secret, message, compress)
1257 .await?
1258 } else {
1259 let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1264 encryption_keyring
1265 .extend(encryption_pubkeys.iter().map(|(_addr, key)| (*key).clone()));
1266
1267 encrypt_helper
1268 .encrypt(
1269 context,
1270 encryption_keyring,
1271 message,
1272 compress,
1273 anonymous_recipients,
1274 )
1275 .await?
1276 };
1277
1278 let encrypted = encrypted + "\n";
1282
1283 MimePart::new(
1285 "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1286 vec![
1287 MimePart::new("application/pgp-encrypted", "Version: 1\r\n").header(
1289 "Content-Description",
1290 mail_builder::headers::raw::Raw::new("PGP/MIME version identification"),
1291 ),
1292 MimePart::new(
1294 "application/octet-stream; name=\"encrypted.asc\"",
1295 encrypted,
1296 )
1297 .header(
1298 "Content-Description",
1299 mail_builder::headers::raw::Raw::new("OpenPGP encrypted message"),
1300 )
1301 .header(
1302 "Content-Disposition",
1303 mail_builder::headers::raw::Raw::new("inline; filename=\"encrypted.asc\";"),
1304 ),
1305 ],
1306 )
1307 } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1308 message
1317 } else {
1318 let message = hidden_headers
1319 .into_iter()
1320 .fold(message, |message, (header, value)| {
1321 message.header(header, value)
1322 });
1323 let message = MimePart::new("multipart/mixed", vec![message]);
1324 let mut message = protected_headers
1325 .iter()
1326 .fold(message, |message, (header, value)| {
1327 message.header(*header, value.clone())
1328 });
1329
1330 if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
1331 let protected: HashSet<&str> =
1333 HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1334 unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1335
1336 message
1337 } else {
1338 for (h, v) in &mut message.headers {
1339 if h == "Content-Type"
1340 && let mail_builder::headers::HeaderType::ContentType(ct) = v
1341 {
1342 let mut ct_new = ct.clone();
1343 ct_new = ct_new.attribute("protected-headers", "v1");
1344 if use_std_header_protection {
1345 ct_new = ct_new.attribute("hp", "clear");
1346 }
1347 *ct = ct_new;
1348 break;
1349 }
1350 }
1351
1352 let signature = encrypt_helper.sign(context, &message).await?;
1353 MimePart::new(
1354 "multipart/signed; protocol=\"application/pgp-signature\"; protected",
1355 vec![
1356 message,
1357 MimePart::new(
1358 "application/pgp-signature; name=\"signature.asc\"",
1359 signature,
1360 )
1361 .header(
1362 "Content-Description",
1363 mail_builder::headers::raw::Raw::<'static>::new(
1364 "OpenPGP digital signature",
1365 ),
1366 )
1367 .attachment("signature"),
1368 ],
1369 )
1370 }
1371 };
1372
1373 let outer_message = unprotected_headers
1375 .into_iter()
1376 .fold(outer_message, |message, (header, value)| {
1377 message.header(header, value)
1378 });
1379
1380 let MimeFactory {
1381 last_added_location_id,
1382 ..
1383 } = self;
1384
1385 let mut buffer = Vec::new();
1386 let cursor = Cursor::new(&mut buffer);
1387 outer_message.clone().write_part(cursor).ok();
1388 let message = String::from_utf8_lossy(&buffer).to_string();
1389
1390 Ok(RenderedEmail {
1391 message,
1392 is_encrypted,
1394 last_added_location_id,
1395 sync_ids_to_delete: self.sync_ids_to_delete,
1396 rfc724_mid,
1397 subject: subject_str,
1398 })
1399 }
1400
1401 fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1403 let Loaded::Message { msg, .. } = &self.loaded else {
1404 return None;
1405 };
1406
1407 let latitude = msg.param.get_float(Param::SetLatitude)?;
1408 let longitude = msg.param.get_float(Param::SetLongitude)?;
1409
1410 let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1411 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1412 .attachment("message.kml");
1413 Some(part)
1414 }
1415
1416 async fn get_location_kml_part(
1418 &mut self,
1419 context: &Context,
1420 ) -> Result<Option<MimePart<'static>>> {
1421 let Loaded::Message { msg, .. } = &self.loaded else {
1422 return Ok(None);
1423 };
1424
1425 let Some((kml_content, last_added_location_id)) =
1426 location::get_kml(context, msg.chat_id).await?
1427 else {
1428 return Ok(None);
1429 };
1430
1431 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1432 .attachment("location.kml");
1433 if !msg.param.exists(Param::SetLatitude) {
1434 self.last_added_location_id = Some(last_added_location_id);
1436 }
1437 Ok(Some(part))
1438 }
1439
1440 async fn render_message(
1441 &mut self,
1442 context: &Context,
1443 headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1444 grpimage: &Option<String>,
1445 is_encrypted: bool,
1446 ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1447 let Loaded::Message { chat, msg } = &self.loaded else {
1448 bail!("Attempt to render MDN as a message");
1449 };
1450 let chat = chat.clone();
1451 let msg = msg.clone();
1452 let command = msg.param.get_cmd();
1453 let mut placeholdertext = None;
1454
1455 let send_verified_headers = match chat.typ {
1456 Chattype::Single => true,
1457 Chattype::Group => true,
1458 Chattype::Mailinglist => false,
1460 Chattype::OutBroadcast | Chattype::InBroadcast => false,
1461 };
1462
1463 if send_verified_headers {
1464 let was_protected: bool = context
1465 .sql
1466 .query_get_value("SELECT protected FROM chats WHERE id=?", (chat.id,))
1467 .await?
1468 .unwrap_or_default();
1469
1470 if was_protected {
1471 let unverified_member_exists = context
1472 .sql
1473 .exists(
1474 "SELECT COUNT(*)
1475 FROM contacts, chats_contacts
1476 WHERE chats_contacts.contact_id=contacts.id AND chats_contacts.chat_id=?
1477 AND contacts.id>9
1478 AND contacts.verifier=0",
1479 (chat.id,),
1480 )
1481 .await?;
1482
1483 if !unverified_member_exists {
1484 headers.push((
1485 "Chat-Verified",
1486 mail_builder::headers::raw::Raw::new("1").into(),
1487 ));
1488 }
1489 }
1490 }
1491
1492 if chat.typ == Chattype::Group {
1493 if !chat.grpid.is_empty() {
1495 headers.push((
1496 "Chat-Group-ID",
1497 mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1498 ));
1499 }
1500 }
1501
1502 if chat.typ == Chattype::Group
1503 || chat.typ == Chattype::OutBroadcast
1504 || chat.typ == Chattype::InBroadcast
1505 {
1506 headers.push((
1507 "Chat-Group-Name",
1508 mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1509 ));
1510 if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1511 headers.push((
1512 "Chat-Group-Name-Timestamp",
1513 mail_builder::headers::text::Text::new(ts.to_string()).into(),
1514 ));
1515 }
1516
1517 match command {
1518 SystemMessage::MemberRemovedFromGroup => {
1519 let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1520 let fingerprint_to_remove = msg.param.get(Param::Arg4).unwrap_or_default();
1521
1522 if email_to_remove
1523 == context
1524 .get_config(Config::ConfiguredAddr)
1525 .await?
1526 .unwrap_or_default()
1527 {
1528 placeholdertext = Some("I left the group.".to_string());
1529 } else {
1530 placeholdertext = Some(format!("I removed member {email_to_remove}."));
1531 };
1532
1533 if !email_to_remove.is_empty() {
1534 headers.push((
1535 "Chat-Group-Member-Removed",
1536 mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1537 .into(),
1538 ));
1539 }
1540
1541 if !fingerprint_to_remove.is_empty() {
1542 headers.push((
1543 "Chat-Group-Member-Removed-Fpr",
1544 mail_builder::headers::raw::Raw::new(fingerprint_to_remove.to_string())
1545 .into(),
1546 ));
1547 }
1548 }
1549 SystemMessage::MemberAddedToGroup => {
1550 let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1551 let fingerprint_to_add = msg.param.get(Param::Arg4).unwrap_or_default();
1552
1553 placeholdertext = Some(format!("I added member {email_to_add}."));
1554
1555 if !email_to_add.is_empty() {
1556 headers.push((
1557 "Chat-Group-Member-Added",
1558 mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1559 ));
1560 }
1561 if !fingerprint_to_add.is_empty() {
1562 headers.push((
1563 "Chat-Group-Member-Added-Fpr",
1564 mail_builder::headers::raw::Raw::new(fingerprint_to_add.to_string())
1565 .into(),
1566 ));
1567 }
1568 if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1569 let step = "vg-member-added";
1570 info!(context, "Sending secure-join message {:?}.", step);
1571 headers.push((
1572 "Secure-Join",
1573 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1574 ));
1575 }
1576 }
1577 SystemMessage::GroupNameChanged => {
1578 let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1579 headers.push((
1580 "Chat-Group-Name-Changed",
1581 mail_builder::headers::text::Text::new(old_name).into(),
1582 ));
1583 }
1584 SystemMessage::GroupImageChanged => {
1585 headers.push((
1586 "Chat-Content",
1587 mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1588 ));
1589 if grpimage.is_none() && is_encrypted {
1590 headers.push((
1591 "Chat-Group-Avatar",
1592 mail_builder::headers::raw::Raw::new("0").into(),
1593 ));
1594 }
1595 }
1596 _ => {}
1597 }
1598 }
1599
1600 match command {
1601 SystemMessage::LocationStreamingEnabled => {
1602 headers.push((
1603 "Chat-Content",
1604 mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1605 ));
1606 }
1607 SystemMessage::EphemeralTimerChanged => {
1608 headers.push((
1609 "Chat-Content",
1610 mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1611 ));
1612 }
1613 SystemMessage::LocationOnly
1614 | SystemMessage::MultiDeviceSync
1615 | SystemMessage::WebxdcStatusUpdate => {
1616 headers.push((
1625 "Auto-Submitted",
1626 mail_builder::headers::raw::Raw::new("auto-generated").into(),
1627 ));
1628 }
1629 SystemMessage::AutocryptSetupMessage => {
1630 headers.push((
1631 "Autocrypt-Setup-Message",
1632 mail_builder::headers::raw::Raw::new("v1").into(),
1633 ));
1634
1635 placeholdertext = Some(ASM_SUBJECT.to_string());
1636 }
1637 SystemMessage::SecurejoinMessage => {
1638 let step = msg.param.get(Param::Arg).unwrap_or_default();
1639 if !step.is_empty() {
1640 info!(context, "Sending secure-join message {step:?}.");
1641 headers.push((
1642 "Secure-Join",
1643 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1644 ));
1645
1646 let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1647 if !param2.is_empty() {
1648 headers.push((
1649 if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1650 "Secure-Join-Auth"
1651 } else {
1652 "Secure-Join-Invitenumber"
1653 },
1654 mail_builder::headers::text::Text::new(param2.to_string()).into(),
1655 ));
1656 }
1657
1658 let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1659 if !fingerprint.is_empty() {
1660 headers.push((
1661 "Secure-Join-Fingerprint",
1662 mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1663 ));
1664 }
1665 if let Some(id) = msg.param.get(Param::Arg4) {
1666 headers.push((
1667 "Secure-Join-Group",
1668 mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1669 ));
1670 };
1671 }
1672 }
1673 SystemMessage::ChatProtectionEnabled => {
1674 headers.push((
1675 "Chat-Content",
1676 mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1677 ));
1678 }
1679 SystemMessage::ChatProtectionDisabled => {
1680 headers.push((
1681 "Chat-Content",
1682 mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1683 ));
1684 }
1685 SystemMessage::IrohNodeAddr => {
1686 let node_addr = context
1687 .get_or_try_init_peer_channel()
1688 .await?
1689 .get_node_addr()
1690 .await?;
1691
1692 debug_assert!(node_addr.relay_url().is_some());
1695 headers.push((
1696 HeaderDef::IrohNodeAddr.into(),
1697 mail_builder::headers::text::Text::new(serde_json::to_string(&node_addr)?)
1698 .into(),
1699 ));
1700 }
1701 SystemMessage::CallAccepted => {
1702 headers.push((
1703 "Chat-Content",
1704 mail_builder::headers::raw::Raw::new("call-accepted").into(),
1705 ));
1706 }
1707 SystemMessage::CallEnded => {
1708 headers.push((
1709 "Chat-Content",
1710 mail_builder::headers::raw::Raw::new("call-ended").into(),
1711 ));
1712 }
1713 _ => {}
1714 }
1715
1716 if let Some(grpimage) = grpimage
1717 && is_encrypted
1718 {
1719 info!(context, "setting group image '{}'", grpimage);
1720 let avatar = build_avatar_file(context, grpimage)
1721 .await
1722 .context("Cannot attach group image")?;
1723 headers.push((
1724 "Chat-Group-Avatar",
1725 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1726 ));
1727 }
1728
1729 if msg.viewtype == Viewtype::Sticker {
1730 headers.push((
1731 "Chat-Content",
1732 mail_builder::headers::raw::Raw::new("sticker").into(),
1733 ));
1734 } else if msg.viewtype == Viewtype::Call {
1735 headers.push((
1736 "Chat-Content",
1737 mail_builder::headers::raw::Raw::new("call").into(),
1738 ));
1739 placeholdertext = Some(
1740 "[This is a 'Call'. The sender uses an experiment not supported on your version yet]".to_string(),
1741 );
1742 }
1743
1744 if let Some(offer) = msg.param.get(Param::WebrtcRoom) {
1745 headers.push((
1746 "Chat-Webrtc-Room",
1747 mail_builder::headers::raw::Raw::new(b_encode(offer)).into(),
1748 ));
1749 } else if let Some(answer) = msg.param.get(Param::WebrtcAccepted) {
1750 headers.push((
1751 "Chat-Webrtc-Accepted",
1752 mail_builder::headers::raw::Raw::new(b_encode(answer)).into(),
1753 ));
1754 }
1755
1756 if msg.viewtype == Viewtype::Voice
1757 || msg.viewtype == Viewtype::Audio
1758 || msg.viewtype == Viewtype::Video
1759 {
1760 if msg.viewtype == Viewtype::Voice {
1761 headers.push((
1762 "Chat-Voice-Message",
1763 mail_builder::headers::raw::Raw::new("1").into(),
1764 ));
1765 }
1766 let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1767 if duration_ms > 0 {
1768 let dur = duration_ms.to_string();
1769 headers.push((
1770 "Chat-Duration",
1771 mail_builder::headers::raw::Raw::new(dur).into(),
1772 ));
1773 }
1774 }
1775
1776 let afwd_email = msg.param.exists(Param::Forwarded);
1782 let fwdhint = if afwd_email {
1783 Some(
1784 "---------- Forwarded message ----------\r\n\
1785 From: Delta Chat\r\n\
1786 \r\n"
1787 .to_string(),
1788 )
1789 } else {
1790 None
1791 };
1792
1793 let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1794
1795 let mut quoted_text = None;
1796 if let Some(msg_quoted_text) = msg.quoted_text() {
1797 let mut some_quoted_text = String::new();
1798 for quoted_line in msg_quoted_text.split('\n') {
1799 some_quoted_text += "> ";
1800 some_quoted_text += quoted_line;
1801 some_quoted_text += "\r\n";
1802 }
1803 some_quoted_text += "\r\n";
1804 quoted_text = Some(some_quoted_text)
1805 }
1806
1807 if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1808 quoted_text = Some("> ...\r\n\r\n".to_string());
1810 }
1811 if quoted_text.is_none() && final_text.starts_with('>') {
1812 quoted_text = Some("\r\n".to_string());
1815 }
1816
1817 let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1818
1819 let footer = if is_reaction { "" } else { &self.selfstatus };
1820
1821 let message_text = format!(
1822 "{}{}{}{}{}{}",
1823 fwdhint.unwrap_or_default(),
1824 quoted_text.unwrap_or_default(),
1825 escape_message_footer_marks(final_text),
1826 if !final_text.is_empty() && !footer.is_empty() {
1827 "\r\n\r\n"
1828 } else {
1829 ""
1830 },
1831 if !footer.is_empty() { "-- \r\n" } else { "" },
1832 footer
1833 );
1834
1835 let mut main_part = MimePart::new("text/plain", message_text);
1836 if is_reaction {
1837 main_part = main_part.header(
1838 "Content-Disposition",
1839 mail_builder::headers::raw::Raw::new("reaction"),
1840 );
1841 }
1842
1843 let mut parts = Vec::new();
1844
1845 if msg.has_html() {
1848 let html = if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded) {
1849 MsgId::new(orig_msg_id.try_into()?)
1850 .get_html(context)
1851 .await?
1852 } else {
1853 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1854 };
1855 if let Some(html) = html {
1856 main_part = MimePart::new(
1857 "multipart/alternative",
1858 vec![main_part, MimePart::new("text/html", html)],
1859 )
1860 }
1861 }
1862
1863 if msg.viewtype.has_file() {
1865 let file_part = build_body_file(context, &msg).await?;
1866 parts.push(file_part);
1867 }
1868
1869 if let Some(msg_kml_part) = self.get_message_kml_part() {
1870 parts.push(msg_kml_part);
1871 }
1872
1873 if location::is_sending_locations_to_chat(context, Some(msg.chat_id)).await?
1874 && let Some(part) = self.get_location_kml_part(context).await?
1875 {
1876 parts.push(part);
1877 }
1878
1879 if command == SystemMessage::MultiDeviceSync {
1882 let json = msg.param.get(Param::Arg).unwrap_or_default();
1883 let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1884 parts.push(context.build_sync_part(json.to_string()));
1885 self.sync_ids_to_delete = Some(ids.to_string());
1886 } else if command == SystemMessage::WebxdcStatusUpdate {
1887 let json = msg.param.get(Param::Arg).unwrap_or_default();
1888 parts.push(context.build_status_update_part(json));
1889 } else if msg.viewtype == Viewtype::Webxdc {
1890 let topic = self
1891 .webxdc_topic
1892 .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1893 .unwrap_or(create_iroh_header(context, msg.id).await?);
1894 headers.push((
1895 HeaderDef::IrohGossipTopic.get_headername(),
1896 mail_builder::headers::raw::Raw::new(topic).into(),
1897 ));
1898 if let (Some(json), _) = context
1899 .render_webxdc_status_update_object(
1900 msg.id,
1901 StatusUpdateSerial::MIN,
1902 StatusUpdateSerial::MAX,
1903 None,
1904 )
1905 .await?
1906 {
1907 parts.push(context.build_status_update_part(&json));
1908 }
1909 }
1910
1911 if self.attach_selfavatar {
1912 match context.get_config(Config::Selfavatar).await? {
1913 Some(path) => match build_avatar_file(context, &path).await {
1914 Ok(avatar) => headers.push((
1915 "Chat-User-Avatar",
1916 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1917 )),
1918 Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1919 },
1920 None => headers.push((
1921 "Chat-User-Avatar",
1922 mail_builder::headers::raw::Raw::new("0").into(),
1923 )),
1924 }
1925 }
1926
1927 Ok((main_part, parts))
1928 }
1929
1930 fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1932 let Loaded::Mdn {
1935 rfc724_mid,
1936 additional_msg_ids,
1937 } = &self.loaded
1938 else {
1939 bail!("Attempt to render a message as MDN");
1940 };
1941
1942 let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1946
1947 let mut message = MimePart::new(
1948 "multipart/report; report-type=disposition-notification",
1949 vec![text_part],
1950 );
1951
1952 let message_text2 = format!(
1954 "Original-Recipient: rfc822;{}\r\n\
1955 Final-Recipient: rfc822;{}\r\n\
1956 Original-Message-ID: <{}>\r\n\
1957 Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1958 self.from_addr, self.from_addr, rfc724_mid
1959 );
1960
1961 let extension_fields = if additional_msg_ids.is_empty() {
1962 "".to_string()
1963 } else {
1964 "Additional-Message-IDs: ".to_string()
1965 + &additional_msg_ids
1966 .iter()
1967 .map(|mid| render_rfc724_mid(mid))
1968 .collect::<Vec<String>>()
1969 .join(" ")
1970 + "\r\n"
1971 };
1972
1973 message.add_part(MimePart::new(
1974 "message/disposition-notification",
1975 message_text2 + &extension_fields,
1976 ));
1977
1978 Ok(message)
1979 }
1980}
1981
1982fn hidden_recipients() -> Address<'static> {
1983 Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
1984}
1985
1986fn should_encrypt_with_broadcast_secret(msg: &Message, chat: &Chat) -> bool {
1987 chat.typ == Chattype::OutBroadcast && must_have_only_one_recipient(msg, chat).is_none()
1988}
1989
1990fn should_hide_recipients(msg: &Message, chat: &Chat) -> bool {
1991 should_encrypt_with_broadcast_secret(msg, chat)
1992}
1993
1994fn should_encrypt_symmetrically(msg: &Message, chat: &Chat) -> bool {
1995 should_encrypt_with_broadcast_secret(msg, chat)
1996}
1997
1998fn must_have_only_one_recipient<'a>(msg: &'a Message, chat: &Chat) -> Option<Result<&'a str>> {
2003 if chat.typ == Chattype::OutBroadcast
2004 && matches!(
2005 msg.param.get_cmd(),
2006 SystemMessage::MemberRemovedFromGroup | SystemMessage::MemberAddedToGroup
2007 )
2008 {
2009 let Some(fp) = msg.param.get(Param::Arg4) else {
2010 return Some(Err(format_err!("Missing removed/added member")));
2011 };
2012 return Some(Ok(fp));
2013 }
2014 None
2015}
2016
2017async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
2018 let file_name = msg.get_filename().context("msg has no file")?;
2019 let blob = msg
2020 .param
2021 .get_file_blob(context)?
2022 .context("msg has no file")?;
2023 let mimetype = msg
2024 .param
2025 .get(Param::MimeType)
2026 .unwrap_or("application/octet-stream")
2027 .to_string();
2028 let body = fs::read(blob.to_abs_path()).await?;
2029
2030 let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
2036
2037 Ok(mail)
2038}
2039
2040async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
2041 let blob = match path.starts_with("$BLOBDIR/") {
2042 true => BlobObject::from_name(context, path)?,
2043 false => BlobObject::from_path(context, path.as_ref())?,
2044 };
2045 let body = fs::read(blob.to_abs_path()).await?;
2046 let encoded_body = base64::engine::general_purpose::STANDARD
2047 .encode(&body)
2048 .chars()
2049 .enumerate()
2050 .fold(String::new(), |mut res, (i, c)| {
2051 if i % 78 == 77 {
2052 res.push(' ')
2053 }
2054 res.push(c);
2055 res
2056 });
2057 Ok(encoded_body)
2058}
2059
2060fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
2061 let addr_lc = addr.to_lowercase();
2062 recipients
2063 .iter()
2064 .any(|(_, cur)| cur.to_lowercase() == addr_lc)
2065}
2066
2067fn render_rfc724_mid(rfc724_mid: &str) -> String {
2068 let rfc724_mid = rfc724_mid.trim().to_string();
2069
2070 if rfc724_mid.chars().next().unwrap_or_default() == '<' {
2071 rfc724_mid
2072 } else {
2073 format!("<{rfc724_mid}>")
2074 }
2075}
2076
2077fn b_encode(value: &str) -> String {
2083 format!(
2084 "=?utf-8?B?{}?=",
2085 base64::engine::general_purpose::STANDARD.encode(value)
2086 )
2087}
2088
2089#[cfg(test)]
2090mod mimefactory_tests;