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 if fp? != fingerprint {
297 continue;
298 }
299 }
300
301 let public_key_opt = if let Some(public_key_bytes) = &public_key_bytes_opt {
302 Some(SignedPublicKey::from_slice(public_key_bytes)?)
303 } else {
304 None
305 };
306
307 let addr = if id == ContactId::SELF {
308 from_addr.to_string()
309 } else {
310 addr
311 };
312 let name = match attach_profile_data {
313 true => authname,
314 false => "".to_string(),
315 };
316 if add_timestamp >= remove_timestamp {
317 if !recipients_contain_addr(&to, &addr) {
318 if id != ContactId::SELF {
319 recipients.push(addr.clone());
320 }
321 if !undisclosed_recipients {
322 to.push((name, addr.clone()));
323
324 if is_encrypted {
325 if !fingerprint.is_empty() {
326 member_fingerprints.push(fingerprint);
327 } else if id == ContactId::SELF {
328 member_fingerprints.push(self_fingerprint.to_string());
329 } else {
330 ensure_and_debug_assert!(member_fingerprints.is_empty(), "If some past member is a key-contact, all other past members should be key-contacts too");
331 }
332 }
333 member_timestamps.push(add_timestamp);
334 }
335 }
336 recipient_ids.insert(id);
337
338 if let Some(public_key) = public_key_opt {
339 keys.push((addr.clone(), public_key))
340 } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
341 missing_key_addresses.insert(addr.clone());
342 if is_encrypted {
343 warn!(context, "Missing key for {addr}");
344 }
345 }
346 } else if remove_timestamp.saturating_add(60 * 24 * 3600) > now {
347 if !recipients_contain_addr(&past_members, &addr) {
350 if let Some(email_to_remove) = email_to_remove {
351 if email_to_remove == addr {
352 if id != ContactId::SELF {
356 recipients.push(addr.clone());
357 }
358
359 if let Some(public_key) = public_key_opt {
360 keys.push((addr.clone(), public_key))
361 } else if id != ContactId::SELF && !should_encrypt_symmetrically(&msg, &chat) {
362 missing_key_addresses.insert(addr.clone());
363 if is_encrypted {
364 warn!(context, "Missing key for {addr}");
365 }
366 }
367 }
368 }
369 if !undisclosed_recipients {
370 past_members.push((name, addr.clone()));
371 past_member_timestamps.push(remove_timestamp);
372
373 if is_encrypted {
374 if !fingerprint.is_empty() {
375 past_member_fingerprints.push(fingerprint);
376 } else if id == ContactId::SELF {
377 past_member_fingerprints.push(self_fingerprint.to_string());
380 } else {
381 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");
382 }
383 }
384 }
385 }
386 }
387 }
388
389 ensure_and_debug_assert!(
390 member_timestamps.len() >= to.len(),
391 "member_timestamps.len() ({}) < to.len() ({})",
392 member_timestamps.len(), to.len());
393 ensure_and_debug_assert!(
394 member_fingerprints.is_empty() || member_fingerprints.len() >= to.len(),
395 "member_fingerprints.len() ({}) < to.len() ({})",
396 member_fingerprints.len(), to.len());
397
398 if to.len() > 1 {
399 if let Some(position) = to.iter().position(|(_, x)| x == &from_addr) {
400 to.remove(position);
401 member_timestamps.remove(position);
402 if is_encrypted {
403 member_fingerprints.remove(position);
404 }
405 }
406 }
407
408 member_timestamps.extend(past_member_timestamps);
409 if is_encrypted {
410 member_fingerprints.extend(past_member_fingerprints);
411 }
412 Ok(())
413 },
414 )
415 .await?;
416 let recipient_ids: Vec<_> = recipient_ids.into_iter().collect();
417 ContactId::scaleup_origin(context, &recipient_ids, Origin::OutgoingTo).await?;
418
419 if !msg.is_system_message()
420 && msg.param.get_int(Param::Reaction).unwrap_or_default() == 0
421 && context.should_request_mdns().await?
422 {
423 req_mdn = true;
424 }
425
426 encryption_pubkeys = if !is_encrypted {
427 None
428 } else if should_encrypt_symmetrically(&msg, &chat) {
429 Some(Vec::new())
430 } else {
431 if keys.is_empty() && !recipients.is_empty() {
432 bail!("No recipient keys are available, cannot encrypt to {recipients:?}.");
433 }
434
435 if !missing_key_addresses.is_empty() {
437 recipients.retain(|addr| !missing_key_addresses.contains(addr));
438 }
439
440 Some(keys)
441 };
442 }
443
444 let (in_reply_to, references) = context
445 .sql
446 .query_row(
447 "SELECT mime_in_reply_to, IFNULL(mime_references, '')
448 FROM msgs WHERE id=?",
449 (msg.id,),
450 |row| {
451 let in_reply_to: String = row.get(0)?;
452 let references: String = row.get(1)?;
453
454 Ok((in_reply_to, references))
455 },
456 )
457 .await?;
458 let references: Vec<String> = references
459 .trim()
460 .split_ascii_whitespace()
461 .map(|s| s.trim_start_matches('<').trim_end_matches('>').to_string())
462 .collect();
463 let selfstatus = match attach_profile_data {
464 true => context
465 .get_config(Config::Selfstatus)
466 .await?
467 .unwrap_or_default(),
468 false => "".to_string(),
469 };
470 let attach_selfavatar = Self::should_attach_selfavatar(context, &msg).await;
471
472 ensure_and_debug_assert!(
473 member_timestamps.is_empty()
474 || to.len() + past_members.len() == member_timestamps.len(),
475 "to.len() ({}) + past_members.len() ({}) != member_timestamps.len() ({})",
476 to.len(),
477 past_members.len(),
478 member_timestamps.len(),
479 );
480 let webxdc_topic = get_iroh_topic_for_msg(context, msg.id).await?;
481 let factory = MimeFactory {
482 from_addr,
483 from_displayname,
484 sender_displayname,
485 selfstatus,
486 recipients,
487 encryption_pubkeys,
488 to,
489 past_members,
490 member_fingerprints,
491 member_timestamps,
492 timestamp: msg.timestamp_sort,
493 loaded: Loaded::Message { msg, chat },
494 in_reply_to,
495 references,
496 req_mdn,
497 last_added_location_id: None,
498 sync_ids_to_delete: None,
499 attach_selfavatar,
500 webxdc_topic,
501 };
502 Ok(factory)
503 }
504
505 pub async fn from_mdn(
506 context: &Context,
507 from_id: ContactId,
508 rfc724_mid: String,
509 additional_msg_ids: Vec<String>,
510 ) -> Result<MimeFactory> {
511 let contact = Contact::get_by_id(context, from_id).await?;
512 let from_addr = context.get_primary_self_addr().await?;
513 let timestamp = create_smeared_timestamp(context);
514
515 let addr = contact.get_addr().to_string();
516 let encryption_pubkeys = if contact.is_key_contact() {
517 if let Some(key) = contact.public_key(context).await? {
518 Some(vec![(addr.clone(), key)])
519 } else {
520 Some(Vec::new())
521 }
522 } else {
523 None
524 };
525
526 let res = MimeFactory {
527 from_addr,
528 from_displayname: "".to_string(),
529 sender_displayname: None,
530 selfstatus: "".to_string(),
531 recipients: vec![addr],
532 encryption_pubkeys,
533 to: vec![("".to_string(), contact.get_addr().to_string())],
534 past_members: vec![],
535 member_fingerprints: vec![],
536 member_timestamps: vec![],
537 timestamp,
538 loaded: Loaded::Mdn {
539 rfc724_mid,
540 additional_msg_ids,
541 },
542 in_reply_to: String::default(),
543 references: Vec::new(),
544 req_mdn: false,
545 last_added_location_id: None,
546 sync_ids_to_delete: None,
547 attach_selfavatar: false,
548 webxdc_topic: None,
549 };
550
551 Ok(res)
552 }
553
554 fn should_skip_autocrypt(&self) -> bool {
555 match &self.loaded {
556 Loaded::Message { msg, .. } => {
557 msg.param.get_bool(Param::SkipAutocrypt).unwrap_or_default()
558 }
559 Loaded::Mdn { .. } => true,
560 }
561 }
562
563 fn should_attach_profile_data(msg: &Message) -> bool {
564 msg.param.get_cmd() != SystemMessage::SecurejoinMessage || {
565 let step = msg.param.get(Param::Arg).unwrap_or_default();
566 step == "vg-request-with-auth"
572 || step == "vc-request-with-auth"
573 || step == "vg-member-added"
578 || step == "vc-contact-confirm"
579 }
580 }
581
582 async fn should_attach_selfavatar(context: &Context, msg: &Message) -> bool {
583 Self::should_attach_profile_data(msg)
584 && match chat::shall_attach_selfavatar(context, msg.chat_id).await {
585 Ok(should) => should,
586 Err(err) => {
587 warn!(
588 context,
589 "should_attach_selfavatar: cannot get selfavatar state: {err:#}."
590 );
591 false
592 }
593 }
594 }
595
596 fn grpimage(&self) -> Option<String> {
597 match &self.loaded {
598 Loaded::Message { chat, msg } => {
599 let cmd = msg.param.get_cmd();
600
601 match cmd {
602 SystemMessage::MemberAddedToGroup => {
603 return chat.param.get(Param::ProfileImage).map(Into::into);
604 }
605 SystemMessage::GroupImageChanged => {
606 return msg.param.get(Param::Arg).map(Into::into);
607 }
608 _ => {}
609 }
610
611 if msg
612 .param
613 .get_bool(Param::AttachGroupImage)
614 .unwrap_or_default()
615 {
616 return chat.param.get(Param::ProfileImage).map(Into::into);
617 }
618
619 None
620 }
621 Loaded::Mdn { .. } => None,
622 }
623 }
624
625 async fn subject_str(&self, context: &Context) -> Result<String> {
626 let subject = match &self.loaded {
627 Loaded::Message { chat, msg } => {
628 let quoted_msg_subject = msg.quoted_message(context).await?.map(|m| m.subject);
629
630 if !msg.subject.is_empty() {
631 return Ok(msg.subject.clone());
632 }
633
634 if (chat.typ == Chattype::Group || chat.typ == Chattype::OutBroadcast)
635 && quoted_msg_subject.is_none_or_empty()
636 {
637 let re = if self.in_reply_to.is_empty() {
638 ""
639 } else {
640 "Re: "
641 };
642 return Ok(format!("{}{}", re, chat.name));
643 }
644
645 let parent_subject = if quoted_msg_subject.is_none_or_empty() {
646 chat.param.get(Param::LastSubject)
647 } else {
648 quoted_msg_subject.as_deref()
649 };
650 if let Some(last_subject) = parent_subject {
651 return Ok(format!("Re: {}", remove_subject_prefix(last_subject)));
652 }
653
654 let self_name = match Self::should_attach_profile_data(msg) {
655 true => context.get_config(Config::Displayname).await?,
656 false => None,
657 };
658 let self_name = &match self_name {
659 Some(name) => name,
660 None => context.get_config(Config::Addr).await?.unwrap_or_default(),
661 };
662 stock_str::subject_for_new_contact(context, self_name).await
663 }
664 Loaded::Mdn { .. } => "Receipt Notification".to_string(), };
666
667 Ok(subject)
668 }
669
670 pub fn recipients(&self) -> Vec<String> {
671 self.recipients.clone()
672 }
673
674 pub async fn render(mut self, context: &Context) -> Result<RenderedEmail> {
677 let mut headers = Vec::<(&'static str, HeaderType<'static>)>::new();
678
679 let from = new_address_with_name(&self.from_displayname, self.from_addr.clone());
680
681 let mut to: Vec<Address<'static>> = Vec::new();
682 for (name, addr) in &self.to {
683 to.push(Address::new_address(
684 if name.is_empty() {
685 None
686 } else {
687 Some(name.to_string())
688 },
689 addr.clone(),
690 ));
691 }
692
693 let mut past_members: Vec<Address<'static>> = Vec::new(); for (name, addr) in &self.past_members {
695 past_members.push(Address::new_address(
696 if name.is_empty() {
697 None
698 } else {
699 Some(name.to_string())
700 },
701 addr.clone(),
702 ));
703 }
704
705 ensure_and_debug_assert!(
706 self.member_timestamps.is_empty()
707 || to.len() + past_members.len() == self.member_timestamps.len(),
708 "to.len() ({}) + past_members.len() ({}) != self.member_timestamps.len() ({})",
709 to.len(),
710 past_members.len(),
711 self.member_timestamps.len(),
712 );
713 if to.is_empty() {
714 to.push(hidden_recipients());
715 }
716
717 headers.push(("From", from.into()));
720
721 if let Some(sender_displayname) = &self.sender_displayname {
722 let sender = new_address_with_name(sender_displayname, self.from_addr.clone());
723 headers.push(("Sender", sender.into()));
724 }
725 headers.push((
726 "To",
727 mail_builder::headers::address::Address::new_list(to.clone()).into(),
728 ));
729 if !past_members.is_empty() {
730 headers.push((
731 "Chat-Group-Past-Members",
732 mail_builder::headers::address::Address::new_list(past_members.clone()).into(),
733 ));
734 }
735
736 if let Loaded::Message { chat, .. } = &self.loaded {
737 if chat.typ == Chattype::Group {
738 if !self.member_timestamps.is_empty() && !chat.member_list_is_stale(context).await?
739 {
740 headers.push((
741 "Chat-Group-Member-Timestamps",
742 mail_builder::headers::raw::Raw::new(
743 self.member_timestamps
744 .iter()
745 .map(|ts| ts.to_string())
746 .collect::<Vec<String>>()
747 .join(" "),
748 )
749 .into(),
750 ));
751 }
752
753 if !self.member_fingerprints.is_empty() {
754 headers.push((
755 "Chat-Group-Member-Fpr",
756 mail_builder::headers::raw::Raw::new(
757 self.member_fingerprints
758 .iter()
759 .map(|fp| fp.to_string())
760 .collect::<Vec<String>>()
761 .join(" "),
762 )
763 .into(),
764 ));
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 if msg.param.get_cmd() == SystemMessage::SecurejoinMessage {
819 let step = msg.param.get(Param::Arg).unwrap_or_default();
820 if step != "vg-request" && step != "vc-request" {
821 headers.push((
822 "Auto-Submitted",
823 mail_builder::headers::raw::Raw::new("auto-replied".to_string()).into(),
824 ));
825 }
826 }
827 }
828
829 if let Loaded::Message { msg, chat } = &self.loaded {
830 if chat.typ == Chattype::OutBroadcast || chat.typ == Chattype::InBroadcast {
831 headers.push((
832 "Chat-List-ID",
833 mail_builder::headers::text::Text::new(format!(
834 "{} <{}>",
835 chat.name, chat.grpid
836 ))
837 .into(),
838 ));
839
840 if msg.param.get_cmd() == SystemMessage::MemberAddedToGroup {
841 if let Some(secret) = msg.param.get(PARAM_BROADCAST_SECRET) {
842 headers.push((
843 "Chat-Broadcast-Secret",
844 mail_builder::headers::text::Text::new(secret.to_string()).into(),
845 ));
846 }
847 }
848 }
849 }
850
851 if let Loaded::Message { msg, .. } = &self.loaded {
852 if let Some(original_rfc724_mid) = msg.param.get(Param::TextEditFor) {
853 headers.push((
854 "Chat-Edit",
855 mail_builder::headers::message_id::MessageId::new(
856 original_rfc724_mid.to_string(),
857 )
858 .into(),
859 ));
860 } else if let Some(rfc724_mid_list) = msg.param.get(Param::DeleteRequestFor) {
861 headers.push((
862 "Chat-Delete",
863 mail_builder::headers::message_id::MessageId::new(rfc724_mid_list.to_string())
864 .into(),
865 ));
866 }
867 }
868
869 headers.push((
871 "Chat-Version",
872 mail_builder::headers::raw::Raw::new("1.0").into(),
873 ));
874
875 if self.req_mdn {
876 headers.push((
880 "Chat-Disposition-Notification-To",
881 mail_builder::headers::raw::Raw::new(self.from_addr.clone()).into(),
882 ));
883 }
884
885 let grpimage = self.grpimage();
886 let skip_autocrypt = self.should_skip_autocrypt();
887 let encrypt_helper = EncryptHelper::new(context).await?;
888
889 if !skip_autocrypt {
890 let aheader = encrypt_helper.get_aheader().to_string();
892 headers.push((
893 "Autocrypt",
894 mail_builder::headers::raw::Raw::new(aheader).into(),
895 ));
896 }
897
898 let is_encrypted = self.encryption_pubkeys.is_some();
899
900 if let Loaded::Message { msg, .. } = &self.loaded {
904 let ephemeral_timer = msg.chat_id.get_ephemeral_timer(context).await?;
905 if let EphemeralTimer::Enabled { duration } = ephemeral_timer {
906 headers.push((
907 "Ephemeral-Timer",
908 mail_builder::headers::raw::Raw::new(duration.to_string()).into(),
909 ));
910 }
911 }
912
913 let is_securejoin_message = if let Loaded::Message { msg, .. } = &self.loaded {
914 msg.param.get_cmd() == SystemMessage::SecurejoinMessage
915 } else {
916 false
917 };
918
919 let message: MimePart<'static> = match &self.loaded {
920 Loaded::Message { msg, .. } => {
921 let msg = msg.clone();
922 let (main_part, mut parts) = self
923 .render_message(context, &mut headers, &grpimage, is_encrypted)
924 .await?;
925 if parts.is_empty() {
926 main_part
928 } else {
929 parts.insert(0, main_part);
930
931 if msg.param.get_cmd() == SystemMessage::MultiDeviceSync {
933 MimePart::new("multipart/report; report-type=multi-device-sync", parts)
934 } else if msg.param.get_cmd() == SystemMessage::WebxdcStatusUpdate {
935 MimePart::new("multipart/report; report-type=status-update", parts)
936 } else {
937 MimePart::new("multipart/mixed", parts)
938 }
939 }
940 }
941 Loaded::Mdn { .. } => self.render_mdn()?,
942 };
943
944 let mut unprotected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
953
954 let mut hidden_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
967
968 let mut protected_headers: Vec<(&'static str, HeaderType<'static>)> = Vec::new();
977
978 unprotected_headers.push((
980 "MIME-Version",
981 mail_builder::headers::raw::Raw::new("1.0").into(),
982 ));
983 for header @ (original_header_name, _header_value) in &headers {
984 let header_name = original_header_name.to_lowercase();
985 if header_name == "message-id" {
986 unprotected_headers.push(header.clone());
987 hidden_headers.push(header.clone());
988 } else if is_hidden(&header_name) {
989 hidden_headers.push(header.clone());
990 } else if header_name == "from" {
991 if is_encrypted || !is_securejoin_message {
993 protected_headers.push(header.clone());
994 }
995
996 unprotected_headers.push((
997 original_header_name,
998 Address::new_address(None::<&'static str>, self.from_addr.clone()).into(),
999 ));
1000 } else if header_name == "to" {
1001 protected_headers.push(header.clone());
1002 if is_encrypted {
1003 let mut to_without_names = to
1004 .clone()
1005 .into_iter()
1006 .filter_map(|header| match header {
1007 Address::Address(mb) => Some(Address::Address(EmailAddress {
1008 name: None,
1009 email: mb.email,
1010 })),
1011 _ => None,
1012 })
1013 .collect::<Vec<_>>();
1014 if to_without_names.is_empty() {
1015 to_without_names.push(hidden_recipients());
1016 }
1017 unprotected_headers.push((
1018 original_header_name,
1019 Address::new_list(to_without_names).into(),
1020 ));
1021 } else {
1022 unprotected_headers.push(header.clone());
1023 }
1024 } else if header_name == "chat-broadcast-secret" {
1025 if is_encrypted {
1026 protected_headers.push(header.clone());
1027 } else {
1028 bail!("Message is unecrypted, cannot include broadcast secret");
1029 }
1030 } else if is_encrypted && header_name == "date" {
1031 protected_headers.push(header.clone());
1032
1033 let timestamp_offset = rand::random_range(0..1000000);
1047 let protected_timestamp = self.timestamp.saturating_sub(timestamp_offset);
1048 let unprotected_date =
1049 chrono::DateTime::<chrono::Utc>::from_timestamp(protected_timestamp, 0)
1050 .unwrap()
1051 .to_rfc2822();
1052 unprotected_headers.push((
1053 "Date",
1054 mail_builder::headers::raw::Raw::new(unprotected_date).into(),
1055 ));
1056 } else if is_encrypted {
1057 protected_headers.push(header.clone());
1058
1059 match header_name.as_str() {
1060 "subject" => {
1061 unprotected_headers.push((
1062 "Subject",
1063 mail_builder::headers::raw::Raw::new("[...]").into(),
1064 ));
1065 }
1066 "in-reply-to"
1067 | "references"
1068 | "auto-submitted"
1069 | "chat-version"
1070 | "autocrypt-setup-message" => {
1071 unprotected_headers.push(header.clone());
1072 }
1073 _ => {
1074 }
1076 }
1077 } else {
1078 protected_headers.push(header.clone());
1082 unprotected_headers.push(header.clone())
1083 }
1084 }
1085
1086 let outer_message = if let Some(encryption_pubkeys) = self.encryption_pubkeys {
1087 let message = protected_headers
1089 .into_iter()
1090 .fold(message, |message, (header, value)| {
1091 message.header(header, value)
1092 });
1093
1094 let mut message: MimePart<'static> = hidden_headers
1096 .into_iter()
1097 .fold(message, |message, (header, value)| {
1098 message.header(header, value)
1099 });
1100
1101 let multiple_recipients =
1103 encryption_pubkeys.len() > 1 || context.get_config_bool(Config::BccSelf).await?;
1104
1105 let gossip_period = context.get_config_i64(Config::GossipPeriod).await?;
1106 let now = time();
1107
1108 match &self.loaded {
1109 Loaded::Message { chat, msg } => {
1110 if !should_hide_recipients(msg, chat) {
1111 for (addr, key) in &encryption_pubkeys {
1112 let fingerprint = key.dc_fingerprint().hex();
1113 let cmd = msg.param.get_cmd();
1114 let should_do_gossip = cmd == SystemMessage::MemberAddedToGroup
1115 || cmd == SystemMessage::SecurejoinMessage
1116 || multiple_recipients && {
1117 let gossiped_timestamp: Option<i64> = context
1118 .sql
1119 .query_get_value(
1120 "SELECT timestamp
1121 FROM gossip_timestamp
1122 WHERE chat_id=? AND fingerprint=?",
1123 (chat.id, &fingerprint),
1124 )
1125 .await?;
1126
1127 gossip_period == 0
1134 || gossiped_timestamp
1135 .is_none_or(|ts| now >= ts + gossip_period || now < ts)
1136 };
1137
1138 let verifier_id: Option<u32> = context
1139 .sql
1140 .query_get_value(
1141 "SELECT verifier FROM contacts WHERE fingerprint=?",
1142 (&fingerprint,),
1143 )
1144 .await?;
1145
1146 let is_verified =
1147 verifier_id.is_some_and(|verifier_id| verifier_id != 0);
1148
1149 if !should_do_gossip {
1150 continue;
1151 }
1152
1153 let header = Aheader {
1154 addr: addr.clone(),
1155 public_key: key.clone(),
1156 prefer_encrypt: EncryptPreference::NoPreference,
1159 verified: is_verified,
1160 }
1161 .to_string();
1162
1163 message = message.header(
1164 "Autocrypt-Gossip",
1165 mail_builder::headers::raw::Raw::new(header),
1166 );
1167
1168 context
1169 .sql
1170 .execute(
1171 "INSERT INTO gossip_timestamp (chat_id, fingerprint, timestamp)
1172 VALUES (?, ?, ?)
1173 ON CONFLICT (chat_id, fingerprint)
1174 DO UPDATE SET timestamp=excluded.timestamp",
1175 (chat.id, &fingerprint, now),
1176 )
1177 .await?;
1178 }
1179 }
1180 }
1181 Loaded::Mdn { .. } => {
1182 }
1184 }
1185
1186 for (h, v) in &mut message.headers {
1188 if h == "Content-Type" {
1189 if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1190 *ct = ct.clone().attribute("protected-headers", "v1");
1191 }
1192 }
1193 }
1194
1195 let compress = match &self.loaded {
1199 Loaded::Message { msg, .. } => {
1200 msg.param.get_cmd() != SystemMessage::SecurejoinMessage
1201 }
1202 Loaded::Mdn { .. } => true,
1203 };
1204
1205 let shared_secret: Option<String> = match &self.loaded {
1206 Loaded::Message { chat, msg }
1207 if should_encrypt_with_broadcast_secret(msg, chat) =>
1208 {
1209 let secret = load_broadcast_secret(context, chat.id).await?;
1210 if secret.is_none() {
1211 let text = BROADCAST_INCOMPATIBILITY_MSG;
1216 chat::add_info_msg(context, chat.id, text, time()).await?;
1217 bail!(text);
1218 }
1219 secret
1220 }
1221 _ => None,
1222 };
1223
1224 let anonymous_recipients = false;
1234
1235 let encrypted = if let Some(shared_secret) = shared_secret {
1236 encrypt_helper
1237 .encrypt_symmetrically(context, &shared_secret, message, compress)
1238 .await?
1239 } else {
1240 let mut encryption_keyring = vec![encrypt_helper.public_key.clone()];
1245 encryption_keyring
1246 .extend(encryption_pubkeys.iter().map(|(_addr, key)| (*key).clone()));
1247
1248 encrypt_helper
1249 .encrypt(
1250 context,
1251 encryption_keyring,
1252 message,
1253 compress,
1254 anonymous_recipients,
1255 )
1256 .await?
1257 };
1258
1259 let encrypted = encrypted + "\n";
1263
1264 MimePart::new(
1266 "multipart/encrypted; protocol=\"application/pgp-encrypted\"",
1267 vec![
1268 MimePart::new("application/pgp-encrypted", "Version: 1\r\n").header(
1270 "Content-Description",
1271 mail_builder::headers::raw::Raw::new("PGP/MIME version identification"),
1272 ),
1273 MimePart::new(
1275 "application/octet-stream; name=\"encrypted.asc\"",
1276 encrypted,
1277 )
1278 .header(
1279 "Content-Description",
1280 mail_builder::headers::raw::Raw::new("OpenPGP encrypted message"),
1281 )
1282 .header(
1283 "Content-Disposition",
1284 mail_builder::headers::raw::Raw::new("inline; filename=\"encrypted.asc\";"),
1285 ),
1286 ],
1287 )
1288 } else if matches!(self.loaded, Loaded::Mdn { .. }) {
1289 message
1298 } else {
1299 let message = hidden_headers
1300 .into_iter()
1301 .fold(message, |message, (header, value)| {
1302 message.header(header, value)
1303 });
1304 let message = MimePart::new("multipart/mixed", vec![message]);
1305 let mut message = protected_headers
1306 .iter()
1307 .fold(message, |message, (header, value)| {
1308 message.header(*header, value.clone())
1309 });
1310
1311 if skip_autocrypt || !context.get_config_bool(Config::SignUnencrypted).await? {
1312 let protected: HashSet<&str> =
1314 HashSet::from_iter(protected_headers.iter().map(|(header, _value)| *header));
1315 unprotected_headers.retain(|(header, _value)| !protected.contains(header));
1316
1317 message
1318 } else {
1319 for (h, v) in &mut message.headers {
1320 if h == "Content-Type" {
1321 if let mail_builder::headers::HeaderType::ContentType(ct) = v {
1322 *ct = ct.clone().attribute("protected-headers", "v1");
1323 }
1324 }
1325 }
1326
1327 let signature = encrypt_helper.sign(context, &message).await?;
1328 MimePart::new(
1329 "multipart/signed; protocol=\"application/pgp-signature\"; protected",
1330 vec![
1331 message,
1332 MimePart::new(
1333 "application/pgp-signature; name=\"signature.asc\"",
1334 signature,
1335 )
1336 .header(
1337 "Content-Description",
1338 mail_builder::headers::raw::Raw::<'static>::new(
1339 "OpenPGP digital signature",
1340 ),
1341 )
1342 .attachment("signature"),
1343 ],
1344 )
1345 }
1346 };
1347
1348 let outer_message = unprotected_headers
1350 .into_iter()
1351 .fold(outer_message, |message, (header, value)| {
1352 message.header(header, value)
1353 });
1354
1355 let MimeFactory {
1356 last_added_location_id,
1357 ..
1358 } = self;
1359
1360 let mut buffer = Vec::new();
1361 let cursor = Cursor::new(&mut buffer);
1362 outer_message.clone().write_part(cursor).ok();
1363 let message = String::from_utf8_lossy(&buffer).to_string();
1364
1365 Ok(RenderedEmail {
1366 message,
1367 is_encrypted,
1369 last_added_location_id,
1370 sync_ids_to_delete: self.sync_ids_to_delete,
1371 rfc724_mid,
1372 subject: subject_str,
1373 })
1374 }
1375
1376 fn get_message_kml_part(&self) -> Option<MimePart<'static>> {
1378 let Loaded::Message { msg, .. } = &self.loaded else {
1379 return None;
1380 };
1381
1382 let latitude = msg.param.get_float(Param::SetLatitude)?;
1383 let longitude = msg.param.get_float(Param::SetLongitude)?;
1384
1385 let kml_file = location::get_message_kml(msg.timestamp_sort, latitude, longitude);
1386 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_file)
1387 .attachment("message.kml");
1388 Some(part)
1389 }
1390
1391 async fn get_location_kml_part(
1393 &mut self,
1394 context: &Context,
1395 ) -> Result<Option<MimePart<'static>>> {
1396 let Loaded::Message { msg, .. } = &self.loaded else {
1397 return Ok(None);
1398 };
1399
1400 let Some((kml_content, last_added_location_id)) =
1401 location::get_kml(context, msg.chat_id).await?
1402 else {
1403 return Ok(None);
1404 };
1405
1406 let part = MimePart::new("application/vnd.google-earth.kml+xml", kml_content)
1407 .attachment("location.kml");
1408 if !msg.param.exists(Param::SetLatitude) {
1409 self.last_added_location_id = Some(last_added_location_id);
1411 }
1412 Ok(Some(part))
1413 }
1414
1415 async fn render_message(
1416 &mut self,
1417 context: &Context,
1418 headers: &mut Vec<(&'static str, HeaderType<'static>)>,
1419 grpimage: &Option<String>,
1420 is_encrypted: bool,
1421 ) -> Result<(MimePart<'static>, Vec<MimePart<'static>>)> {
1422 let Loaded::Message { chat, msg } = &self.loaded else {
1423 bail!("Attempt to render MDN as a message");
1424 };
1425 let chat = chat.clone();
1426 let msg = msg.clone();
1427 let command = msg.param.get_cmd();
1428 let mut placeholdertext = None;
1429
1430 let send_verified_headers = match chat.typ {
1431 Chattype::Single => true,
1432 Chattype::Group => true,
1433 Chattype::Mailinglist => false,
1435 Chattype::OutBroadcast | Chattype::InBroadcast => false,
1436 };
1437
1438 if send_verified_headers {
1439 let was_protected: bool = context
1440 .sql
1441 .query_get_value("SELECT protected FROM chats WHERE id=?", (chat.id,))
1442 .await?
1443 .unwrap_or_default();
1444
1445 if was_protected {
1446 let unverified_member_exists = context
1447 .sql
1448 .exists(
1449 "SELECT COUNT(*)
1450 FROM contacts, chats_contacts
1451 WHERE chats_contacts.contact_id=contacts.id AND chats_contacts.chat_id=?
1452 AND contacts.id>9
1453 AND contacts.verifier=0",
1454 (chat.id,),
1455 )
1456 .await?;
1457
1458 if !unverified_member_exists {
1459 headers.push((
1460 "Chat-Verified",
1461 mail_builder::headers::raw::Raw::new("1").into(),
1462 ));
1463 }
1464 }
1465 }
1466
1467 if chat.typ == Chattype::Group {
1468 if !chat.grpid.is_empty() {
1470 headers.push((
1471 "Chat-Group-ID",
1472 mail_builder::headers::raw::Raw::new(chat.grpid.clone()).into(),
1473 ));
1474 }
1475 }
1476
1477 if chat.typ == Chattype::Group
1478 || chat.typ == Chattype::OutBroadcast
1479 || chat.typ == Chattype::InBroadcast
1480 {
1481 headers.push((
1482 "Chat-Group-Name",
1483 mail_builder::headers::text::Text::new(chat.name.to_string()).into(),
1484 ));
1485 if let Some(ts) = chat.param.get_i64(Param::GroupNameTimestamp) {
1486 headers.push((
1487 "Chat-Group-Name-Timestamp",
1488 mail_builder::headers::text::Text::new(ts.to_string()).into(),
1489 ));
1490 }
1491
1492 match command {
1493 SystemMessage::MemberRemovedFromGroup => {
1494 let email_to_remove = msg.param.get(Param::Arg).unwrap_or_default();
1495 let fingerprint_to_remove = msg.param.get(Param::Arg4).unwrap_or_default();
1496
1497 if email_to_remove
1498 == context
1499 .get_config(Config::ConfiguredAddr)
1500 .await?
1501 .unwrap_or_default()
1502 {
1503 placeholdertext = Some(stock_str::msg_group_left_remote(context).await);
1504 } else {
1505 placeholdertext =
1506 Some(stock_str::msg_del_member_remote(context, email_to_remove).await);
1507 };
1508
1509 if !email_to_remove.is_empty() {
1510 headers.push((
1511 "Chat-Group-Member-Removed",
1512 mail_builder::headers::raw::Raw::new(email_to_remove.to_string())
1513 .into(),
1514 ));
1515 }
1516
1517 if !fingerprint_to_remove.is_empty() {
1518 headers.push((
1519 "Chat-Group-Member-Removed-Fpr",
1520 mail_builder::headers::raw::Raw::new(fingerprint_to_remove.to_string())
1521 .into(),
1522 ));
1523 }
1524 }
1525 SystemMessage::MemberAddedToGroup => {
1526 let email_to_add = msg.param.get(Param::Arg).unwrap_or_default();
1527 let fingerprint_to_add = msg.param.get(Param::Arg4).unwrap_or_default();
1528
1529 placeholdertext =
1530 Some(stock_str::msg_add_member_remote(context, email_to_add).await);
1531
1532 if !email_to_add.is_empty() {
1533 headers.push((
1534 "Chat-Group-Member-Added",
1535 mail_builder::headers::raw::Raw::new(email_to_add.to_string()).into(),
1536 ));
1537 }
1538 if !fingerprint_to_add.is_empty() {
1539 headers.push((
1540 "Chat-Group-Member-Added-Fpr",
1541 mail_builder::headers::raw::Raw::new(fingerprint_to_add.to_string())
1542 .into(),
1543 ));
1544 }
1545 if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & DC_FROM_HANDSHAKE {
1546 let step = "vg-member-added";
1547 info!(context, "Sending secure-join message {:?}.", step);
1548 headers.push((
1549 "Secure-Join",
1550 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1551 ));
1552 }
1553 }
1554 SystemMessage::GroupNameChanged => {
1555 let old_name = msg.param.get(Param::Arg).unwrap_or_default().to_string();
1556 headers.push((
1557 "Chat-Group-Name-Changed",
1558 mail_builder::headers::text::Text::new(old_name).into(),
1559 ));
1560 }
1561 SystemMessage::GroupImageChanged => {
1562 headers.push((
1563 "Chat-Content",
1564 mail_builder::headers::text::Text::new("group-avatar-changed").into(),
1565 ));
1566 if grpimage.is_none() {
1567 headers.push((
1568 "Chat-Group-Avatar",
1569 mail_builder::headers::raw::Raw::new("0").into(),
1570 ));
1571 }
1572 }
1573 _ => {}
1574 }
1575 }
1576
1577 match command {
1578 SystemMessage::LocationStreamingEnabled => {
1579 headers.push((
1580 "Chat-Content",
1581 mail_builder::headers::raw::Raw::new("location-streaming-enabled").into(),
1582 ));
1583 }
1584 SystemMessage::EphemeralTimerChanged => {
1585 headers.push((
1586 "Chat-Content",
1587 mail_builder::headers::raw::Raw::new("ephemeral-timer-changed").into(),
1588 ));
1589 }
1590 SystemMessage::LocationOnly
1591 | SystemMessage::MultiDeviceSync
1592 | SystemMessage::WebxdcStatusUpdate => {
1593 headers.push((
1602 "Auto-Submitted",
1603 mail_builder::headers::raw::Raw::new("auto-generated").into(),
1604 ));
1605 }
1606 SystemMessage::AutocryptSetupMessage => {
1607 headers.push((
1608 "Autocrypt-Setup-Message",
1609 mail_builder::headers::raw::Raw::new("v1").into(),
1610 ));
1611
1612 placeholdertext = Some(ASM_SUBJECT.to_string());
1613 }
1614 SystemMessage::SecurejoinMessage => {
1615 let step = msg.param.get(Param::Arg).unwrap_or_default();
1616 if !step.is_empty() {
1617 info!(context, "Sending secure-join message {step:?}.");
1618 headers.push((
1619 "Secure-Join",
1620 mail_builder::headers::raw::Raw::new(step.to_string()).into(),
1621 ));
1622
1623 let param2 = msg.param.get(Param::Arg2).unwrap_or_default();
1624 if !param2.is_empty() {
1625 headers.push((
1626 if step == "vg-request-with-auth" || step == "vc-request-with-auth" {
1627 "Secure-Join-Auth"
1628 } else {
1629 "Secure-Join-Invitenumber"
1630 },
1631 mail_builder::headers::text::Text::new(param2.to_string()).into(),
1632 ));
1633 }
1634
1635 let fingerprint = msg.param.get(Param::Arg3).unwrap_or_default();
1636 if !fingerprint.is_empty() {
1637 headers.push((
1638 "Secure-Join-Fingerprint",
1639 mail_builder::headers::raw::Raw::new(fingerprint.to_string()).into(),
1640 ));
1641 }
1642 if let Some(id) = msg.param.get(Param::Arg4) {
1643 headers.push((
1644 "Secure-Join-Group",
1645 mail_builder::headers::raw::Raw::new(id.to_string()).into(),
1646 ));
1647 };
1648 }
1649 }
1650 SystemMessage::ChatProtectionEnabled => {
1651 headers.push((
1652 "Chat-Content",
1653 mail_builder::headers::raw::Raw::new("protection-enabled").into(),
1654 ));
1655 }
1656 SystemMessage::ChatProtectionDisabled => {
1657 headers.push((
1658 "Chat-Content",
1659 mail_builder::headers::raw::Raw::new("protection-disabled").into(),
1660 ));
1661 }
1662 SystemMessage::IrohNodeAddr => {
1663 let node_addr = context
1664 .get_or_try_init_peer_channel()
1665 .await?
1666 .get_node_addr()
1667 .await?;
1668
1669 debug_assert!(node_addr.relay_url().is_some());
1672 headers.push((
1673 HeaderDef::IrohNodeAddr.into(),
1674 mail_builder::headers::text::Text::new(serde_json::to_string(&node_addr)?)
1675 .into(),
1676 ));
1677 }
1678 SystemMessage::CallAccepted => {
1679 headers.push((
1680 "Chat-Content",
1681 mail_builder::headers::raw::Raw::new("call-accepted").into(),
1682 ));
1683 }
1684 SystemMessage::CallEnded => {
1685 headers.push((
1686 "Chat-Content",
1687 mail_builder::headers::raw::Raw::new("call-ended").into(),
1688 ));
1689 }
1690 _ => {}
1691 }
1692
1693 if let Some(grpimage) = grpimage {
1694 info!(context, "setting group image '{}'", grpimage);
1695 let avatar = build_avatar_file(context, grpimage)
1696 .await
1697 .context("Cannot attach group image")?;
1698 headers.push((
1699 "Chat-Group-Avatar",
1700 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1701 ));
1702 }
1703
1704 if msg.viewtype == Viewtype::Sticker {
1705 headers.push((
1706 "Chat-Content",
1707 mail_builder::headers::raw::Raw::new("sticker").into(),
1708 ));
1709 } else if msg.viewtype == Viewtype::Call {
1710 headers.push((
1711 "Chat-Content",
1712 mail_builder::headers::raw::Raw::new("call").into(),
1713 ));
1714 placeholdertext = Some(
1715 "[This is a 'Call'. The sender uses an experiment not supported on your version yet]".to_string(),
1716 );
1717 }
1718
1719 if let Some(offer) = msg.param.get(Param::WebrtcRoom) {
1720 headers.push((
1721 "Chat-Webrtc-Room",
1722 mail_builder::headers::raw::Raw::new(b_encode(offer)).into(),
1723 ));
1724 } else if let Some(answer) = msg.param.get(Param::WebrtcAccepted) {
1725 headers.push((
1726 "Chat-Webrtc-Accepted",
1727 mail_builder::headers::raw::Raw::new(b_encode(answer)).into(),
1728 ));
1729 }
1730
1731 if msg.viewtype == Viewtype::Voice
1732 || msg.viewtype == Viewtype::Audio
1733 || msg.viewtype == Viewtype::Video
1734 {
1735 if msg.viewtype == Viewtype::Voice {
1736 headers.push((
1737 "Chat-Voice-Message",
1738 mail_builder::headers::raw::Raw::new("1").into(),
1739 ));
1740 }
1741 let duration_ms = msg.param.get_int(Param::Duration).unwrap_or_default();
1742 if duration_ms > 0 {
1743 let dur = duration_ms.to_string();
1744 headers.push((
1745 "Chat-Duration",
1746 mail_builder::headers::raw::Raw::new(dur).into(),
1747 ));
1748 }
1749 }
1750
1751 let afwd_email = msg.param.exists(Param::Forwarded);
1757 let fwdhint = if afwd_email {
1758 Some(
1759 "---------- Forwarded message ----------\r\n\
1760 From: Delta Chat\r\n\
1761 \r\n"
1762 .to_string(),
1763 )
1764 } else {
1765 None
1766 };
1767
1768 let final_text = placeholdertext.as_deref().unwrap_or(&msg.text);
1769
1770 let mut quoted_text = None;
1771 if let Some(msg_quoted_text) = msg.quoted_text() {
1772 let mut some_quoted_text = String::new();
1773 for quoted_line in msg_quoted_text.split('\n') {
1774 some_quoted_text += "> ";
1775 some_quoted_text += quoted_line;
1776 some_quoted_text += "\r\n";
1777 }
1778 some_quoted_text += "\r\n";
1779 quoted_text = Some(some_quoted_text)
1780 }
1781
1782 if !is_encrypted && msg.param.get_bool(Param::ProtectQuote).unwrap_or_default() {
1783 quoted_text = Some("> ...\r\n\r\n".to_string());
1785 }
1786 if quoted_text.is_none() && final_text.starts_with('>') {
1787 quoted_text = Some("\r\n".to_string());
1790 }
1791
1792 let is_reaction = msg.param.get_int(Param::Reaction).unwrap_or_default() != 0;
1793
1794 let footer = if is_reaction { "" } else { &self.selfstatus };
1795
1796 let message_text = format!(
1797 "{}{}{}{}{}{}",
1798 fwdhint.unwrap_or_default(),
1799 quoted_text.unwrap_or_default(),
1800 escape_message_footer_marks(final_text),
1801 if !final_text.is_empty() && !footer.is_empty() {
1802 "\r\n\r\n"
1803 } else {
1804 ""
1805 },
1806 if !footer.is_empty() { "-- \r\n" } else { "" },
1807 footer
1808 );
1809
1810 let mut main_part = MimePart::new("text/plain", message_text);
1811 if is_reaction {
1812 main_part = main_part.header(
1813 "Content-Disposition",
1814 mail_builder::headers::raw::Raw::new("reaction"),
1815 );
1816 }
1817
1818 let mut parts = Vec::new();
1819
1820 if msg.has_html() {
1823 let html = if let Some(orig_msg_id) = msg.param.get_int(Param::Forwarded) {
1824 MsgId::new(orig_msg_id.try_into()?)
1825 .get_html(context)
1826 .await?
1827 } else {
1828 msg.param.get(Param::SendHtml).map(|s| s.to_string())
1829 };
1830 if let Some(html) = html {
1831 main_part = MimePart::new(
1832 "multipart/alternative",
1833 vec![main_part, MimePart::new("text/html", html)],
1834 )
1835 }
1836 }
1837
1838 if msg.viewtype.has_file() {
1840 let file_part = build_body_file(context, &msg).await?;
1841 parts.push(file_part);
1842 }
1843
1844 if let Some(msg_kml_part) = self.get_message_kml_part() {
1845 parts.push(msg_kml_part);
1846 }
1847
1848 if location::is_sending_locations_to_chat(context, Some(msg.chat_id)).await? {
1849 if let Some(part) = self.get_location_kml_part(context).await? {
1850 parts.push(part);
1851 }
1852 }
1853
1854 if command == SystemMessage::MultiDeviceSync {
1857 let json = msg.param.get(Param::Arg).unwrap_or_default();
1858 let ids = msg.param.get(Param::Arg2).unwrap_or_default();
1859 parts.push(context.build_sync_part(json.to_string()));
1860 self.sync_ids_to_delete = Some(ids.to_string());
1861 } else if command == SystemMessage::WebxdcStatusUpdate {
1862 let json = msg.param.get(Param::Arg).unwrap_or_default();
1863 parts.push(context.build_status_update_part(json));
1864 } else if msg.viewtype == Viewtype::Webxdc {
1865 let topic = self
1866 .webxdc_topic
1867 .map(|top| BASE32_NOPAD.encode(top.as_bytes()).to_ascii_lowercase())
1868 .unwrap_or(create_iroh_header(context, msg.id).await?);
1869 headers.push((
1870 HeaderDef::IrohGossipTopic.get_headername(),
1871 mail_builder::headers::raw::Raw::new(topic).into(),
1872 ));
1873 if let (Some(json), _) = context
1874 .render_webxdc_status_update_object(
1875 msg.id,
1876 StatusUpdateSerial::MIN,
1877 StatusUpdateSerial::MAX,
1878 None,
1879 )
1880 .await?
1881 {
1882 parts.push(context.build_status_update_part(&json));
1883 }
1884 }
1885
1886 if self.attach_selfavatar {
1887 match context.get_config(Config::Selfavatar).await? {
1888 Some(path) => match build_avatar_file(context, &path).await {
1889 Ok(avatar) => headers.push((
1890 "Chat-User-Avatar",
1891 mail_builder::headers::raw::Raw::new(format!("base64:{avatar}")).into(),
1892 )),
1893 Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
1894 },
1895 None => headers.push((
1896 "Chat-User-Avatar",
1897 mail_builder::headers::raw::Raw::new("0").into(),
1898 )),
1899 }
1900 }
1901
1902 Ok((main_part, parts))
1903 }
1904
1905 fn render_mdn(&mut self) -> Result<MimePart<'static>> {
1907 let Loaded::Mdn {
1910 rfc724_mid,
1911 additional_msg_ids,
1912 } = &self.loaded
1913 else {
1914 bail!("Attempt to render a message as MDN");
1915 };
1916
1917 let text_part = MimePart::new("text/plain", "This is a receipt notification.");
1921
1922 let mut message = MimePart::new(
1923 "multipart/report; report-type=disposition-notification",
1924 vec![text_part],
1925 );
1926
1927 let message_text2 = format!(
1929 "Original-Recipient: rfc822;{}\r\n\
1930 Final-Recipient: rfc822;{}\r\n\
1931 Original-Message-ID: <{}>\r\n\
1932 Disposition: manual-action/MDN-sent-automatically; displayed\r\n",
1933 self.from_addr, self.from_addr, rfc724_mid
1934 );
1935
1936 let extension_fields = if additional_msg_ids.is_empty() {
1937 "".to_string()
1938 } else {
1939 "Additional-Message-IDs: ".to_string()
1940 + &additional_msg_ids
1941 .iter()
1942 .map(|mid| render_rfc724_mid(mid))
1943 .collect::<Vec<String>>()
1944 .join(" ")
1945 + "\r\n"
1946 };
1947
1948 message.add_part(MimePart::new(
1949 "message/disposition-notification",
1950 message_text2 + &extension_fields,
1951 ));
1952
1953 Ok(message)
1954 }
1955}
1956
1957fn hidden_recipients() -> Address<'static> {
1958 Address::new_group(Some("hidden-recipients".to_string()), Vec::new())
1959}
1960
1961fn should_encrypt_with_broadcast_secret(msg: &Message, chat: &Chat) -> bool {
1962 chat.typ == Chattype::OutBroadcast && must_have_only_one_recipient(msg, chat).is_none()
1963}
1964
1965fn should_hide_recipients(msg: &Message, chat: &Chat) -> bool {
1966 should_encrypt_with_broadcast_secret(msg, chat)
1967}
1968
1969fn should_encrypt_symmetrically(msg: &Message, chat: &Chat) -> bool {
1970 should_encrypt_with_broadcast_secret(msg, chat)
1971}
1972
1973fn must_have_only_one_recipient<'a>(msg: &'a Message, chat: &Chat) -> Option<Result<&'a str>> {
1978 if chat.typ == Chattype::OutBroadcast
1979 && matches!(
1980 msg.param.get_cmd(),
1981 SystemMessage::MemberRemovedFromGroup | SystemMessage::MemberAddedToGroup
1982 )
1983 {
1984 let Some(fp) = msg.param.get(Param::Arg4) else {
1985 return Some(Err(format_err!("Missing removed/added member")));
1986 };
1987 return Some(Ok(fp));
1988 }
1989 None
1990}
1991
1992async fn build_body_file(context: &Context, msg: &Message) -> Result<MimePart<'static>> {
1993 let file_name = msg.get_filename().context("msg has no file")?;
1994 let blob = msg
1995 .param
1996 .get_file_blob(context)?
1997 .context("msg has no file")?;
1998 let mimetype = msg
1999 .param
2000 .get(Param::MimeType)
2001 .unwrap_or("application/octet-stream")
2002 .to_string();
2003 let body = fs::read(blob.to_abs_path()).await?;
2004
2005 let mail = MimePart::new(mimetype, body).attachment(sanitize_bidi_characters(&file_name));
2011
2012 Ok(mail)
2013}
2014
2015async fn build_avatar_file(context: &Context, path: &str) -> Result<String> {
2016 let blob = match path.starts_with("$BLOBDIR/") {
2017 true => BlobObject::from_name(context, path)?,
2018 false => BlobObject::from_path(context, path.as_ref())?,
2019 };
2020 let body = fs::read(blob.to_abs_path()).await?;
2021 let encoded_body = base64::engine::general_purpose::STANDARD
2022 .encode(&body)
2023 .chars()
2024 .enumerate()
2025 .fold(String::new(), |mut res, (i, c)| {
2026 if i % 78 == 77 {
2027 res.push(' ')
2028 }
2029 res.push(c);
2030 res
2031 });
2032 Ok(encoded_body)
2033}
2034
2035fn recipients_contain_addr(recipients: &[(String, String)], addr: &str) -> bool {
2036 let addr_lc = addr.to_lowercase();
2037 recipients
2038 .iter()
2039 .any(|(_, cur)| cur.to_lowercase() == addr_lc)
2040}
2041
2042fn render_rfc724_mid(rfc724_mid: &str) -> String {
2043 let rfc724_mid = rfc724_mid.trim().to_string();
2044
2045 if rfc724_mid.chars().next().unwrap_or_default() == '<' {
2046 rfc724_mid
2047 } else {
2048 format!("<{rfc724_mid}>")
2049 }
2050}
2051
2052fn b_encode(value: &str) -> String {
2058 format!(
2059 "=?utf-8?B?{}?=",
2060 base64::engine::general_purpose::STANDARD.encode(value)
2061 )
2062}
2063
2064#[cfg(test)]
2065mod mimefactory_tests;