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