1use std::cmp::min;
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::path::Path;
6use std::str;
7use std::str::FromStr;
8
9use anyhow::{Context as _, Result, bail};
10use deltachat_contact_tools::{addr_cmp, addr_normalize, sanitize_bidi_characters};
11use deltachat_derive::{FromSql, ToSql};
12use format_flowed::unformat_flowed;
13use mailparse::{DispositionType, MailHeader, MailHeaderMap, SingleInfo, addrparse_header};
14use mime::Mime;
15
16use crate::aheader::Aheader;
17use crate::authres::handle_authres;
18use crate::blob::BlobObject;
19use crate::chat::ChatId;
20use crate::config::Config;
21use crate::constants;
22use crate::contact::ContactId;
23use crate::context::Context;
24use crate::decrypt::{try_decrypt, validate_detached_signature};
25use crate::dehtml::dehtml;
26use crate::events::EventType;
27use crate::headerdef::{HeaderDef, HeaderDefMap};
28use crate::key::{self, DcKey, Fingerprint, SignedPublicKey, load_self_secret_keyring};
29use crate::log::warn;
30use crate::message::{self, Message, MsgId, Viewtype, get_vcard_summary, set_msg_failed};
31use crate::param::{Param, Params};
32use crate::simplify::{SimplifiedText, simplify};
33use crate::sync::SyncItems;
34use crate::tools::{
35 get_filemeta, parse_receive_headers, smeared_time, time, truncate_msg_text, validate_id,
36};
37use crate::{chatlist_events, location, tools};
38
39#[derive(Debug)]
42pub struct GossipedKey {
43 pub public_key: SignedPublicKey,
45
46 pub verified: bool,
48}
49
50#[derive(Debug)]
60pub(crate) struct MimeMessage {
61 pub parts: Vec<Part>,
63
64 headers: HashMap<String, String>,
66
67 #[cfg(test)]
68 headers_removed: HashSet<String>,
70
71 pub recipients: Vec<SingleInfo>,
75
76 pub past_members: Vec<SingleInfo>,
78
79 pub from: SingleInfo,
81
82 pub incoming: bool,
84 pub list_post: Option<String>,
87 pub chat_disposition_notification_to: Option<SingleInfo>,
88 pub decrypting_failed: bool,
89
90 pub signature: Option<Fingerprint>,
96
97 pub gossiped_keys: BTreeMap<String, GossipedKey>,
100
101 pub autocrypt_fingerprint: Option<String>,
105
106 pub is_forwarded: bool,
108 pub is_system_message: SystemMessage,
109 pub location_kml: Option<location::Kml>,
110 pub message_kml: Option<location::Kml>,
111 pub(crate) sync_items: Option<SyncItems>,
112 pub(crate) webxdc_status_update: Option<String>,
113 pub(crate) user_avatar: Option<AvatarAction>,
114 pub(crate) group_avatar: Option<AvatarAction>,
115 pub(crate) mdn_reports: Vec<Report>,
116 pub(crate) delivery_report: Option<DeliveryReport>,
117
118 pub(crate) footer: Option<String>,
123
124 pub is_mime_modified: bool,
127
128 pub decoded_data: Vec<u8>,
130
131 pub(crate) hop_info: String,
133
134 pub(crate) is_bot: Option<bool>,
144
145 pub(crate) timestamp_rcvd: i64,
147 pub(crate) timestamp_sent: i64,
150}
151
152#[derive(Debug, PartialEq)]
153pub(crate) enum AvatarAction {
154 Delete,
155 Change(String),
156}
157
158#[derive(
160 Debug, Default, Display, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive, ToSql, FromSql,
161)]
162#[repr(u32)]
163pub enum SystemMessage {
164 #[default]
166 Unknown = 0,
167
168 GroupNameChanged = 2,
170
171 GroupImageChanged = 3,
173
174 MemberAddedToGroup = 4,
176
177 MemberRemovedFromGroup = 5,
179
180 AutocryptSetupMessage = 6,
182
183 SecurejoinMessage = 7,
185
186 LocationStreamingEnabled = 8,
188
189 LocationOnly = 9,
191
192 EphemeralTimerChanged = 10,
194
195 ChatProtectionEnabled = 11,
197
198 ChatProtectionDisabled = 12,
200
201 InvalidUnencryptedMail = 13,
204
205 SecurejoinWait = 14,
208
209 SecurejoinWaitTimeout = 15,
212
213 MultiDeviceSync = 20,
216
217 WebxdcStatusUpdate = 30,
221
222 WebxdcInfoMessage = 32,
224
225 IrohNodeAddr = 40,
227
228 ChatE2ee = 50,
230
231 CallAccepted = 66,
233
234 CallEnded = 67,
236}
237
238const MIME_AC_SETUP_FILE: &str = "application/autocrypt-setup";
239
240impl MimeMessage {
241 pub(crate) async fn from_bytes(
245 context: &Context,
246 body: &[u8],
247 partial: Option<u32>,
248 ) -> Result<Self> {
249 let mail = mailparse::parse_mail(body)?;
250
251 let timestamp_rcvd = smeared_time(context);
252 let mut timestamp_sent =
253 Self::get_timestamp_sent(&mail.headers, timestamp_rcvd, timestamp_rcvd);
254 let mut hop_info = parse_receive_headers(&mail.get_headers());
255
256 let mut headers = Default::default();
257 let mut headers_removed = HashSet::<String>::new();
258 let mut recipients = Default::default();
259 let mut past_members = Default::default();
260 let mut from = Default::default();
261 let mut list_post = Default::default();
262 let mut chat_disposition_notification_to = None;
263
264 MimeMessage::merge_headers(
266 context,
267 &mut headers,
268 &mut headers_removed,
269 &mut recipients,
270 &mut past_members,
271 &mut from,
272 &mut list_post,
273 &mut chat_disposition_notification_to,
274 &mail,
275 );
276 headers_removed.extend(
277 headers
278 .extract_if(|k, _v| is_hidden(k))
279 .map(|(k, _v)| k.to_string()),
280 );
281
282 let mimetype = mail.ctype.mimetype.parse::<Mime>()?;
284 let (part, mimetype) =
285 if mimetype.type_() == mime::MULTIPART && mimetype.subtype().as_str() == "signed" {
286 if let Some(part) = mail.subparts.first() {
287 timestamp_sent =
291 Self::get_timestamp_sent(&part.headers, timestamp_sent, timestamp_rcvd);
292 MimeMessage::merge_headers(
293 context,
294 &mut headers,
295 &mut headers_removed,
296 &mut recipients,
297 &mut past_members,
298 &mut from,
299 &mut list_post,
300 &mut chat_disposition_notification_to,
301 part,
302 );
303 (part, part.ctype.mimetype.parse::<Mime>()?)
304 } else {
305 (&mail, mimetype)
307 }
308 } else {
309 (&mail, mimetype)
311 };
312 if mimetype.type_() == mime::MULTIPART
313 && mimetype.subtype().as_str() == "mixed"
314 && let Some(part) = part.subparts.first()
315 {
316 for field in &part.headers {
317 let key = field.get_key().to_lowercase();
318 if !headers.contains_key(&key) && is_hidden(&key) || key == "message-id" {
319 headers.insert(key.to_string(), field.get_value());
320 }
321 }
322 }
323
324 if let Some(microsoft_message_id) = remove_header(
328 &mut headers,
329 HeaderDef::XMicrosoftOriginalMessageId.get_headername(),
330 &mut headers_removed,
331 ) {
332 headers.insert(
333 HeaderDef::MessageId.get_headername().to_string(),
334 microsoft_message_id,
335 );
336 }
337
338 Self::remove_secured_headers(&mut headers, &mut headers_removed);
341
342 let mut from = from.context("No from in message")?;
343 let private_keyring = load_self_secret_keyring(context).await?;
344
345 let dkim_results = handle_authres(context, &mail, &from.addr).await?;
346
347 let mut gossiped_keys = Default::default();
348 hop_info += "\n\n";
349 hop_info += &dkim_results.to_string();
350
351 let incoming = !context.is_self_addr(&from.addr).await?;
352
353 let mut aheader_values = mail.headers.get_all_values(HeaderDef::Autocrypt.into());
354
355 let mail_raw; let decrypted_msg; let secrets: Vec<String> = context
358 .sql
359 .query_map_vec("SELECT secret FROM broadcast_secrets", (), |row| {
360 let secret: String = row.get(0)?;
361 Ok(secret)
362 })
363 .await?;
364
365 let (mail, is_encrypted) =
366 match tokio::task::block_in_place(|| try_decrypt(&mail, &private_keyring, &secrets)) {
367 Ok(Some(mut msg)) => {
368 mail_raw = msg.as_data_vec().unwrap_or_default();
369
370 let decrypted_mail = mailparse::parse_mail(&mail_raw)?;
371 if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {
372 info!(
373 context,
374 "decrypted message mime-body:\n{}",
375 String::from_utf8_lossy(&mail_raw),
376 );
377 }
378
379 decrypted_msg = Some(msg);
380
381 timestamp_sent = Self::get_timestamp_sent(
382 &decrypted_mail.headers,
383 timestamp_sent,
384 timestamp_rcvd,
385 );
386
387 let protected_aheader_values = decrypted_mail
388 .headers
389 .get_all_values(HeaderDef::Autocrypt.into());
390 if !protected_aheader_values.is_empty() {
391 aheader_values = protected_aheader_values;
392 }
393
394 (Ok(decrypted_mail), true)
395 }
396 Ok(None) => {
397 mail_raw = Vec::new();
398 decrypted_msg = None;
399 (Ok(mail), false)
400 }
401 Err(err) => {
402 mail_raw = Vec::new();
403 decrypted_msg = None;
404 warn!(context, "decryption failed: {:#}", err);
405 (Err(err), false)
406 }
407 };
408
409 let mut autocrypt_header = None;
410 if incoming {
411 for val in aheader_values.iter().rev() {
413 autocrypt_header = match Aheader::from_str(val) {
414 Ok(header) if addr_cmp(&header.addr, &from.addr) => Some(header),
415 Ok(header) => {
416 warn!(
417 context,
418 "Autocrypt header address {:?} is not {:?}.", header.addr, from.addr
419 );
420 continue;
421 }
422 Err(err) => {
423 warn!(context, "Failed to parse Autocrypt header: {:#}.", err);
424 continue;
425 }
426 };
427 break;
428 }
429 }
430
431 let autocrypt_fingerprint = if let Some(autocrypt_header) = &autocrypt_header {
432 let fingerprint = autocrypt_header.public_key.dc_fingerprint().hex();
433 let inserted = context
434 .sql
435 .execute(
436 "INSERT INTO public_keys (fingerprint, public_key)
437 VALUES (?, ?)
438 ON CONFLICT (fingerprint)
439 DO NOTHING",
440 (&fingerprint, autocrypt_header.public_key.to_bytes()),
441 )
442 .await?;
443 if inserted > 0 {
444 info!(
445 context,
446 "Saved key with fingerprint {fingerprint} from the Autocrypt header"
447 );
448 }
449 Some(fingerprint)
450 } else {
451 None
452 };
453
454 let mut public_keyring = if incoming {
455 if let Some(autocrypt_header) = autocrypt_header {
456 vec![autocrypt_header.public_key]
457 } else {
458 vec![]
459 }
460 } else {
461 key::load_self_public_keyring(context).await?
462 };
463
464 if let Some(signature) = match &decrypted_msg {
465 Some(pgp::composed::Message::Literal { .. }) => None,
466 Some(pgp::composed::Message::Compressed { .. }) => {
467 None
470 }
471 Some(pgp::composed::Message::SignedOnePass { reader, .. }) => reader.signature(),
472 Some(pgp::composed::Message::Signed { reader, .. }) => Some(reader.signature()),
473 Some(pgp::composed::Message::Encrypted { .. }) => {
474 None
476 }
477 None => None,
478 } {
479 for issuer_fingerprint in signature.issuer_fingerprint() {
480 let issuer_fingerprint =
481 crate::key::Fingerprint::from(issuer_fingerprint.clone()).hex();
482 if let Some(public_key_bytes) = context
483 .sql
484 .query_row_optional(
485 "SELECT public_key
486 FROM public_keys
487 WHERE fingerprint=?",
488 (&issuer_fingerprint,),
489 |row| {
490 let bytes: Vec<u8> = row.get(0)?;
491 Ok(bytes)
492 },
493 )
494 .await?
495 {
496 let public_key = SignedPublicKey::from_slice(&public_key_bytes)?;
497 public_keyring.push(public_key)
498 }
499 }
500 }
501
502 let mut signatures = if let Some(ref decrypted_msg) = decrypted_msg {
503 crate::pgp::valid_signature_fingerprints(decrypted_msg, &public_keyring)
504 } else {
505 HashSet::new()
506 };
507
508 let mail = mail.as_ref().map(|mail| {
509 let (content, signatures_detached) = validate_detached_signature(mail, &public_keyring)
510 .unwrap_or((mail, Default::default()));
511 signatures.extend(signatures_detached);
512 content
513 });
514 if let (Ok(mail), true) = (mail, is_encrypted) {
515 if !signatures.is_empty() {
516 remove_header(&mut headers, "subject", &mut headers_removed);
520 remove_header(&mut headers, "list-id", &mut headers_removed);
521 }
522
523 let mut inner_from = None;
529
530 MimeMessage::merge_headers(
531 context,
532 &mut headers,
533 &mut headers_removed,
534 &mut recipients,
535 &mut past_members,
536 &mut inner_from,
537 &mut list_post,
538 &mut chat_disposition_notification_to,
539 mail,
540 );
541
542 if !signatures.is_empty() {
543 let gossip_headers = mail.headers.get_all_values("Autocrypt-Gossip");
548 gossiped_keys =
549 parse_gossip_headers(context, &from.addr, &recipients, gossip_headers).await?;
550 }
551
552 if let Some(inner_from) = inner_from {
553 if !addr_cmp(&inner_from.addr, &from.addr) {
554 warn!(
563 context,
564 "From header in encrypted part doesn't match the outer one",
565 );
566
567 bail!("From header is forged");
572 }
573 from = inner_from;
574 }
575 }
576 if signatures.is_empty() {
577 Self::remove_secured_headers(&mut headers, &mut headers_removed);
578 }
579 if !is_encrypted {
580 signatures.clear();
581 }
582
583 let mut parser = MimeMessage {
584 parts: Vec::new(),
585 headers,
586 #[cfg(test)]
587 headers_removed,
588
589 recipients,
590 past_members,
591 list_post,
592 from,
593 incoming,
594 chat_disposition_notification_to,
595 decrypting_failed: mail.is_err(),
596
597 signature: signatures.into_iter().last(),
599 autocrypt_fingerprint,
600 gossiped_keys,
601 is_forwarded: false,
602 mdn_reports: Vec::new(),
603 is_system_message: SystemMessage::Unknown,
604 location_kml: None,
605 message_kml: None,
606 sync_items: None,
607 webxdc_status_update: None,
608 user_avatar: None,
609 group_avatar: None,
610 delivery_report: None,
611 footer: None,
612 is_mime_modified: false,
613 decoded_data: Vec::new(),
614 hop_info,
615 is_bot: None,
616 timestamp_rcvd,
617 timestamp_sent,
618 };
619
620 match partial {
621 Some(org_bytes) => {
622 parser
623 .create_stub_from_partial_download(context, org_bytes)
624 .await?;
625 }
626 None => match mail {
627 Ok(mail) => {
628 parser.parse_mime_recursive(context, mail, false).await?;
629 }
630 Err(err) => {
631 let txt = "[This message cannot be decrypted.\n\n• It might already help to simply reply to this message and ask the sender to send the message again.\n\n• If you just re-installed Delta Chat then it is best if you re-setup Delta Chat now and choose \"Add as second device\" or import a backup.]";
632
633 let part = Part {
634 typ: Viewtype::Text,
635 msg_raw: Some(txt.to_string()),
636 msg: txt.to_string(),
637 error: Some(format!("Decrypting failed: {err:#}")),
640 ..Default::default()
641 };
642 parser.do_add_single_part(part);
643 }
644 },
645 };
646
647 let is_location_only = parser.location_kml.is_some() && parser.parts.is_empty();
648 if parser.mdn_reports.is_empty()
649 && !is_location_only
650 && parser.sync_items.is_none()
651 && parser.webxdc_status_update.is_none()
652 {
653 let is_bot =
654 parser.headers.get("auto-submitted") == Some(&"auto-generated".to_string());
655 parser.is_bot = Some(is_bot);
656 }
657 parser.maybe_remove_bad_parts();
658 parser.maybe_remove_inline_mailinglist_footer();
659 parser.heuristically_parse_ndn(context).await;
660 parser.parse_headers(context).await?;
661 parser.decoded_data = mail_raw;
662
663 Ok(parser)
664 }
665
666 fn get_timestamp_sent(
667 hdrs: &[mailparse::MailHeader<'_>],
668 default: i64,
669 timestamp_rcvd: i64,
670 ) -> i64 {
671 hdrs.get_header_value(HeaderDef::Date)
672 .and_then(|v| mailparse::dateparse(&v).ok())
673 .map_or(default, |value| {
674 min(value, timestamp_rcvd + constants::TIMESTAMP_SENT_TOLERANCE)
675 })
676 }
677
678 fn parse_system_message_headers(&mut self, context: &Context) {
680 if self.get_header(HeaderDef::AutocryptSetupMessage).is_some() && !self.incoming {
681 self.parts.retain(|part| {
682 part.mimetype.is_none()
683 || part.mimetype.as_ref().unwrap().as_ref() == MIME_AC_SETUP_FILE
684 });
685
686 if self.parts.len() == 1 {
687 self.is_system_message = SystemMessage::AutocryptSetupMessage;
688 } else {
689 warn!(context, "could not determine ASM mime-part");
690 }
691 } else if let Some(value) = self.get_header(HeaderDef::ChatContent) {
692 if value == "location-streaming-enabled" {
693 self.is_system_message = SystemMessage::LocationStreamingEnabled;
694 } else if value == "ephemeral-timer-changed" {
695 self.is_system_message = SystemMessage::EphemeralTimerChanged;
696 } else if value == "protection-enabled" {
697 self.is_system_message = SystemMessage::ChatProtectionEnabled;
698 } else if value == "protection-disabled" {
699 self.is_system_message = SystemMessage::ChatProtectionDisabled;
700 } else if value == "group-avatar-changed" {
701 self.is_system_message = SystemMessage::GroupImageChanged;
702 } else if value == "call-accepted" {
703 self.is_system_message = SystemMessage::CallAccepted;
704 } else if value == "call-ended" {
705 self.is_system_message = SystemMessage::CallEnded;
706 }
707 } else if self.get_header(HeaderDef::ChatGroupMemberRemoved).is_some() {
708 self.is_system_message = SystemMessage::MemberRemovedFromGroup;
709 } else if self.get_header(HeaderDef::ChatGroupMemberAdded).is_some() {
710 self.is_system_message = SystemMessage::MemberAddedToGroup;
711 } else if self.get_header(HeaderDef::ChatGroupNameChanged).is_some() {
712 self.is_system_message = SystemMessage::GroupNameChanged;
713 }
714 }
715
716 fn parse_avatar_headers(&mut self, context: &Context) -> Result<()> {
718 if let Some(header_value) = self.get_header(HeaderDef::ChatGroupAvatar) {
719 self.group_avatar =
720 self.avatar_action_from_header(context, header_value.to_string())?;
721 }
722
723 if let Some(header_value) = self.get_header(HeaderDef::ChatUserAvatar) {
724 self.user_avatar = self.avatar_action_from_header(context, header_value.to_string())?;
725 }
726 Ok(())
727 }
728
729 fn parse_videochat_headers(&mut self) {
730 let content = self
731 .get_header(HeaderDef::ChatContent)
732 .unwrap_or_default()
733 .to_string();
734 let room = self
735 .get_header(HeaderDef::ChatWebrtcRoom)
736 .map(|s| s.to_string());
737 let accepted = self
738 .get_header(HeaderDef::ChatWebrtcAccepted)
739 .map(|s| s.to_string());
740 if let Some(part) = self.parts.first_mut() {
741 if let Some(room) = room {
742 if content == "call" {
743 part.typ = Viewtype::Call;
744 part.param.set(Param::WebrtcRoom, room);
745 }
746 } else if let Some(accepted) = accepted {
747 part.param.set(Param::WebrtcAccepted, accepted);
748 }
749 }
750 }
751
752 fn squash_attachment_parts(&mut self) {
758 if self.parts.len() == 2
759 && self.parts.first().map(|textpart| textpart.typ) == Some(Viewtype::Text)
760 && self
761 .parts
762 .get(1)
763 .is_some_and(|filepart| match filepart.typ {
764 Viewtype::Image
765 | Viewtype::Gif
766 | Viewtype::Sticker
767 | Viewtype::Audio
768 | Viewtype::Voice
769 | Viewtype::Video
770 | Viewtype::Vcard
771 | Viewtype::File
772 | Viewtype::Webxdc => true,
773 Viewtype::Unknown | Viewtype::Text | Viewtype::Call => false,
774 })
775 {
776 let mut parts = std::mem::take(&mut self.parts);
777 let Some(mut filepart) = parts.pop() else {
778 return;
780 };
781 let Some(textpart) = parts.pop() else {
782 return;
784 };
785
786 filepart.msg.clone_from(&textpart.msg);
787 if let Some(quote) = textpart.param.get(Param::Quote) {
788 filepart.param.set(Param::Quote, quote);
789 }
790
791 self.parts = vec![filepart];
792 }
793 }
794
795 fn parse_attachments(&mut self) {
797 if self.parts.len() != 1 {
800 return;
801 }
802
803 if let Some(mut part) = self.parts.pop() {
804 if part.typ == Viewtype::Audio && self.get_header(HeaderDef::ChatVoiceMessage).is_some()
805 {
806 part.typ = Viewtype::Voice;
807 }
808 if (part.typ == Viewtype::Image || part.typ == Viewtype::Gif)
809 && let Some(value) = self.get_header(HeaderDef::ChatContent)
810 && value == "sticker"
811 {
812 part.typ = Viewtype::Sticker;
813 }
814 if (part.typ == Viewtype::Audio
815 || part.typ == Viewtype::Voice
816 || part.typ == Viewtype::Video)
817 && let Some(field_0) = self.get_header(HeaderDef::ChatDuration)
818 {
819 let duration_ms = field_0.parse().unwrap_or_default();
820 if duration_ms > 0 && duration_ms < 24 * 60 * 60 * 1000 {
821 part.param.set_int(Param::Duration, duration_ms);
822 }
823 }
824
825 self.parts.push(part);
826 }
827 }
828
829 async fn parse_headers(&mut self, context: &Context) -> Result<()> {
830 self.parse_system_message_headers(context);
831 self.parse_avatar_headers(context)?;
832 self.parse_videochat_headers();
833 if self.delivery_report.is_none() {
834 self.squash_attachment_parts();
835 }
836
837 if !context.get_config_bool(Config::Bot).await?
838 && let Some(ref subject) = self.get_subject()
839 {
840 let mut prepend_subject = true;
841 if !self.decrypting_failed {
842 let colon = subject.find(':');
843 if colon == Some(2)
844 || colon == Some(3)
845 || self.has_chat_version()
846 || subject.contains("Chat:")
847 {
848 prepend_subject = false
849 }
850 }
851
852 if self.is_mailinglist_message() && !self.has_chat_version() {
855 prepend_subject = true;
856 }
857
858 if prepend_subject && !subject.is_empty() {
859 let part_with_text = self
860 .parts
861 .iter_mut()
862 .find(|part| !part.msg.is_empty() && !part.is_reaction);
863 if let Some(part) = part_with_text {
864 part.msg = format!("{} – {}", subject, part.msg);
869 }
870 }
871 }
872
873 if self.is_forwarded {
874 for part in &mut self.parts {
875 part.param.set_int(Param::Forwarded, 1);
876 }
877 }
878
879 self.parse_attachments();
880
881 if !self.decrypting_failed
883 && !self.parts.is_empty()
884 && let Some(ref dn_to) = self.chat_disposition_notification_to
885 {
886 let from = &self.from.addr;
888 if !context.is_self_addr(from).await? {
889 if from.to_lowercase() == dn_to.addr.to_lowercase() {
890 if let Some(part) = self.parts.last_mut() {
891 part.param.set_int(Param::WantsMdn, 1);
892 }
893 } else {
894 warn!(
895 context,
896 "{} requested a read receipt to {}, ignoring", from, dn_to.addr
897 );
898 }
899 }
900 }
901
902 if self.parts.is_empty() && self.mdn_reports.is_empty() {
907 let mut part = Part {
908 typ: Viewtype::Text,
909 ..Default::default()
910 };
911
912 if let Some(ref subject) = self.get_subject()
913 && !self.has_chat_version()
914 && self.webxdc_status_update.is_none()
915 {
916 part.msg = subject.to_string();
917 }
918
919 self.do_add_single_part(part);
920 }
921
922 if self.is_bot == Some(true) {
923 for part in &mut self.parts {
924 part.param.set(Param::Bot, "1");
925 }
926 }
927
928 Ok(())
929 }
930
931 fn avatar_action_from_header(
932 &mut self,
933 context: &Context,
934 header_value: String,
935 ) -> Result<Option<AvatarAction>> {
936 let res = if header_value == "0" {
937 Some(AvatarAction::Delete)
938 } else if let Some(base64) = header_value
939 .split_ascii_whitespace()
940 .collect::<String>()
941 .strip_prefix("base64:")
942 {
943 match BlobObject::store_from_base64(context, base64)? {
944 Some(path) => Some(AvatarAction::Change(path)),
945 None => {
946 warn!(context, "Could not decode avatar base64");
947 None
948 }
949 }
950 } else {
951 let mut i = 0;
954 while let Some(part) = self.parts.get_mut(i) {
955 if let Some(part_filename) = &part.org_filename
956 && part_filename == &header_value
957 {
958 if let Some(blob) = part.param.get(Param::File) {
959 let res = Some(AvatarAction::Change(blob.to_string()));
960 self.parts.remove(i);
961 return Ok(res);
962 }
963 break;
964 }
965 i += 1;
966 }
967 None
968 };
969 Ok(res)
970 }
971
972 pub fn was_encrypted(&self) -> bool {
978 self.signature.is_some()
979 }
980
981 pub(crate) fn has_chat_version(&self) -> bool {
984 self.headers.contains_key("chat-version")
985 }
986
987 pub(crate) fn get_subject(&self) -> Option<String> {
988 self.get_header(HeaderDef::Subject)
989 .map(|s| s.trim_start())
990 .filter(|s| !s.is_empty())
991 .map(|s| s.to_string())
992 }
993
994 pub fn get_header(&self, headerdef: HeaderDef) -> Option<&str> {
995 self.headers
996 .get(headerdef.get_headername())
997 .map(|s| s.as_str())
998 }
999
1000 #[cfg(test)]
1001 pub(crate) fn header_exists(&self, headerdef: HeaderDef) -> bool {
1006 let hname = headerdef.get_headername();
1007 self.headers.contains_key(hname) || self.headers_removed.contains(hname)
1008 }
1009
1010 #[cfg(test)]
1011 pub(crate) fn decoded_data_contains(&self, s: &str) -> bool {
1013 assert!(!self.decrypting_failed);
1014 let decoded_str = str::from_utf8(&self.decoded_data).unwrap();
1015 decoded_str.contains(s)
1016 }
1017
1018 pub fn get_chat_group_id(&self) -> Option<&str> {
1020 self.get_header(HeaderDef::ChatGroupId)
1021 .filter(|s| validate_id(s))
1022 }
1023
1024 async fn parse_mime_recursive<'a>(
1025 &'a mut self,
1026 context: &'a Context,
1027 mail: &'a mailparse::ParsedMail<'a>,
1028 is_related: bool,
1029 ) -> Result<bool> {
1030 enum MimeS {
1031 Multiple,
1032 Single,
1033 Message,
1034 }
1035
1036 let mimetype = mail.ctype.mimetype.to_lowercase();
1037
1038 let m = if mimetype.starts_with("multipart") {
1039 if mail.ctype.params.contains_key("boundary") {
1040 MimeS::Multiple
1041 } else {
1042 MimeS::Single
1043 }
1044 } else if mimetype.starts_with("message") {
1045 if mimetype == "message/rfc822" && !is_attachment_disposition(mail) {
1046 MimeS::Message
1047 } else {
1048 MimeS::Single
1049 }
1050 } else {
1051 MimeS::Single
1052 };
1053
1054 let is_related = is_related || mimetype == "multipart/related";
1055 match m {
1056 MimeS::Multiple => Box::pin(self.handle_multiple(context, mail, is_related)).await,
1057 MimeS::Message => {
1058 let raw = mail.get_body_raw()?;
1059 if raw.is_empty() {
1060 return Ok(false);
1061 }
1062 let mail = mailparse::parse_mail(&raw).context("failed to parse mail")?;
1063
1064 Box::pin(self.parse_mime_recursive(context, &mail, is_related)).await
1065 }
1066 MimeS::Single => {
1067 self.add_single_part_if_known(context, mail, is_related)
1068 .await
1069 }
1070 }
1071 }
1072
1073 async fn handle_multiple(
1074 &mut self,
1075 context: &Context,
1076 mail: &mailparse::ParsedMail<'_>,
1077 is_related: bool,
1078 ) -> Result<bool> {
1079 let mut any_part_added = false;
1080 let mimetype = get_mime_type(
1081 mail,
1082 &get_attachment_filename(context, mail)?,
1083 self.has_chat_version(),
1084 )?
1085 .0;
1086 match (mimetype.type_(), mimetype.subtype().as_str()) {
1087 (mime::MULTIPART, "alternative") => {
1088 for cur_data in mail.subparts.iter().rev() {
1100 let (mime_type, _viewtype) = get_mime_type(
1101 cur_data,
1102 &get_attachment_filename(context, cur_data)?,
1103 self.has_chat_version(),
1104 )?;
1105
1106 if mime_type == mime::TEXT_PLAIN || mime_type.type_() == mime::MULTIPART {
1107 any_part_added = self
1108 .parse_mime_recursive(context, cur_data, is_related)
1109 .await?;
1110 break;
1111 }
1112 }
1113
1114 for cur_data in mail.subparts.iter().rev() {
1123 let mimetype = cur_data.ctype.mimetype.parse::<Mime>()?;
1124 if mimetype.type_() == mime::TEXT && mimetype.subtype() == "calendar" {
1125 let filename = get_attachment_filename(context, cur_data)?
1126 .unwrap_or_else(|| "calendar.ics".to_string());
1127 self.do_add_single_file_part(
1128 context,
1129 Viewtype::File,
1130 mimetype,
1131 &mail.ctype.mimetype.to_lowercase(),
1132 &mail.get_body_raw()?,
1133 &filename,
1134 is_related,
1135 )
1136 .await?;
1137 }
1138 }
1139
1140 if !any_part_added {
1141 for cur_part in mail.subparts.iter().rev() {
1142 if self
1143 .parse_mime_recursive(context, cur_part, is_related)
1144 .await?
1145 {
1146 any_part_added = true;
1147 break;
1148 }
1149 }
1150 }
1151 if any_part_added && mail.subparts.len() > 1 {
1152 self.is_mime_modified = true;
1156 }
1157 }
1158 (mime::MULTIPART, "signed") => {
1159 if let Some(first) = mail.subparts.first() {
1168 any_part_added = self
1169 .parse_mime_recursive(context, first, is_related)
1170 .await?;
1171 }
1172 }
1173 (mime::MULTIPART, "report") => {
1174 if mail.subparts.len() >= 2 {
1176 match mail.ctype.params.get("report-type").map(|s| s as &str) {
1177 Some("disposition-notification") => {
1178 if let Some(report) = self.process_report(context, mail)? {
1179 self.mdn_reports.push(report);
1180 }
1181
1182 let part = Part {
1187 typ: Viewtype::Unknown,
1188 ..Default::default()
1189 };
1190 self.parts.push(part);
1191
1192 any_part_added = true;
1193 }
1194 Some("delivery-status") | None => {
1196 if let Some(report) = self.process_delivery_status(context, mail)? {
1197 self.delivery_report = Some(report);
1198 }
1199
1200 for cur_data in &mail.subparts {
1202 if self
1203 .parse_mime_recursive(context, cur_data, is_related)
1204 .await?
1205 {
1206 any_part_added = true;
1207 }
1208 }
1209 }
1210 Some("multi-device-sync") => {
1211 if let Some(second) = mail.subparts.get(1) {
1212 self.add_single_part_if_known(context, second, is_related)
1213 .await?;
1214 }
1215 }
1216 Some("status-update") => {
1217 if let Some(second) = mail.subparts.get(1) {
1218 self.add_single_part_if_known(context, second, is_related)
1219 .await?;
1220 }
1221 }
1222 Some(_) => {
1223 for cur_data in &mail.subparts {
1224 if self
1225 .parse_mime_recursive(context, cur_data, is_related)
1226 .await?
1227 {
1228 any_part_added = true;
1229 }
1230 }
1231 }
1232 }
1233 }
1234 }
1235 _ => {
1236 for cur_data in &mail.subparts {
1239 if self
1240 .parse_mime_recursive(context, cur_data, is_related)
1241 .await?
1242 {
1243 any_part_added = true;
1244 }
1245 }
1246 }
1247 }
1248
1249 Ok(any_part_added)
1250 }
1251
1252 async fn add_single_part_if_known(
1254 &mut self,
1255 context: &Context,
1256 mail: &mailparse::ParsedMail<'_>,
1257 is_related: bool,
1258 ) -> Result<bool> {
1259 let filename = get_attachment_filename(context, mail)?;
1261 let (mime_type, msg_type) = get_mime_type(mail, &filename, self.has_chat_version())?;
1262 let raw_mime = mail.ctype.mimetype.to_lowercase();
1263
1264 let old_part_count = self.parts.len();
1265
1266 match filename {
1267 Some(filename) => {
1268 self.do_add_single_file_part(
1269 context,
1270 msg_type,
1271 mime_type,
1272 &raw_mime,
1273 &mail.get_body_raw()?,
1274 &filename,
1275 is_related,
1276 )
1277 .await?;
1278 }
1279 None => {
1280 match mime_type.type_() {
1281 mime::IMAGE | mime::AUDIO | mime::VIDEO | mime::APPLICATION => {
1282 warn!(context, "Missing attachment");
1283 return Ok(false);
1284 }
1285 mime::TEXT
1286 if mail.get_content_disposition().disposition
1287 == DispositionType::Extension("reaction".to_string()) =>
1288 {
1289 let decoded_data = match mail.get_body() {
1291 Ok(decoded_data) => decoded_data,
1292 Err(err) => {
1293 warn!(context, "Invalid body parsed {:#}", err);
1294 return Ok(false);
1296 }
1297 };
1298
1299 let part = Part {
1300 typ: Viewtype::Text,
1301 mimetype: Some(mime_type),
1302 msg: decoded_data,
1303 is_reaction: true,
1304 ..Default::default()
1305 };
1306 self.do_add_single_part(part);
1307 return Ok(true);
1308 }
1309 mime::TEXT | mime::HTML => {
1310 let decoded_data = match mail.get_body() {
1311 Ok(decoded_data) => decoded_data,
1312 Err(err) => {
1313 warn!(context, "Invalid body parsed {:#}", err);
1314 return Ok(false);
1316 }
1317 };
1318
1319 let is_plaintext = mime_type == mime::TEXT_PLAIN;
1320 let mut dehtml_failed = false;
1321
1322 let SimplifiedText {
1323 text: simplified_txt,
1324 is_forwarded,
1325 is_cut,
1326 top_quote,
1327 footer,
1328 } = if decoded_data.is_empty() {
1329 Default::default()
1330 } else {
1331 let is_html = mime_type == mime::TEXT_HTML;
1332 if is_html {
1333 self.is_mime_modified = true;
1334 if let Some(text) = dehtml(&decoded_data) {
1339 text
1340 } else {
1341 dehtml_failed = true;
1342 SimplifiedText {
1343 text: decoded_data.clone(),
1344 ..Default::default()
1345 }
1346 }
1347 } else {
1348 simplify(decoded_data.clone(), self.has_chat_version())
1349 }
1350 };
1351
1352 self.is_mime_modified = self.is_mime_modified
1353 || ((is_forwarded || is_cut || top_quote.is_some())
1354 && !self.has_chat_version());
1355
1356 let is_format_flowed = if let Some(format) = mail.ctype.params.get("format")
1357 {
1358 format.as_str().eq_ignore_ascii_case("flowed")
1359 } else {
1360 false
1361 };
1362
1363 let (simplified_txt, simplified_quote) = if mime_type.type_() == mime::TEXT
1364 && mime_type.subtype() == mime::PLAIN
1365 {
1366 let simplified_txt = match mail
1369 .ctype
1370 .params
1371 .get("hp-legacy-display")
1372 .is_some_and(|v| v == "1")
1373 {
1374 false => simplified_txt,
1375 true => rm_legacy_display_elements(&simplified_txt),
1376 };
1377 if is_format_flowed {
1378 let delsp = if let Some(delsp) = mail.ctype.params.get("delsp") {
1379 delsp.as_str().eq_ignore_ascii_case("yes")
1380 } else {
1381 false
1382 };
1383 let unflowed_text = unformat_flowed(&simplified_txt, delsp);
1384 let unflowed_quote = top_quote.map(|q| unformat_flowed(&q, delsp));
1385 (unflowed_text, unflowed_quote)
1386 } else {
1387 (simplified_txt, top_quote)
1388 }
1389 } else {
1390 (simplified_txt, top_quote)
1391 };
1392
1393 let (simplified_txt, was_truncated) =
1394 truncate_msg_text(context, simplified_txt).await?;
1395 if was_truncated {
1396 self.is_mime_modified = was_truncated;
1397 }
1398
1399 if !simplified_txt.is_empty() || simplified_quote.is_some() {
1400 let mut part = Part {
1401 dehtml_failed,
1402 typ: Viewtype::Text,
1403 mimetype: Some(mime_type),
1404 msg: simplified_txt,
1405 ..Default::default()
1406 };
1407 if let Some(quote) = simplified_quote {
1408 part.param.set(Param::Quote, quote);
1409 }
1410 part.msg_raw = Some(decoded_data);
1411 self.do_add_single_part(part);
1412 }
1413
1414 if is_forwarded {
1415 self.is_forwarded = true;
1416 }
1417
1418 if self.footer.is_none() && is_plaintext {
1419 self.footer = Some(footer.unwrap_or_default());
1420 }
1421 }
1422 _ => {}
1423 }
1424 }
1425 }
1426
1427 Ok(self.parts.len() > old_part_count)
1429 }
1430
1431 #[expect(clippy::too_many_arguments)]
1432 async fn do_add_single_file_part(
1433 &mut self,
1434 context: &Context,
1435 msg_type: Viewtype,
1436 mime_type: Mime,
1437 raw_mime: &str,
1438 decoded_data: &[u8],
1439 filename: &str,
1440 is_related: bool,
1441 ) -> Result<()> {
1442 if mime_type.type_() == mime::APPLICATION
1444 && mime_type.subtype().as_str() == "pgp-keys"
1445 && Self::try_set_peer_key_from_file_part(context, decoded_data).await?
1446 {
1447 return Ok(());
1448 }
1449 let mut part = Part::default();
1450 let msg_type = if context
1451 .is_webxdc_file(filename, decoded_data)
1452 .await
1453 .unwrap_or(false)
1454 {
1455 Viewtype::Webxdc
1456 } else if filename.ends_with(".kml") {
1457 if filename.starts_with("location") || filename.starts_with("message") {
1460 let parsed = location::Kml::parse(decoded_data)
1461 .map_err(|err| {
1462 warn!(context, "failed to parse kml part: {:#}", err);
1463 })
1464 .ok();
1465 if filename.starts_with("location") {
1466 self.location_kml = parsed;
1467 } else {
1468 self.message_kml = parsed;
1469 }
1470 return Ok(());
1471 }
1472 msg_type
1473 } else if filename == "multi-device-sync.json" {
1474 if !context.get_config_bool(Config::SyncMsgs).await? {
1475 return Ok(());
1476 }
1477 let serialized = String::from_utf8_lossy(decoded_data)
1478 .parse()
1479 .unwrap_or_default();
1480 self.sync_items = context
1481 .parse_sync_items(serialized)
1482 .map_err(|err| {
1483 warn!(context, "failed to parse sync data: {:#}", err);
1484 })
1485 .ok();
1486 return Ok(());
1487 } else if filename == "status-update.json" {
1488 let serialized = String::from_utf8_lossy(decoded_data)
1489 .parse()
1490 .unwrap_or_default();
1491 self.webxdc_status_update = Some(serialized);
1492 return Ok(());
1493 } else if msg_type == Viewtype::Vcard {
1494 if let Some(summary) = get_vcard_summary(decoded_data) {
1495 part.param.set(Param::Summary1, summary);
1496 msg_type
1497 } else {
1498 Viewtype::File
1499 }
1500 } else if msg_type == Viewtype::Image
1501 || msg_type == Viewtype::Gif
1502 || msg_type == Viewtype::Sticker
1503 {
1504 match get_filemeta(decoded_data) {
1505 Ok((width, height)) if width * height <= constants::MAX_RCVD_IMAGE_PIXELS => {
1507 part.param.set_i64(Param::Width, width.into());
1508 part.param.set_i64(Param::Height, height.into());
1509 msg_type
1510 }
1511 _ => Viewtype::File,
1513 }
1514 } else {
1515 msg_type
1516 };
1517
1518 let blob =
1522 match BlobObject::create_and_deduplicate_from_bytes(context, decoded_data, filename) {
1523 Ok(blob) => blob,
1524 Err(err) => {
1525 error!(
1526 context,
1527 "Could not add blob for mime part {}, error {:#}", filename, err
1528 );
1529 return Ok(());
1530 }
1531 };
1532 info!(context, "added blobfile: {:?}", blob.as_name());
1533
1534 part.typ = msg_type;
1535 part.org_filename = Some(filename.to_string());
1536 part.mimetype = Some(mime_type);
1537 part.bytes = decoded_data.len();
1538 part.param.set(Param::File, blob.as_name());
1539 part.param.set(Param::Filename, filename);
1540 part.param.set(Param::MimeType, raw_mime);
1541 part.is_related = is_related;
1542
1543 self.do_add_single_part(part);
1544 Ok(())
1545 }
1546
1547 async fn try_set_peer_key_from_file_part(
1549 context: &Context,
1550 decoded_data: &[u8],
1551 ) -> Result<bool> {
1552 let key = match str::from_utf8(decoded_data) {
1553 Err(err) => {
1554 warn!(context, "PGP key attachment is not a UTF-8 file: {}", err);
1555 return Ok(false);
1556 }
1557 Ok(key) => key,
1558 };
1559 let key = match SignedPublicKey::from_asc(key) {
1560 Err(err) => {
1561 warn!(
1562 context,
1563 "PGP key attachment is not an ASCII-armored file: {err:#}."
1564 );
1565 return Ok(false);
1566 }
1567 Ok(key) => key,
1568 };
1569 if let Err(err) = key.verify() {
1570 warn!(context, "Attached PGP key verification failed: {err:#}.");
1571 return Ok(false);
1572 }
1573
1574 let fingerprint = key.dc_fingerprint().hex();
1575 context
1576 .sql
1577 .execute(
1578 "INSERT INTO public_keys (fingerprint, public_key)
1579 VALUES (?, ?)
1580 ON CONFLICT (fingerprint)
1581 DO NOTHING",
1582 (&fingerprint, key.to_bytes()),
1583 )
1584 .await?;
1585
1586 info!(context, "Imported PGP key {fingerprint} from attachment.");
1587 Ok(true)
1588 }
1589
1590 pub(crate) fn do_add_single_part(&mut self, mut part: Part) {
1591 if self.was_encrypted() {
1592 part.param.set_int(Param::GuaranteeE2ee, 1);
1593 }
1594 self.parts.push(part);
1595 }
1596
1597 pub(crate) fn get_mailinglist_header(&self) -> Option<&str> {
1598 if let Some(list_id) = self.get_header(HeaderDef::ListId) {
1599 return Some(list_id);
1602 } else if let Some(chat_list_id) = self.get_header(HeaderDef::ChatListId) {
1603 return Some(chat_list_id);
1604 } else if let Some(sender) = self.get_header(HeaderDef::Sender) {
1605 if let Some(precedence) = self.get_header(HeaderDef::Precedence)
1608 && (precedence == "list" || precedence == "bulk")
1609 {
1610 return Some(sender);
1614 }
1615 }
1616 None
1617 }
1618
1619 pub(crate) fn is_mailinglist_message(&self) -> bool {
1620 self.get_mailinglist_header().is_some()
1621 }
1622
1623 pub(crate) fn is_schleuder_message(&self) -> bool {
1625 if let Some(list_help) = self.get_header(HeaderDef::ListHelp) {
1626 list_help == "<https://schleuder.org/>"
1627 } else {
1628 false
1629 }
1630 }
1631
1632 pub(crate) fn is_call(&self) -> bool {
1634 self.parts
1635 .first()
1636 .is_some_and(|part| part.typ == Viewtype::Call)
1637 }
1638
1639 pub(crate) fn get_rfc724_mid(&self) -> Option<String> {
1640 self.get_header(HeaderDef::MessageId)
1641 .and_then(|msgid| parse_message_id(msgid).ok())
1642 }
1643
1644 fn remove_secured_headers(
1645 headers: &mut HashMap<String, String>,
1646 removed: &mut HashSet<String>,
1647 ) {
1648 remove_header(headers, "secure-join-fingerprint", removed);
1649 remove_header(headers, "secure-join-auth", removed);
1650 remove_header(headers, "chat-verified", removed);
1651 remove_header(headers, "autocrypt-gossip", removed);
1652
1653 if let Some(secure_join) = remove_header(headers, "secure-join", removed)
1655 && (secure_join == "vc-request" || secure_join == "vg-request")
1656 {
1657 headers.insert("secure-join".to_string(), secure_join);
1658 }
1659 }
1660
1661 #[allow(clippy::too_many_arguments)]
1667 fn merge_headers(
1668 context: &Context,
1669 headers: &mut HashMap<String, String>,
1670 headers_removed: &mut HashSet<String>,
1671 recipients: &mut Vec<SingleInfo>,
1672 past_members: &mut Vec<SingleInfo>,
1673 from: &mut Option<SingleInfo>,
1674 list_post: &mut Option<String>,
1675 chat_disposition_notification_to: &mut Option<SingleInfo>,
1676 part: &mailparse::ParsedMail,
1677 ) {
1678 let fields = &part.headers;
1679 let has_header_protection = part.ctype.params.contains_key("hp");
1681
1682 headers_removed.extend(
1683 headers
1684 .extract_if(|k, _v| has_header_protection || is_protected(k))
1685 .map(|(k, _v)| k.to_string()),
1686 );
1687 for field in fields {
1688 let key = field.get_key().to_lowercase();
1690 if key == HeaderDef::ChatDispositionNotificationTo.get_headername() {
1691 match addrparse_header(field) {
1692 Ok(addrlist) => {
1693 *chat_disposition_notification_to = addrlist.extract_single_info();
1694 }
1695 Err(e) => warn!(context, "Could not read {} address: {}", key, e),
1696 }
1697 } else {
1698 let value = field.get_value();
1699 headers.insert(key.to_string(), value);
1700 }
1701 }
1702 let recipients_new = get_recipients(fields);
1703 if !recipients_new.is_empty() {
1704 *recipients = recipients_new;
1705 }
1706 let past_members_addresses =
1707 get_all_addresses_from_header(fields, "chat-group-past-members");
1708 if !past_members_addresses.is_empty() {
1709 *past_members = past_members_addresses;
1710 }
1711 let from_new = get_from(fields);
1712 if from_new.is_some() {
1713 *from = from_new;
1714 }
1715 let list_post_new = get_list_post(fields);
1716 if list_post_new.is_some() {
1717 *list_post = list_post_new;
1718 }
1719 }
1720
1721 fn process_report(
1722 &self,
1723 context: &Context,
1724 report: &mailparse::ParsedMail<'_>,
1725 ) -> Result<Option<Report>> {
1726 let report_body = if let Some(subpart) = report.subparts.get(1) {
1728 subpart.get_body_raw()?
1729 } else {
1730 bail!("Report does not have second MIME part");
1731 };
1732 let (report_fields, _) = mailparse::parse_headers(&report_body)?;
1733
1734 if report_fields
1736 .get_header_value(HeaderDef::Disposition)
1737 .is_none()
1738 {
1739 warn!(
1740 context,
1741 "Ignoring unknown disposition-notification, Message-Id: {:?}.",
1742 report_fields.get_header_value(HeaderDef::MessageId)
1743 );
1744 return Ok(None);
1745 };
1746
1747 let original_message_id = report_fields
1748 .get_header_value(HeaderDef::OriginalMessageId)
1749 .or_else(|| report.headers.get_header_value(HeaderDef::InReplyTo))
1752 .and_then(|v| parse_message_id(&v).ok());
1753 let additional_message_ids = report_fields
1754 .get_header_value(HeaderDef::AdditionalMessageIds)
1755 .map_or_else(Vec::new, |v| {
1756 v.split(' ')
1757 .filter_map(|s| parse_message_id(s).ok())
1758 .collect()
1759 });
1760
1761 Ok(Some(Report {
1762 original_message_id,
1763 additional_message_ids,
1764 }))
1765 }
1766
1767 fn process_delivery_status(
1768 &self,
1769 context: &Context,
1770 report: &mailparse::ParsedMail<'_>,
1771 ) -> Result<Option<DeliveryReport>> {
1772 let mut failure = true;
1774
1775 if let Some(status_part) = report.subparts.get(1) {
1776 if status_part.ctype.mimetype != "message/delivery-status"
1779 && status_part.ctype.mimetype != "message/global-delivery-status"
1780 {
1781 warn!(
1782 context,
1783 "Second part of Delivery Status Notification is not message/delivery-status or message/global-delivery-status, ignoring"
1784 );
1785 return Ok(None);
1786 }
1787
1788 let status_body = status_part.get_body_raw()?;
1789
1790 let (_, sz) = mailparse::parse_headers(&status_body)?;
1792
1793 if let Some(status_body) = status_body.get(sz..) {
1795 let (status_fields, _) = mailparse::parse_headers(status_body)?;
1796 if let Some(action) = status_fields.get_first_value("action") {
1797 if action != "failed" {
1798 info!(context, "DSN with {:?} action", action);
1799 failure = false;
1800 }
1801 } else {
1802 warn!(context, "DSN without action");
1803 }
1804 } else {
1805 warn!(context, "DSN without per-recipient fields");
1806 }
1807 } else {
1808 return Ok(None);
1810 }
1811
1812 if let Some(original_msg) = report.subparts.get(2).filter(|p| {
1814 p.ctype.mimetype.contains("rfc822")
1815 || p.ctype.mimetype == "message/global"
1816 || p.ctype.mimetype == "message/global-headers"
1817 }) {
1818 let report_body = original_msg.get_body_raw()?;
1819 let (report_fields, _) = mailparse::parse_headers(&report_body)?;
1820
1821 if let Some(original_message_id) = report_fields
1822 .get_header_value(HeaderDef::MessageId)
1823 .and_then(|v| parse_message_id(&v).ok())
1824 {
1825 return Ok(Some(DeliveryReport {
1826 rfc724_mid: original_message_id,
1827 failure,
1828 }));
1829 }
1830
1831 warn!(
1832 context,
1833 "ignoring unknown ndn-notification, Message-Id: {:?}",
1834 report_fields.get_header_value(HeaderDef::MessageId)
1835 );
1836 }
1837
1838 Ok(None)
1839 }
1840
1841 fn maybe_remove_bad_parts(&mut self) {
1842 let good_parts = self.parts.iter().filter(|p| !p.dehtml_failed).count();
1843 if good_parts == 0 {
1844 self.parts.truncate(1);
1846 } else if good_parts < self.parts.len() {
1847 self.parts.retain(|p| !p.dehtml_failed);
1848 }
1849
1850 if !self.has_chat_version() && self.is_mime_modified {
1858 fn is_related_image(p: &&Part) -> bool {
1859 (p.typ == Viewtype::Image || p.typ == Viewtype::Gif) && p.is_related
1860 }
1861 let related_image_cnt = self.parts.iter().filter(is_related_image).count();
1862 if related_image_cnt > 1 {
1863 let mut is_first_image = true;
1864 self.parts.retain(|p| {
1865 let retain = is_first_image || !is_related_image(&p);
1866 if p.typ == Viewtype::Image || p.typ == Viewtype::Gif {
1867 is_first_image = false;
1868 }
1869 retain
1870 });
1871 }
1872 }
1873 }
1874
1875 fn maybe_remove_inline_mailinglist_footer(&mut self) {
1885 if self.is_mailinglist_message() && !self.is_schleuder_message() {
1886 let text_part_cnt = self
1887 .parts
1888 .iter()
1889 .filter(|p| p.typ == Viewtype::Text)
1890 .count();
1891 if text_part_cnt == 2
1892 && let Some(last_part) = self.parts.last()
1893 && last_part.typ == Viewtype::Text
1894 {
1895 self.parts.pop();
1896 }
1897 }
1898 }
1899
1900 async fn heuristically_parse_ndn(&mut self, context: &Context) {
1904 let maybe_ndn = if let Some(from) = self.get_header(HeaderDef::From_) {
1905 let from = from.to_ascii_lowercase();
1906 from.contains("mailer-daemon") || from.contains("mail-daemon")
1907 } else {
1908 false
1909 };
1910 if maybe_ndn && self.delivery_report.is_none() {
1911 for original_message_id in self
1912 .parts
1913 .iter()
1914 .filter_map(|part| part.msg_raw.as_ref())
1915 .flat_map(|part| part.lines())
1916 .filter_map(|line| line.split_once("Message-ID:"))
1917 .filter_map(|(_, message_id)| parse_message_id(message_id).ok())
1918 {
1919 if let Ok(Some(_)) = message::rfc724_mid_exists(context, &original_message_id).await
1920 {
1921 self.delivery_report = Some(DeliveryReport {
1922 rfc724_mid: original_message_id,
1923 failure: true,
1924 })
1925 }
1926 }
1927 }
1928 }
1929
1930 pub async fn handle_reports(&self, context: &Context, from_id: ContactId, parts: &[Part]) {
1934 for report in &self.mdn_reports {
1935 for original_message_id in report
1936 .original_message_id
1937 .iter()
1938 .chain(&report.additional_message_ids)
1939 {
1940 if let Err(err) =
1941 handle_mdn(context, from_id, original_message_id, self.timestamp_sent).await
1942 {
1943 warn!(context, "Could not handle MDN: {err:#}.");
1944 }
1945 }
1946 }
1947
1948 if let Some(delivery_report) = &self.delivery_report
1949 && delivery_report.failure
1950 {
1951 let error = parts
1952 .iter()
1953 .find(|p| p.typ == Viewtype::Text)
1954 .map(|p| p.msg.clone());
1955 if let Err(err) = handle_ndn(context, delivery_report, error).await {
1956 warn!(context, "Could not handle NDN: {err:#}.");
1957 }
1958 }
1959 }
1960
1961 pub async fn get_parent_timestamp(&self, context: &Context) -> Result<Option<i64>> {
1966 let parent_timestamp = if let Some(field) = self
1967 .get_header(HeaderDef::InReplyTo)
1968 .and_then(|msgid| parse_message_id(msgid).ok())
1969 {
1970 context
1971 .sql
1972 .query_get_value("SELECT timestamp FROM msgs WHERE rfc724_mid=?", (field,))
1973 .await?
1974 } else {
1975 None
1976 };
1977 Ok(parent_timestamp)
1978 }
1979
1980 pub fn chat_group_member_timestamps(&self) -> Option<Vec<i64>> {
1984 let now = time() + constants::TIMESTAMP_SENT_TOLERANCE;
1985 self.get_header(HeaderDef::ChatGroupMemberTimestamps)
1986 .map(|h| {
1987 h.split_ascii_whitespace()
1988 .filter_map(|ts| ts.parse::<i64>().ok())
1989 .map(|ts| std::cmp::min(now, ts))
1990 .collect()
1991 })
1992 }
1993
1994 pub fn chat_group_member_fingerprints(&self) -> Vec<Fingerprint> {
1997 if let Some(header) = self.get_header(HeaderDef::ChatGroupMemberFpr) {
1998 header
1999 .split_ascii_whitespace()
2000 .filter_map(|fpr| Fingerprint::from_str(fpr).ok())
2001 .collect()
2002 } else {
2003 Vec::new()
2004 }
2005 }
2006}
2007
2008fn rm_legacy_display_elements(text: &str) -> String {
2009 let mut res = None;
2010 for l in text.lines() {
2011 res = res.map(|r: String| match r.is_empty() {
2012 true => l.to_string(),
2013 false => r + "\r\n" + l,
2014 });
2015 if l.is_empty() {
2016 res = Some(String::new());
2017 }
2018 }
2019 res.unwrap_or_default()
2020}
2021
2022fn remove_header(
2023 headers: &mut HashMap<String, String>,
2024 key: &str,
2025 removed: &mut HashSet<String>,
2026) -> Option<String> {
2027 if let Some((k, v)) = headers.remove_entry(key) {
2028 removed.insert(k);
2029 Some(v)
2030 } else {
2031 None
2032 }
2033}
2034
2035async fn parse_gossip_headers(
2041 context: &Context,
2042 from: &str,
2043 recipients: &[SingleInfo],
2044 gossip_headers: Vec<String>,
2045) -> Result<BTreeMap<String, GossipedKey>> {
2046 let mut gossiped_keys: BTreeMap<String, GossipedKey> = Default::default();
2048
2049 for value in &gossip_headers {
2050 let header = match value.parse::<Aheader>() {
2051 Ok(header) => header,
2052 Err(err) => {
2053 warn!(context, "Failed parsing Autocrypt-Gossip header: {}", err);
2054 continue;
2055 }
2056 };
2057
2058 if !recipients
2059 .iter()
2060 .any(|info| addr_cmp(&info.addr, &header.addr))
2061 {
2062 warn!(
2063 context,
2064 "Ignoring gossiped \"{}\" as the address is not in To/Cc list.", &header.addr,
2065 );
2066 continue;
2067 }
2068 if addr_cmp(from, &header.addr) {
2069 warn!(
2071 context,
2072 "Ignoring gossiped \"{}\" as it equals the From address", &header.addr,
2073 );
2074 continue;
2075 }
2076
2077 let fingerprint = header.public_key.dc_fingerprint().hex();
2078 context
2079 .sql
2080 .execute(
2081 "INSERT INTO public_keys (fingerprint, public_key)
2082 VALUES (?, ?)
2083 ON CONFLICT (fingerprint)
2084 DO NOTHING",
2085 (&fingerprint, header.public_key.to_bytes()),
2086 )
2087 .await?;
2088
2089 let gossiped_key = GossipedKey {
2090 public_key: header.public_key,
2091
2092 verified: header.verified,
2093 };
2094 gossiped_keys.insert(header.addr.to_lowercase(), gossiped_key);
2095 }
2096
2097 Ok(gossiped_keys)
2098}
2099
2100#[derive(Debug)]
2102pub(crate) struct Report {
2103 original_message_id: Option<String>,
2108 additional_message_ids: Vec<String>,
2110}
2111
2112#[derive(Debug)]
2114pub(crate) struct DeliveryReport {
2115 pub rfc724_mid: String,
2116 pub failure: bool,
2117}
2118
2119pub(crate) fn parse_message_ids(ids: &str) -> Vec<String> {
2120 let mut msgids = Vec::new();
2122 for id in ids.split_whitespace() {
2123 let mut id = id.to_string();
2124 if let Some(id_without_prefix) = id.strip_prefix('<') {
2125 id = id_without_prefix.to_string();
2126 };
2127 if let Some(id_without_suffix) = id.strip_suffix('>') {
2128 id = id_without_suffix.to_string();
2129 };
2130 if !id.is_empty() {
2131 msgids.push(id);
2132 }
2133 }
2134 msgids
2135}
2136
2137pub(crate) fn parse_message_id(ids: &str) -> Result<String> {
2138 if let Some(id) = parse_message_ids(ids).first() {
2139 Ok(id.to_string())
2140 } else {
2141 bail!("could not parse message_id: {ids}");
2142 }
2143}
2144
2145fn is_protected(key: &str) -> bool {
2152 key.starts_with("chat-")
2153 || matches!(
2154 key,
2155 "return-path"
2156 | "auto-submitted"
2157 | "autocrypt-setup-message"
2158 | "date"
2159 | "from"
2160 | "sender"
2161 | "reply-to"
2162 | "to"
2163 | "cc"
2164 | "bcc"
2165 | "message-id"
2166 | "in-reply-to"
2167 | "references"
2168 | "secure-join"
2169 )
2170}
2171
2172pub(crate) fn is_hidden(key: &str) -> bool {
2174 matches!(
2175 key,
2176 "chat-user-avatar" | "chat-group-avatar" | "chat-delete" | "chat-edit"
2177 )
2178}
2179
2180#[derive(Debug, Default, Clone)]
2182pub struct Part {
2183 pub typ: Viewtype,
2185
2186 pub mimetype: Option<Mime>,
2188
2189 pub msg: String,
2191
2192 pub msg_raw: Option<String>,
2194
2195 pub bytes: usize,
2197
2198 pub param: Params,
2200
2201 pub(crate) org_filename: Option<String>,
2203
2204 pub error: Option<String>,
2206
2207 pub(crate) dehtml_failed: bool,
2209
2210 pub(crate) is_related: bool,
2217
2218 pub(crate) is_reaction: bool,
2220}
2221
2222fn get_mime_type(
2227 mail: &mailparse::ParsedMail<'_>,
2228 filename: &Option<String>,
2229 is_chat_msg: bool,
2230) -> Result<(Mime, Viewtype)> {
2231 let mimetype = mail.ctype.mimetype.parse::<Mime>()?;
2232
2233 let viewtype = match mimetype.type_() {
2234 mime::TEXT => match mimetype.subtype() {
2235 mime::VCARD => Viewtype::Vcard,
2236 mime::PLAIN | mime::HTML if !is_attachment_disposition(mail) => Viewtype::Text,
2237 _ => Viewtype::File,
2238 },
2239 mime::IMAGE => match mimetype.subtype() {
2240 mime::GIF => Viewtype::Gif,
2241 mime::SVG => Viewtype::File,
2242 _ => Viewtype::Image,
2243 },
2244 mime::AUDIO => Viewtype::Audio,
2245 mime::VIDEO => Viewtype::Video,
2246 mime::MULTIPART => Viewtype::Unknown,
2247 mime::MESSAGE => {
2248 if is_attachment_disposition(mail) {
2249 Viewtype::File
2250 } else {
2251 Viewtype::Unknown
2259 }
2260 }
2261 mime::APPLICATION => match mimetype.subtype() {
2262 mime::OCTET_STREAM => match filename {
2263 Some(filename) if !is_chat_msg => {
2264 match message::guess_msgtype_from_path_suffix(Path::new(&filename)) {
2265 Some((viewtype, _)) => viewtype,
2266 None => Viewtype::File,
2267 }
2268 }
2269 _ => Viewtype::File,
2270 },
2271 _ => Viewtype::File,
2272 },
2273 _ => Viewtype::Unknown,
2274 };
2275
2276 Ok((mimetype, viewtype))
2277}
2278
2279fn is_attachment_disposition(mail: &mailparse::ParsedMail<'_>) -> bool {
2280 let ct = mail.get_content_disposition();
2281 ct.disposition == DispositionType::Attachment
2282 && ct
2283 .params
2284 .iter()
2285 .any(|(key, _value)| key.starts_with("filename"))
2286}
2287
2288fn get_attachment_filename(
2295 context: &Context,
2296 mail: &mailparse::ParsedMail,
2297) -> Result<Option<String>> {
2298 let ct = mail.get_content_disposition();
2299
2300 let mut desired_filename = ct.params.get("filename").map(|s| s.to_string());
2303
2304 if desired_filename.is_none()
2305 && let Some(name) = ct.params.get("filename*").map(|s| s.to_string())
2306 {
2307 warn!(context, "apostrophed encoding invalid: {}", name);
2311 desired_filename = Some(name);
2312 }
2313
2314 if desired_filename.is_none() {
2316 desired_filename = ct.params.get("name").map(|s| s.to_string());
2317 }
2318
2319 if desired_filename.is_none() {
2322 desired_filename = mail.ctype.params.get("name").map(|s| s.to_string());
2323 }
2324
2325 if desired_filename.is_none() && ct.disposition == DispositionType::Attachment {
2327 if let Some(subtype) = mail.ctype.mimetype.split('/').nth(1) {
2328 desired_filename = Some(format!("file.{subtype}",));
2329 } else {
2330 bail!(
2331 "could not determine attachment filename: {:?}",
2332 ct.disposition
2333 );
2334 };
2335 }
2336
2337 let desired_filename = desired_filename.map(|filename| sanitize_bidi_characters(&filename));
2338
2339 Ok(desired_filename)
2340}
2341
2342pub(crate) fn get_recipients(headers: &[MailHeader]) -> Vec<SingleInfo> {
2344 let to_addresses = get_all_addresses_from_header(headers, "to");
2345 let cc_addresses = get_all_addresses_from_header(headers, "cc");
2346
2347 let mut res = to_addresses;
2348 res.extend(cc_addresses);
2349 res
2350}
2351
2352pub(crate) fn get_from(headers: &[MailHeader]) -> Option<SingleInfo> {
2354 let all = get_all_addresses_from_header(headers, "from");
2355 tools::single_value(all)
2356}
2357
2358pub(crate) fn get_list_post(headers: &[MailHeader]) -> Option<String> {
2360 get_all_addresses_from_header(headers, "list-post")
2361 .into_iter()
2362 .next()
2363 .map(|s| s.addr)
2364}
2365
2366fn get_all_addresses_from_header(headers: &[MailHeader], header: &str) -> Vec<SingleInfo> {
2378 let mut result: Vec<SingleInfo> = Default::default();
2379
2380 if let Some(header) = headers
2381 .iter()
2382 .rev()
2383 .find(|h| h.get_key().to_lowercase() == header)
2384 && let Ok(addrs) = mailparse::addrparse_header(header)
2385 {
2386 for addr in addrs.iter() {
2387 match addr {
2388 mailparse::MailAddr::Single(info) => {
2389 result.push(SingleInfo {
2390 addr: addr_normalize(&info.addr).to_lowercase(),
2391 display_name: info.display_name.clone(),
2392 });
2393 }
2394 mailparse::MailAddr::Group(infos) => {
2395 for info in &infos.addrs {
2396 result.push(SingleInfo {
2397 addr: addr_normalize(&info.addr).to_lowercase(),
2398 display_name: info.display_name.clone(),
2399 });
2400 }
2401 }
2402 }
2403 }
2404 }
2405
2406 result
2407}
2408
2409async fn handle_mdn(
2410 context: &Context,
2411 from_id: ContactId,
2412 rfc724_mid: &str,
2413 timestamp_sent: i64,
2414) -> Result<()> {
2415 if from_id == ContactId::SELF {
2416 warn!(
2417 context,
2418 "Ignoring MDN sent to self, this is a bug on the sender device."
2419 );
2420
2421 return Ok(());
2424 }
2425
2426 let Some((msg_id, chat_id, has_mdns, is_dup)) = context
2427 .sql
2428 .query_row_optional(
2429 concat!(
2430 "SELECT",
2431 " m.id AS msg_id,",
2432 " c.id AS chat_id,",
2433 " mdns.contact_id AS mdn_contact",
2434 " FROM msgs m ",
2435 " LEFT JOIN chats c ON m.chat_id=c.id",
2436 " LEFT JOIN msgs_mdns mdns ON mdns.msg_id=m.id",
2437 " WHERE rfc724_mid=? AND from_id=1",
2438 " ORDER BY msg_id DESC, mdn_contact=? DESC",
2439 " LIMIT 1",
2440 ),
2441 (&rfc724_mid, from_id),
2442 |row| {
2443 let msg_id: MsgId = row.get("msg_id")?;
2444 let chat_id: ChatId = row.get("chat_id")?;
2445 let mdn_contact: Option<ContactId> = row.get("mdn_contact")?;
2446 Ok((
2447 msg_id,
2448 chat_id,
2449 mdn_contact.is_some(),
2450 mdn_contact == Some(from_id),
2451 ))
2452 },
2453 )
2454 .await?
2455 else {
2456 info!(
2457 context,
2458 "Ignoring MDN, found no message with Message-ID {rfc724_mid:?} sent by us in the database.",
2459 );
2460 return Ok(());
2461 };
2462
2463 if is_dup {
2464 return Ok(());
2465 }
2466 context
2467 .sql
2468 .execute(
2469 "INSERT INTO msgs_mdns (msg_id, contact_id, timestamp_sent) VALUES (?, ?, ?)",
2470 (msg_id, from_id, timestamp_sent),
2471 )
2472 .await?;
2473 if !has_mdns {
2474 context.emit_event(EventType::MsgRead { chat_id, msg_id });
2475 chatlist_events::emit_chatlist_item_changed(context, chat_id);
2477 }
2478 Ok(())
2479}
2480
2481async fn handle_ndn(
2484 context: &Context,
2485 failed: &DeliveryReport,
2486 error: Option<String>,
2487) -> Result<()> {
2488 if failed.rfc724_mid.is_empty() {
2489 return Ok(());
2490 }
2491
2492 let msg_ids = context
2495 .sql
2496 .query_map_vec(
2497 "SELECT id FROM msgs
2498 WHERE rfc724_mid=? AND from_id=1",
2499 (&failed.rfc724_mid,),
2500 |row| {
2501 let msg_id: MsgId = row.get(0)?;
2502 Ok(msg_id)
2503 },
2504 )
2505 .await?;
2506
2507 let error = if let Some(error) = error {
2508 error
2509 } else {
2510 "Delivery to at least one recipient failed.".to_string()
2511 };
2512 let err_msg = &error;
2513
2514 for msg_id in msg_ids {
2515 let mut message = Message::load_from_db(context, msg_id).await?;
2516 let aggregated_error = message
2517 .error
2518 .as_ref()
2519 .map(|err| format!("{err}\n\n{err_msg}"));
2520 set_msg_failed(
2521 context,
2522 &mut message,
2523 aggregated_error.as_ref().unwrap_or(err_msg),
2524 )
2525 .await?;
2526 }
2527
2528 Ok(())
2529}
2530
2531#[cfg(test)]
2532mod mimeparser_tests;