From 266e54b7b8c34c9a58dd60a2e53c5ca7d1deae19 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Date: Fri, 11 Sep 2020 10:57:51 +0300
Subject: [PATCH] lib-imap: Don't generate invalid BODYSTRUCTURE when reaching
 MIME part limit

If the last MIME part was message/rfc822 and its child was truncated away,
BODYSTRUCTURE was missing the ENVELOPE and BODY[STRUCTURE] parts. Fixed by
writing empty dummy ones.
---
 src/lib-imap/imap-bodystructure.c | 29 +++++++++++++++++++++++++++--
 1 file changed, 27 insertions(+), 2 deletions(-)

diff --git a/src/lib-imap/imap-bodystructure.c b/src/lib-imap/imap-bodystructure.c
index 4e379e56a9..e3da1090b4 100644
--- a/src/lib-imap/imap-bodystructure.c
+++ b/src/lib-imap/imap-bodystructure.c
@@ -146,11 +146,25 @@ static void part_write_body(const struct message_part *part,
 			    string_t *str, bool extended)
 {
 	const struct message_part_data *data = part->data;
-	bool text;
+	bool text, message_rfc822;
 
 	i_assert(part->data != NULL);
 
-	if ((part->flags & MESSAGE_PART_FLAG_MESSAGE_RFC822) != 0) {
+	if ((part->flags & MESSAGE_PART_FLAG_MESSAGE_RFC822) != 0)
+		message_rfc822 = TRUE;
+	else if (data->content_type != NULL &&
+		 strcasecmp(data->content_type, "message") == 0 &&
+		 strcasecmp(data->content_subtype, "rfc822") == 0) {
+		/* It's message/rfc822, but without
+		   MESSAGE_PART_FLAG_MESSAGE_RFC822. That likely means maximum
+		   MIME part count was reached while parsing the mail. Write
+		   the missing child mail's ENVELOPE and BODY as empty dummy
+		   values. */
+		message_rfc822 = TRUE;
+	} else
+		message_rfc822 = FALSE;
+
+	if (message_rfc822) {
 		str_append(str, "\"message\" \"rfc822\"");
 		text = FALSE;
 	} else {
@@ -200,6 +214,17 @@ static void part_write_body(const struct message_part *part,
 
 		part_write_bodystructure_siblings(part->children, str, extended);
 		str_printfa(str, " %u", part->body_size.lines);
+	} else if (message_rfc822) {
+		/* truncated MIME part - write out dummy values */
+		i_assert(part->children == NULL);
+
+		str_append(str, " (NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL) ");
+
+		if (!extended)
+			str_append(str, EMPTY_BODY);
+		else
+			str_append(str, EMPTY_BODYSTRUCTURE);
+		str_printfa(str, " %u", part->body_size.lines);
 	}
 
 	if (!extended)
