[packages/dovecot] Rel 11. Backport security fixes from 2.4.5

arekm arekm at pld-linux.org
Thu Oct 29 11:40:39 CET 2026


commit 45c5baf96cab7033346d2640d9f1b3d9817074e8
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Thu Oct 29 10:42:18 2026 +0100

    Rel 11. Backport security fixes from 2.4.5
    
    Fixes CVE-2026-42391, CVE-2026-40203, CVE-2026-40018, CVE-2026-40017,
    CVE-2026-40014, CVE-2026-33604, CVE-2026-27852.
    
    Fix the CVE-2026-27857 backport, which logged every pre-login ID pair.

 CVE-2026-27852.patch | 1134 ++++++++++++++++++++++++++++++++++++++++++++++++++
 CVE-2026-27857.patch |    9 +-
 CVE-2026-33604.patch |  387 +++++++++++++++++
 CVE-2026-40014.patch |  144 +++++++
 CVE-2026-40017.patch |  953 ++++++++++++++++++++++++++++++++++++++++++
 CVE-2026-40018.patch |  135 ++++++
 CVE-2026-40203.patch |  174 ++++++++
 CVE-2026-42391.patch |   63 +++
 dovecot.spec         |   16 +-
 9 files changed, 3009 insertions(+), 6 deletions(-)
---
diff --git a/dovecot.spec b/dovecot.spec
index 1012ea8..7fb932f 100644
--- a/dovecot.spec
+++ b/dovecot.spec
@@ -13,7 +13,7 @@ Summary:	IMAP and POP3 server written with security primarily in mind
 Summary(pl.UTF-8):	Serwer IMAP i POP3 pisany głównie z myślą o bezpieczeństwie
 Name:		dovecot
 Version:	2.3.21.1
-Release:	10
+Release:	11
 Epoch:		1
 License:	MIT (libraries), LGPL v2.1 (the rest)
 Group:		Networking/Daemons
@@ -43,6 +43,13 @@ Patch13:	CVE-2026-27859.patch
 Patch14:	CVE-2026-33603.patch
 Patch15:	CVE-2026-40020.patch
 Patch16:	CVE-2026-42006.patch
+Patch17:	CVE-2026-42391.patch
+Patch18:	CVE-2026-27852.patch
+Patch19:	CVE-2026-40014.patch
+Patch20:	CVE-2026-40017.patch
+Patch21:	CVE-2026-33604.patch
+Patch22:	CVE-2026-40018.patch
+Patch23:	CVE-2026-40203.patch
 URL:		http://dovecot.org/
 BuildRequires:	autoconf
 BuildRequires:	automake
@@ -200,6 +207,13 @@ Pakiet programistyczny do tworzenia wtyczek dla Dovecota.
 %patch -P14 -p1
 %patch -P15 -p1
 %patch -P16 -p1
+%patch -P17 -p1
+%patch -P18 -p1
+%patch -P19 -p1
+%patch -P20 -p1
+%patch -P21 -p1
+%patch -P22 -p1
+%patch -P23 -p1
 
 %{__sed} -i 's,/usr/lib/dovecot,%{_libdir}/dovecot,g' doc/example-config/*.conf doc/example-config/conf.d/*.conf
 
diff --git a/CVE-2026-27852.patch b/CVE-2026-27852.patch
new file mode 100644
index 0000000..86a5d05
--- /dev/null
+++ b/CVE-2026-27852.patch
@@ -0,0 +1,1134 @@
+Subject: [PATCH] lib-mail, imap: Limit memory used by huge headers and
+ address/MIME parameter lists (CVE-2026-27852)
+
+A message with a huge number of addresses or MIME parameters, or huge
+header blocks, used excessive memory when parsed for ENVELOPE,
+BODYSTRUCTURE and header fetches.
+
+Backport of the upstream 2.4.5 series via Debian trixie
+1:2.4.1+dfsg1-6+deb13u7:
+  https://github.com/dovecot/core/commit/00daee1af18d929b3fcd14aa52840e38fe929711
+  https://github.com/dovecot/core/commit/035fbfa155288ac037965e0e4700eb198ccbf39a
+  https://github.com/dovecot/core/commit/1fa4c5a3fe21ca1994e54022050d23e260416c3c
+  https://github.com/dovecot/core/commit/32010a7067a7970d302981c888f1e10904184499
+  https://github.com/dovecot/core/commit/41c4a77d2830a70616273962c720b7e2a9041efa
+  https://github.com/dovecot/core/commit/4380d7c5293760c0473566a227c63f3f91304f90
+  https://github.com/dovecot/core/commit/4b7e869b4b8fb70e0c32e4106aebc31a07b9f75b
+  https://github.com/dovecot/core/commit/84e6d207c83e9c1ed1d533d591475d9da2d6b55b
+  https://github.com/dovecot/core/commit/8f0089e5a811d7ee46eff17e2a46de7e004a74f4
+  https://github.com/dovecot/core/commit/977de721d6fcac09ab254958253856abcc0393c1
+  https://github.com/dovecot/core/commit/a81dd72a884a4f3e6b2859e9dd4fbada8c3900fe
+  https://github.com/dovecot/core/commit/c853685f820157046136bd027861cb2a21c13fbc
+  https://github.com/dovecot/core/commit/ec0294808ea6443690044132c5f309ed0272cc06
+  https://github.com/dovecot/core/commit/f27b7ae04f88f662c5f2bdd256ee9bef86d4c937
+
+PLD changes on top of upstream:
+- message_address_parse_full() gets a new flag,
+  MESSAGE_ADDRESS_PARSE_FLAG_LIMIT_ALL_ENTRIES, used by message-part-data.
+  Upstream only counts top-level addresses against the limit, so group
+  members, group markers and fixed-up invalid addresses could exceed it
+  and trigger
+  i_assert(new_addr.count <= limits->remaining_addresses) in
+  message_part_envelope_parse_from_header() (any mail sender could crash
+  FETCH ENVELOPE).  The assert is replaced with a clamp.
+- test-imap-envelope covers groups, empty groups and trailing garbage at
+  the limit.
+---
+ src/imap/imap-fetch.c                        | 75 ++++++++++++++--
+ src/lib-imap/test-imap-bodystructure.c       |  3 +-
+ src/lib-imap/test-imap-envelope.c            | 90 +++++++++++++++++++-
+ src/lib-mail/istream-header-filter.c         | 30 +++++--
+ src/lib-mail/istream-header-filter.h         |  8 ++
+ src/lib-mail/message-address.c               | 28 +++++-
+ src/lib-mail/message-address.h               |  7 ++
+ src/lib-mail/message-decoder.c               |  4 +
+ src/lib-mail/message-header-parser.c         | 16 ++--
+ src/lib-mail/message-parser-from-parts.c     | 10 +++
+ src/lib-mail/message-part-data.c             | 50 +++++++----
+ src/lib-mail/message-part-data.h             | 18 ++++
+ src/lib-mail/test-message-decoder.c          | 66 +++++++++++++-
+ src/lib-mail/test-message-header-parser.c    | 16 +++-
+ src/lib-mail/test-message-parser.c           |  3 +-
+ src/lib-storage/index/index-mail-headers.c   | 15 +++-
+ src/lib-storage/index/index-mail.c           | 21 ++++-
+ src/lib-storage/index/index-mail.h           |  2 +
+ src/lib-storage/index/mbox/mbox-sync-parse.c |  5 ++
+ 19 files changed, 415 insertions(+), 52 deletions(-)
+
+diff --git a/src/imap/imap-fetch.c b/src/imap/imap-fetch.c
+index db811f7..a424a58 100644
+--- a/src/imap/imap-fetch.c
++++ b/src/imap/imap-fetch.c
+@@ -732,6 +732,34 @@ static bool fetch_body_init(struct imap_fetch_init_context *ctx)
+ 	return imap_fetch_body_section_init(ctx);
+ }
+ 
++static int fetch_bodystructure_stream_continue(struct imap_fetch_context *ctx)
++{
++	struct imap_fetch_state *state = &ctx->state;
++	enum ostream_send_istream_result res;
++
++	o_stream_set_max_buffer_size(ctx->client->output, 0);
++	res = o_stream_send_istream(ctx->client->output, state->cur_input);
++	o_stream_set_max_buffer_size(ctx->client->output, SIZE_MAX);
++
++	switch (res) {
++	case OSTREAM_SEND_ISTREAM_RESULT_FINISHED:
++		i_stream_unref(&state->cur_input);
++		state->cont_handler = NULL;
++		if (o_stream_send(ctx->client->output, ")", 1) < 0)
++			return -1;
++		return 1;
++	case OSTREAM_SEND_ISTREAM_RESULT_WAIT_INPUT:
++		i_unreached();
++	case OSTREAM_SEND_ISTREAM_RESULT_WAIT_OUTPUT:
++		return 0;
++	case OSTREAM_SEND_ISTREAM_RESULT_ERROR_INPUT:
++		i_unreached();
++	case OSTREAM_SEND_ISTREAM_RESULT_ERROR_OUTPUT:
++		return -1;
++	}
++	i_unreached();
++}
++
+ static int fetch_bodystructure(struct imap_fetch_context *ctx,
+ 			       struct mail *mail, void *context ATTR_UNUSED)
+ {
+@@ -748,12 +776,13 @@ static int fetch_bodystructure(struct imap_fetch_context *ctx,
+ 			return -1;
+ 	}
+ 
+-	if (o_stream_send(ctx->client->output, "BODYSTRUCTURE (", 15) < 0 ||
+-	    o_stream_send_str(ctx->client->output, bodystructure) < 0 ||
+-	    o_stream_send(ctx->client->output, ")", 1) < 0)
++	if (o_stream_send(ctx->client->output, "BODYSTRUCTURE (", 15) < 0)
+ 		return -1;
+ 
+-	return 1;
++	ctx->state.cur_input =
++		i_stream_create_from_data(bodystructure, strlen(bodystructure));
++	ctx->state.cont_handler = fetch_bodystructure_stream_continue;
++	return fetch_bodystructure_stream_continue(ctx);
+ }
+ 
+ static bool fetch_bodystructure_init(struct imap_fetch_init_context *ctx)
+@@ -764,6 +793,34 @@ static bool fetch_bodystructure_init(struct imap_fetch_init_context *ctx)
+ 	return TRUE;
+ }
+ 
++static int fetch_envelope_stream_continue(struct imap_fetch_context *ctx)
++{
++	struct imap_fetch_state *state = &ctx->state;
++	enum ostream_send_istream_result res;
++
++	o_stream_set_max_buffer_size(ctx->client->output, 0);
++	res = o_stream_send_istream(ctx->client->output, state->cur_input);
++	o_stream_set_max_buffer_size(ctx->client->output, SIZE_MAX);
++
++	switch (res) {
++	case OSTREAM_SEND_ISTREAM_RESULT_FINISHED:
++		i_stream_unref(&state->cur_input);
++		state->cont_handler = NULL;
++		if (o_stream_send(ctx->client->output, ")", 1) < 0)
++			return -1;
++		return 1;
++	case OSTREAM_SEND_ISTREAM_RESULT_WAIT_INPUT:
++		i_unreached();
++	case OSTREAM_SEND_ISTREAM_RESULT_WAIT_OUTPUT:
++		return 0;
++	case OSTREAM_SEND_ISTREAM_RESULT_ERROR_INPUT:
++		i_unreached();
++	case OSTREAM_SEND_ISTREAM_RESULT_ERROR_OUTPUT:
++		return -1;
++	}
++	i_unreached();
++}
++
+ static int fetch_envelope(struct imap_fetch_context *ctx, struct mail *mail,
+ 			  void *context ATTR_UNUSED)
+ {
+@@ -779,11 +836,13 @@ static int fetch_envelope(struct imap_fetch_context *ctx, struct mail *mail,
+ 			return -1;
+ 	}
+ 
+-	if (o_stream_send(ctx->client->output, "ENVELOPE (", 10) < 0 ||
+-	    o_stream_send_str(ctx->client->output, envelope) < 0 ||
+-	    o_stream_send(ctx->client->output, ")", 1) < 0)
++	if (o_stream_send(ctx->client->output, "ENVELOPE (", 10) < 0)
+ 		return -1;
+-	return 1;
++
++	ctx->state.cur_input =
++		i_stream_create_from_data(envelope, strlen(envelope));
++	ctx->state.cont_handler = fetch_envelope_stream_continue;
++	return fetch_envelope_stream_continue(ctx);
+ }
+ 
+ static bool fetch_envelope_init(struct imap_fetch_init_context *ctx)
+diff --git a/src/lib-imap/test-imap-bodystructure.c b/src/lib-imap/test-imap-bodystructure.c
+index 736eb99..c96baf4 100644
+--- a/src/lib-imap/test-imap-bodystructure.c
++++ b/src/lib-imap/test-imap-bodystructure.c
+@@ -398,10 +398,11 @@ msg_parse(pool_t pool, const char *message, unsigned int max_nested_mime_parts,
+ 
+ 	input = i_stream_create_from_data(message, strlen(message));
+ 	parser = message_parser_init(pool, input, &parser_set);
++	struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT;
+ 	while ((ret = message_parser_parse_next_block(parser, &block)) > 0) {
+ 		if (parse_bodystructure) {
+ 			message_part_data_parse_from_header(pool, block.part,
+-							block.hdr);
++							&limits, block.hdr);
+ 		}
+ 	}
+ 	test_assert(ret < 0);
+diff --git a/src/lib-imap/test-imap-envelope.c b/src/lib-imap/test-imap-envelope.c
+index c9b92b4..5a16784 100644
+--- a/src/lib-imap/test-imap-envelope.c
++++ b/src/lib-imap/test-imap-envelope.c
+@@ -132,9 +132,11 @@ msg_parse(pool_t pool, const char *message)
+ 
+ 	input = i_stream_create_from_data(message, strlen(message));
+ 	parser = message_parser_init(pool, input, &parser_set);
++	struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT;
+ 	while ((ret = message_parser_parse_next_block(parser, &block)) > 0) {
+ 		i_assert(block.part->parent == NULL);
+-		message_part_envelope_parse_from_header(pool, &envlp, block.hdr);
++		message_part_envelope_parse_from_header(pool, &envlp, &limits,
++							block.hdr);
+ 	}
+ 	test_assert(ret < 0);
+ 
+@@ -194,11 +196,97 @@ static void test_imap_envelope_parse(void)
+ 	} T_END;
+ }
+ 
++static unsigned int
++test_address_list_check(const struct message_address *addr, bool *balanced_r)
++{
++	unsigned int count = 0;
++	int depth = 0;
++
++	*balanced_r = TRUE;
++	for (; addr != NULL; addr = addr->next) {
++		count++;
++		if (addr->mailbox != NULL && addr->domain == NULL) {
++			/* group start */
++			if (depth++ != 0)
++				*balanced_r = FALSE;
++		} else if (addr->mailbox == NULL && addr->domain == NULL) {
++			/* group end */
++			if (--depth != 0)
++				*balanced_r = FALSE;
++		}
++	}
++	if (depth != 0)
++		*balanced_r = FALSE;
++	return count;
++}
++
++static void test_imap_envelope_address_limit(void)
++{
++	/* Group markers, group members and fixed-up garbage add list
++	   entries beyond the top-level address count. The per-message
++	   address limit must still hold, without crashing. */
++	const unsigned int max = MESSAGE_PART_DATA_MAX_TOTAL_ADDRESSES;
++	struct message_part_envelope *envlp;
++	unsigned int i, n, count;
++	bool balanced;
++
++	test_begin("imap envelope address limit");
++	for (n = 0; n < 4; n++) {
++		string_t *msg = str_new(default_pool, 1024*1024);
++		pool_t pool = pool_alloconly_create("imap envelope limit",
++						    1024*1024);
++
++		switch (n) {
++		case 0:
++			/* one group with more members than the limit */
++			str_append(msg, "To: g:");
++			for (i = 0; i < max + 10; i++)
++				str_append(msg, " a at x,");
++			str_append(msg, " a at x;\n\n");
++			break;
++		case 1:
++			/* repeated groups */
++			str_append(msg, "To:");
++			for (i = 0; i < max / 2 + 10; i++)
++				str_append(msg, " g: a at x, b at y;,");
++			str_append(msg, " a at x\n\n");
++			break;
++		case 2:
++			/* repeated empty groups */
++			str_append(msg, "To:");
++			for (i = 0; i < max + 10; i++)
++				str_append(msg, " g:;,");
++			str_append(msg, " a at x\n\n");
++			break;
++		case 3:
++			/* limit reached exactly, then garbage that makes
++			   the parser add a fixed-up entry */
++			str_append(msg, "To:");
++			for (i = 0; i < max; i++)
++				str_append(msg, " a at x,");
++			str_append(msg, " (\n\n");
++			break;
++		}
++		envlp = msg_parse(pool, str_c(msg));
++		test_assert_idx(envlp != NULL, n);
++		if (envlp != NULL) {
++			count = test_address_list_check(envlp->to.head, &balanced);
++			test_assert_idx(count == envlp->to.count, n);
++			test_assert_idx(count <= max, n);
++			test_assert_idx(balanced, n);
++		}
++		pool_unref(&pool);
++		str_free(&msg);
++	}
++	test_end();
++}
++
+ int main(void)
+ {
+ 	static void (*const test_functions[])(void) = {
+ 		test_imap_envelope_write,
+ 		test_imap_envelope_parse,
++		test_imap_envelope_address_limit,
+ 		NULL
+ 	};
+ 	return test_run(test_functions);
+diff --git a/src/lib-mail/istream-header-filter.c b/src/lib-mail/istream-header-filter.c
+index 1783dbd..167800b 100644
+--- a/src/lib-mail/istream-header-filter.c
++++ b/src/lib-mail/istream-header-filter.c
+@@ -28,6 +28,7 @@ struct header_filter_istream {
+ 
+ 	buffer_t *hdr_buf;
+ 	struct message_size header_size;
++	size_t max_header_block_size;
+ 	uoff_t skip_count;
+ 	uoff_t last_lf_offset;
+ 
+@@ -60,7 +61,7 @@ static ssize_t i_stream_header_filter_read(struct istream_private *stream);
+ static void i_stream_header_filter_destroy(struct iostream_private *stream)
+ {
+ 	struct header_filter_istream *mstream =
+-		(struct header_filter_istream *)stream;
++		container_of(stream, struct header_filter_istream, istream.iostream);
+ 
+ 	if (mstream->hdr_ctx != NULL)
+ 		message_parse_header_deinit(&mstream->hdr_ctx);
+@@ -194,6 +195,8 @@ static ssize_t read_header(struct header_filter_istream *mstream)
+ 		mstream->hdr_ctx =
+ 			message_parse_header_init(mstream->istream.parent,
+ 						  NULL, 0);
++		message_parse_header_set_limit(mstream->hdr_ctx,
++					       mstream->max_header_block_size);
+ 	}
+ 
+ 	/* remove skipped data from hdr_buf */
+@@ -468,7 +471,7 @@ handle_end_body_with_lf(struct header_filter_istream *mstream, ssize_t ret)
+ static ssize_t i_stream_header_filter_read(struct istream_private *stream)
+ {
+ 	struct header_filter_istream *mstream =
+-		(struct header_filter_istream *)stream;
++		container_of(stream, struct header_filter_istream, istream);
+ 	uoff_t v_offset;
+ 	ssize_t ret;
+ 
+@@ -552,7 +555,7 @@ static void i_stream_header_filter_seek(struct istream_private *stream,
+ 					uoff_t v_offset, bool mark ATTR_UNUSED)
+ {
+ 	struct header_filter_istream *mstream =
+-		(struct header_filter_istream *)stream;
++		container_of(stream, struct header_filter_istream, istream);
+ 
+ 	if (stream->istream.v_offset == v_offset) {
+ 		/* just reset the input buffer */
+@@ -602,7 +605,7 @@ static int
+ i_stream_header_filter_stat(struct istream_private *stream, bool exact)
+ {
+ 	struct header_filter_istream *mstream =
+-		(struct header_filter_istream *)stream;
++		container_of(stream, struct header_filter_istream, istream);
+ 	const struct stat *st;
+ 	uoff_t old_offset;
+ 
+@@ -671,7 +674,7 @@ i_stream_header_filter_snapshot(struct istream_private *stream,
+ 				struct istream_snapshot *prev_snapshot)
+ {
+ 	struct header_filter_istream *mstream =
+-		(struct header_filter_istream *)stream;
++		container_of(stream, struct header_filter_istream, istream);
+ 	struct header_filter_istream_snapshot *snapshot;
+ 
+ 	if (stream->buffer != mstream->hdr_buf->data) {
+@@ -707,6 +710,9 @@ i_stream_create_header_filter(struct istream *input,
+ 	mstream->pool = pool_alloconly_create(MEMPOOL_GROWING
+ 					      "header filter stream", 256);
+ 	mstream->istream.max_buffer_size = input->real_stream->max_buffer_size;
++	/* Default to no per-header block size limit. Callers that want one
++	   call i_stream_header_filter_set_max_header_block_size(). */
++	mstream->max_header_block_size = SIZE_MAX;
+ 
+ 	mstream->headers = headers_count == 0 ? NULL :
+ 		p_new(mstream->pool, const char *, headers_count);
+@@ -760,3 +766,17 @@ void i_stream_header_filter_add(struct header_filter_istream *input,
+ 	buffer_append(input->hdr_buf, data, size);
+ 	input->headers_edited = TRUE;
+ }
++
++void i_stream_header_filter_set_max_header_block_size(
++	struct istream *input, size_t max_header_block_size)
++{
++	struct header_filter_istream *mstream =
++		container_of(input->real_stream, struct header_filter_istream,
++			     istream);
++
++	mstream->max_header_block_size = max_header_block_size;
++	if (mstream->hdr_ctx != NULL) {
++		message_parse_header_set_limit(mstream->hdr_ctx,
++					       max_header_block_size);
++	}
++}
+diff --git a/src/lib-mail/istream-header-filter.h b/src/lib-mail/istream-header-filter.h
+index 7c5ca36..6a2ffd8 100644
+--- a/src/lib-mail/istream-header-filter.h
++++ b/src/lib-mail/istream-header-filter.h
+@@ -49,4 +49,12 @@ i_stream_create_header_filter(struct istream *input,
+ void i_stream_header_filter_add(struct header_filter_istream *input,
+ 				const void *data, size_t size);
+ 
++/* Set a per-header-block maximum size for this filter stream. Data beyond
++   this limit in any single header is dropped from the filter's output and
++   from values delivered to the filter callback. The default is SIZE_MAX
++   (unlimited). Use MESSAGE_HEADER_BLOCK_DEFAULT_MAX_SIZE from
++   message-header-parser.h for the standard cap. */
++void i_stream_header_filter_set_max_header_block_size(
++	struct istream *input, size_t max_header_block_size);
++
+ #endif
+diff --git a/src/lib-mail/message-address.c b/src/lib-mail/message-address.c
+index ae37014..920b0df 100644
+--- a/src/lib-mail/message-address.c
++++ b/src/lib-mail/message-address.c
+@@ -16,10 +16,24 @@ struct message_address_parser_context {
+ 	struct message_address addr;
+ 	struct message_address_list addr_list;
+ 	string_t *str;
++	/* UINT_MAX unless MESSAGE_ADDRESS_PARSE_FLAG_LIMIT_ALL_ENTRIES */
++	unsigned int max_entries;
+ 
+ 	bool fill_missing, non_strict_dots;
++	bool entry_limit_reached;
+ };
+ 
++static bool
++entries_have_room(struct message_address_parser_context *ctx,
++		  unsigned int needed)
++{
++	if (ctx->addr_list.count <= ctx->max_entries &&
++	    ctx->max_entries - ctx->addr_list.count >= needed)
++		return TRUE;
++	ctx->entry_limit_reached = TRUE;
++	return FALSE;
++}
++
+ static void add_address(struct message_address_parser_context *ctx)
+ {
+ 	struct message_address *addr;
+@@ -30,6 +44,7 @@ static void add_address(struct message_address_parser_context *ctx)
+ 	i_zero(&ctx->addr);
+ 
+ 	DLLIST2_APPEND(&ctx->addr_list.head, &ctx->addr_list.tail, addr);
++	ctx->addr_list.count++;
+ }
+ 
+ /* quote with "" and escape all '\', '"' and "'" characters if need */
+@@ -339,6 +354,8 @@ static int parse_group(struct message_address_parser_context *ctx)
+ 		for (;;) {
+ 			/* mailbox-list    =
+ 			   	(mailbox *("," mailbox)) / obs-mbox-list */
++			if (!entries_have_room(ctx, 2))
++				break;
+ 			if (parse_mailbox(ctx) <= 0) {
+ 				/* broken mailbox - try to continue anyway. */
+ 			}
+@@ -390,8 +407,12 @@ static int parse_address_list(struct message_address_parser_context *ctx,
+ 
+ 	/* address-list    = (address *("," address)) / obs-addr-list */
+ 	while (max_addresses > 0) {
++		/* room for a mailbox and a fixed address after it, or for
++		   a group's start and end markers */
++		if (!entries_have_room(ctx, 2))
++			break;
+ 		max_addresses--;
+-		if ((ret = parse_address(ctx)) == 0)
++		if ((ret = parse_address(ctx)) == 0 || ctx->entry_limit_reached)
+ 			break;
+ 		if (ctx->parser.data >= ctx->parser.end ||
+ 		    *ctx->parser.data != ',') {
+@@ -400,7 +421,7 @@ static int parse_address_list(struct message_address_parser_context *ctx,
+ 		}
+ 		ctx->parser.data++;
+ 		if ((ret = rfc822_skip_lwsp(&ctx->parser)) <= 0) {
+-			if (ret < 0) {
++			if (ret < 0 && entries_have_room(ctx, 1)) {
+ 				/* ends with some garbage */
+ 				add_fixed_address(ctx);
+ 			}
+@@ -456,6 +477,8 @@ message_address_parse_real(pool_t pool, const unsigned char *data, size_t size,
+ 	ctx.str = t_str_new(128);
+ 	ctx.fill_missing = (flags & MESSAGE_ADDRESS_PARSE_FLAG_FILL_MISSING) != 0;
+ 	ctx.non_strict_dots = (flags & MESSAGE_ADDRESS_PARSE_FLAG_STRICT_DOTS) == 0;
++	ctx.max_entries = (flags & MESSAGE_ADDRESS_PARSE_FLAG_LIMIT_ALL_ENTRIES) != 0 ?
++		max_addresses : UINT_MAX;
+ 
+ 	if (rfc822_skip_lwsp(&ctx.parser) <= 0) {
+ 		/* no addresses */
+@@ -479,6 +502,7 @@ message_address_parse_path_real(pool_t pool, const unsigned char *data,
+ 	rfc822_parser_init(&ctx.parser, data, size, NULL);
+ 	ctx.pool = pool;
+ 	ctx.str = t_str_new(128);
++	ctx.max_entries = UINT_MAX;
+ 
+ 	ret = parse_path(&ctx);
+ 
+diff --git a/src/lib-mail/message-address.h b/src/lib-mail/message-address.h
+index 224f7a7..0e0f7dc 100644
+--- a/src/lib-mail/message-address.h
++++ b/src/lib-mail/message-address.h
+@@ -12,6 +12,12 @@ enum message_address_parse_flags {
+ 	   isn't enabled by default, because these kind of invalid addresses
+ 	   are commonly used in Japan. */
+ 	MESSAGE_ADDRESS_PARSE_FLAG_STRICT_DOTS = BIT(1),
++	/* Count every list entry against max_addresses: group start/end
++	   markers, group members and fixed-up invalid addresses. Parsing
++	   stops when the limit is reached, but a started group is still
++	   terminated. Without this flag only top-level addresses are
++	   counted. */
++	MESSAGE_ADDRESS_PARSE_FLAG_LIMIT_ALL_ENTRIES = BIT(2),
+ };
+ 
+ /* group: ... ; will be stored like:
+@@ -33,6 +39,7 @@ struct message_address {
+ 
+ struct message_address_list {
+ 	struct message_address *head, *tail;
++	unsigned int count;
+ };
+ 
+ /* Parse message addresses from given data. Note that giving an empty string
+diff --git a/src/lib-mail/message-decoder.c b/src/lib-mail/message-decoder.c
+index 845b3d5..4eea999 100644
+--- a/src/lib-mail/message-decoder.c
++++ b/src/lib-mail/message-decoder.c
+@@ -257,6 +257,10 @@ message_decode_body_init_charset(struct message_decoder_context *ctx,
+ 	if (ctx->binary_input)
+ 		return;
+ 
++	/* If some input was left untranslated in the previous MIME part,
++	   it needs to be discarded now so it won't affect the next part. */
++	ctx->translation_size = 0;
++
+ 	if (ctx->charset_trans != NULL && ctx->content_charset != NULL &&
+ 	    strcasecmp(ctx->content_charset, ctx->charset_trans_charset) == 0) {
+ 		/* already have the correct translation selected */
+diff --git a/src/lib-mail/message-header-parser.c b/src/lib-mail/message-header-parser.c
+index 5e020bb..a138b8d 100644
+--- a/src/lib-mail/message-header-parser.c
++++ b/src/lib-mail/message-header-parser.c
+@@ -96,7 +96,6 @@ int message_parse_header_next(struct message_header_parser_ctx *ctx,
+ 		/* new header line */
+ 		line->name_offset = ctx->input->v_offset;
+ 		colon_pos = UINT_MAX;
+-		ctx->header_block_total_size += ctx->value_buf->used;
+ 		buffer_set_used_size(ctx->value_buf, 0);
+ 	}
+ 
+@@ -362,12 +361,17 @@ int message_parse_header_next(struct message_header_parser_ctx *ctx,
+ 		}
+ 	}
+ 
+-	line->value_len = I_MIN(line->value_len, ctx->header_block_max_size);
+ 	size_t line_value_size = line->value_len;
+-	size_t header_total_used = ctx->header_block_total_size + ctx->value_buf->used;
+-	size_t line_available = ctx->header_block_max_size <= header_total_used ? 0 :
+-				ctx->header_block_max_size - header_total_used;
++	/* Clamp line_value_size against the remaining header_block_max_size
++	   budget. header_block_total_size is the running sum of
++	   line_value_size across all chunks of all headers; value_buf growth
++	   is bounded implicitly because every append to value_buf uses
++	   line_value_size. */
++	size_t line_available =
++		ctx->header_block_max_size <= ctx->header_block_total_size ? 0 :
++		ctx->header_block_max_size - ctx->header_block_total_size;
+ 	line_value_size = I_MIN(line_value_size, line_available);
++	ctx->header_block_total_size += line_value_size;
+ 
+ 	if (!line->continued) {
+ 		/* first header line. make a copy of the line since we can't
+@@ -397,10 +401,12 @@ int message_parse_header_next(struct message_header_parser_ctx *ctx,
+ 
+ 		line->full_value = ctx->value_buf->data;
+ 		line->full_value_len = ctx->value_buf->used;
++		line->value_len = line_value_size;
+ 	} else {
+ 		/* we didn't want full_value, and this is a continued line. */
+ 		line->full_value = NULL;
+ 		line->full_value_len = 0;
++		line->value_len = line_value_size;
+ 	}
+ 
+ 	/* always reset it */
+diff --git a/src/lib-mail/message-parser-from-parts.c b/src/lib-mail/message-parser-from-parts.c
+index 8e21ec8..349b0f3 100644
+--- a/src/lib-mail/message-parser-from-parts.c
++++ b/src/lib-mail/message-parser-from-parts.c
+@@ -303,6 +303,11 @@ static int preparsed_parse_next_header(struct message_parser_ctx *ctx,
+ 	}
+ 
+ 	if (hdr != NULL) {
++		if (!hdr->continues) {
++			ctx->all_headers_total_size += hdr->name_len;
++			ctx->all_headers_total_size += hdr->middle_len;
++		}
++		ctx->all_headers_total_size += hdr->value_len;
+ 		block_r->hdr = hdr;
+ 		block_r->size = 0;
+ 		return 1;
+@@ -344,6 +349,11 @@ static int preparsed_parse_next_header_init(struct message_parser_ctx *ctx,
+ 		message_parse_header_init(hdr_input, NULL, ctx->hdr_flags);
+ 	i_stream_unref(&hdr_input);
+ 
++	size_t headers_available =
++		ctx->all_headers_max_size > ctx->all_headers_total_size ?
++		ctx->all_headers_max_size - ctx->all_headers_total_size : 0;
++	message_parse_header_lower_limit(ctx->hdr_parser_ctx, headers_available);
++
+ 	ctx->parse_next_block = preparsed_parse_next_header;
+ 	return preparsed_parse_next_header(ctx, block_r);
+ }
+diff --git a/src/lib-mail/message-part-data.c b/src/lib-mail/message-part-data.c
+index 25019ab..f366d2d 100644
+--- a/src/lib-mail/message-part-data.c
++++ b/src/lib-mail/message-part-data.c
+@@ -173,6 +173,7 @@ envelope_get_field(const char *name)
+ 
+ void message_part_envelope_parse_from_header(pool_t pool,
+ 	struct message_part_envelope **data,
++	struct message_part_data_limits *limits,
+ 	struct message_header_line *hdr)
+ {
+ 	struct message_part_envelope *d;
+@@ -237,9 +238,13 @@ void message_part_envelope_parse_from_header(pool_t pool,
+ 	if (addr_p != NULL) {
+ 		message_address_parse_full(pool, hdr->full_value,
+ 					   hdr->full_value_len,
+-					   UINT_MAX,
+-					   MESSAGE_ADDRESS_PARSE_FLAG_FILL_MISSING,
++					   limits->remaining_addresses,
++					   MESSAGE_ADDRESS_PARSE_FLAG_FILL_MISSING |
++					   MESSAGE_ADDRESS_PARSE_FLAG_LIMIT_ALL_ENTRIES,
+ 					   &new_addr);
++		limits->remaining_addresses -=
++			I_MIN(new_addr.count, limits->remaining_addresses);
++
+ 		/* Merge multiple headers the same as if they were comma
+ 		   separated in a single line. This is better from security
+ 		   point of view, because attacker could intentionally write
+@@ -247,6 +252,7 @@ void message_part_envelope_parse_from_header(pool_t pool,
+ 		   validated while MUA only shows the second From header. */
+ 		DLLIST2_JOIN(&addr_p->head, &addr_p->tail,
+ 			     &new_addr.head, &new_addr.tail);
++		addr_p->count += new_addr.count;
+ 	} else if (str_p != NULL) {
+ 		*str_p = message_header_strdup(pool, hdr->full_value,
+ 					       hdr->full_value_len);
+@@ -258,7 +264,8 @@ void message_part_envelope_parse_from_header(pool_t pool,
+ static void
+ parse_mime_parameters(struct rfc822_parser_context *parser,
+ 	pool_t pool, const struct message_part_param **params_r,
+-	unsigned int *params_count_r)
++	unsigned int *params_count_r,
++	struct message_part_data_limits *limits)
+ {
+ 	const char *const *results;
+ 	struct message_part_param *params;
+@@ -270,6 +277,10 @@ parse_mime_parameters(struct rfc822_parser_context *parser,
+ 	i_assert((params_count % 2) == 0);
+ 	params_count /= 2;
+ 
++	if (params_count > limits->remaining_mime_params)
++		params_count = limits->remaining_mime_params;
++	limits->remaining_mime_params -= params_count;
++
+ 	if (params_count > 0) {
+ 		params = p_new(pool, struct message_part_param, params_count);
+ 		for (i = 0; i < params_count; i++) {
+@@ -284,7 +295,8 @@ parse_mime_parameters(struct rfc822_parser_context *parser,
+ 
+ static void
+ parse_content_type(struct message_part_data *data,
+-	pool_t pool, struct message_header_line *hdr)
++	pool_t pool, struct message_header_line *hdr,
++	struct message_part_data_limits *limits)
+ {
+ 	struct rfc822_parser_context parser;
+ 	string_t *str;
+@@ -327,7 +339,7 @@ parse_content_type(struct message_part_data *data,
+ 
+ 	parse_mime_parameters(&parser, pool,
+ 		&data->content_type_params,
+-		&data->content_type_params_count);
++		&data->content_type_params_count, limits);
+ 	rfc822_parser_deinit(&parser);
+ }
+ 
+@@ -352,7 +364,8 @@ parse_content_transfer_encoding(struct message_part_data *data,
+ 
+ static void
+ parse_content_disposition(struct message_part_data *data,
+-	pool_t pool, struct message_header_line *hdr)
++	pool_t pool, struct message_header_line *hdr,
++	struct message_part_data_limits *limits)
+ {
+ 	struct rfc822_parser_context parser;
+ 	string_t *str;
+@@ -369,13 +382,14 @@ parse_content_disposition(struct message_part_data *data,
+ 
+ 	parse_mime_parameters(&parser, pool,
+ 		&data->content_disposition_params,
+-		&data->content_disposition_params_count);
++		&data->content_disposition_params_count, limits);
+ 	rfc822_parser_deinit(&parser);
+ }
+ 
+ static void
+ parse_content_language(struct message_part_data *data,
+-	pool_t pool, const unsigned char *value, size_t value_len)
++	pool_t pool, const unsigned char *value, size_t value_len,
++	struct message_part_data_limits *limits)
+ {
+ 	struct rfc822_parser_context parser;
+ 	ARRAY_TYPE(const_string) langs;
+@@ -393,8 +407,11 @@ parse_content_language(struct message_part_data *data,
+ 
+ 	rfc822_skip_lwsp(&parser);
+ 	while (rfc822_parse_atom(&parser, str) >= 0) {
+-		const char *lang = p_strdup(pool, str_c(str));
++		if (limits->remaining_language_tags == 0)
++			break;
++		limits->remaining_language_tags--;
+ 
++		const char *lang = p_strdup(pool, str_c(str));
+ 		array_push_back(&langs, &lang);
+ 		str_truncate(str, 0);
+ 
+@@ -414,7 +431,8 @@ parse_content_language(struct message_part_data *data,
+ 
+ static void
+ parse_content_header(struct message_part_data *data,
+-	pool_t pool, struct message_header_line *hdr)
++	pool_t pool, struct message_header_line *hdr,
++	struct message_part_data_limits *limits)
+ {
+ 	const char *name = hdr->name + strlen("Content-");
+ 
+@@ -443,7 +461,7 @@ parse_content_header(struct message_part_data *data,
+ 	case 't':
+ 	case 'T':
+ 		if (strcasecmp(name, "Type") == 0 && data->content_type == NULL)
+-			parse_content_type(data, pool, hdr);
++			parse_content_type(data, pool, hdr, limits);
+ 		else if (strcasecmp(name, "Transfer-Encoding") == 0 &&
+ 			 data->content_transfer_encoding == NULL)
+ 			parse_content_transfer_encoding(data, pool, hdr);
+@@ -454,7 +472,7 @@ parse_content_header(struct message_part_data *data,
+ 		if (strcasecmp(name, "Language") == 0 &&
+ 		    data->content_language == NULL) {
+ 			parse_content_language(data, pool,
+-				hdr->full_value, hdr->full_value_len);
++				hdr->full_value, hdr->full_value_len, limits);
+ 		} else if (strcasecmp(name, "Location") == 0 &&
+ 			   data->content_location == NULL) {
+ 			data->content_location =
+@@ -472,13 +490,14 @@ parse_content_header(struct message_part_data *data,
+ 						      hdr->full_value_len);
+ 		else if (strcasecmp(name, "Disposition") == 0 &&
+ 			 data->content_disposition_params == NULL)
+-			parse_content_disposition(data, pool, hdr);
++			parse_content_disposition(data, pool, hdr, limits);
+ 		break;
+ 	}
+ }
+ 
+ void message_part_data_parse_from_header(pool_t pool,
+ 	struct message_part *part,
++	struct message_part_data_limits *limits,
+ 	struct message_header_line *hdr)
+ {
+ 	struct message_part_data *part_data;
+@@ -518,13 +537,14 @@ void message_part_data_parse_from_header(pool_t pool,
+ 
+ 	if (strncasecmp(hdr->name, "Content-", 8) == 0) {
+ 		T_BEGIN {
+-			parse_content_header(part_data, pool, hdr);
++			parse_content_header(part_data, pool, hdr, limits);
+ 		} T_END;
+ 	}
+ 
+ 	if (parent_rfc822) {
+ 		/* message/rfc822, we need the envelope */
+-		message_part_envelope_parse_from_header(pool, &part_data->envelope, hdr);
++		message_part_envelope_parse_from_header(pool, &part_data->envelope,
++							limits, hdr);
+ 	}
+ }
+ 
+diff --git a/src/lib-mail/message-part-data.h b/src/lib-mail/message-part-data.h
+index 7ec878d..9891e72 100644
+--- a/src/lib-mail/message-part-data.h
++++ b/src/lib-mail/message-part-data.h
+@@ -8,6 +8,22 @@
+ 
+ struct message_header_line;
+ 
++#define MESSAGE_PART_DATA_MAX_TOTAL_ADDRESSES 100000
++#define MESSAGE_PART_DATA_MAX_TOTAL_LANGUAGE_TAGS 100000
++/* Combined limit for Content-Type + Content-Disposition parameters */
++#define MESSAGE_PART_DATA_MAX_TOTAL_MIME_PARAMS 200000
++
++struct message_part_data_limits {
++	unsigned int remaining_addresses;
++	unsigned int remaining_language_tags;
++	unsigned int remaining_mime_params;
++};
++
++#define MESSAGE_PART_DATA_LIMITS_INIT \
++	{ MESSAGE_PART_DATA_MAX_TOTAL_ADDRESSES, \
++	  MESSAGE_PART_DATA_MAX_TOTAL_LANGUAGE_TAGS, \
++	  MESSAGE_PART_DATA_MAX_TOTAL_MIME_PARAMS }
++
+ struct message_part_param {
+ 	const char *name;
+ 	const char *value;
+@@ -93,11 +109,13 @@ bool message_part_is_attachment(struct message_part *part,
+ /* Update envelope data based from given header field */
+ void message_part_envelope_parse_from_header(pool_t pool,
+ 	struct message_part_envelope **_data,
++	struct message_part_data_limits *limits,
+ 	struct message_header_line *hdr);
+ 
+ /* Parse a single header. Note that this modifies part->context. */
+ void message_part_data_parse_from_header(pool_t pool,
+ 	struct message_part *part,
++	struct message_part_data_limits *limits,
+ 	struct message_header_line *hdr);
+ 
+ #endif
+diff --git a/src/lib-mail/test-message-decoder.c b/src/lib-mail/test-message-decoder.c
+index edf9210..ad212c8 100644
+--- a/src/lib-mail/test-message-decoder.c
++++ b/src/lib-mail/test-message-decoder.c
+@@ -260,8 +260,10 @@ static void test_message_decoder_content_transfer_encoding(void)
+ 	parser = message_parser_init(pool, istream, &parser_set);
+ 	decoder = message_decoder_init(NULL, 0);
+ 
++	struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT;
+ 	while ((ret = message_parser_parse_next_block(parser, &input)) > 0) {
+-		message_part_data_parse_from_header(pool, input.part, input.hdr);
++		message_part_data_parse_from_header(pool, input.part, &limits,
++						    input.hdr);
+ 		if (message_decoder_decode_next_block(decoder, &input, &output) &&
+ 		    output.hdr == NULL && output.size > 0)
+ 			str_append_data(str_out, output.data, output.size);
+@@ -349,8 +351,10 @@ static void test_message_decoder_invalid_content_transfer_encoding(void)
+ 	parser = message_parser_init(pool, istream, &parser_set);
+ 	decoder = message_decoder_init(NULL, 0);
+ 
++	struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT;
+ 	while ((ret = message_parser_parse_next_block(parser, &input)) > 0) {
+-		message_part_data_parse_from_header(pool, input.part, input.hdr);
++		message_part_data_parse_from_header(pool, input.part, &limits,
++						    input.hdr);
+ 		if (input.hdr != NULL &&
+ 		    strcasecmp(input.hdr->name, "content-transfer-encoding") == 0) {
+ 			enum message_cte cte = message_decoder_parse_cte(input.hdr);
+@@ -480,8 +484,63 @@ UNICODE_REPLACEMENT_CHAR_UTF8;
+ 	parser = message_parser_init(pool, istream, &parser_set);
+ 	decoder = message_decoder_init(NULL, 0);
+ 
++	struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT;
+ 	while ((ret = message_parser_parse_next_block(parser, &input)) > 0) {
+-		message_part_data_parse_from_header(pool, input.part, input.hdr);
++		message_part_data_parse_from_header(pool, input.part, &limits,
++						    input.hdr);
++		if (message_decoder_decode_next_block(decoder, &input, &output) &&
++		    output.hdr == NULL && output.size > 0)
++			str_append_data(str_out, output.data, output.size);
++	}
++
++	test_assert(ret == -1);
++	test_assert_strcmp(test_message_output, str_c(str_out));
++	message_decoder_deinit(&decoder);
++	message_parser_deinit(&parser, &parts);
++	test_assert(istream->stream_errno == 0);
++
++	i_stream_unref(&istream);
++	pool_unref(&pool);
++	test_end();
++}
++
++static void test_message_decoder_charset_mime_part_change(void)
++{
++	static const unsigned char test_message_input[] =
++"Content-Type: multipart/mixed; boundary=\"1\"\n"
++"MIME-Version: 1.0\n\n"
++"--1\n"
++"Content-Type: text/plain; charset=utf-8\n\n"
++"\xc3\n"
++"--1\n"
++"Content-Type: text/plain; charset=utf-8\n\n"
++"\xa4\n"
++"--1--\n";
++
++	static const char *test_message_output =
++		UNICODE_REPLACEMENT_CHAR_UTF8;
++
++	test_begin("message decoder charset - mime part change");
++
++	const struct message_parser_settings parser_set = { .flags = 0, };
++	struct message_parser_ctx *parser;
++	struct message_decoder_context *decoder;
++	struct message_part *parts;
++	struct message_block input, output;
++	struct istream *istream;
++	string_t *str_out = t_str_new(20);
++	int ret;
++
++	pool_t pool = pool_alloconly_create("message parser", 10240);
++	istream = test_istream_create_data(test_message_input,
++					   sizeof(test_message_input)-1);
++	parser = message_parser_init(pool, istream, &parser_set);
++	decoder = message_decoder_init(NULL, 0);
++
++	struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT;
++	while ((ret = message_parser_parse_next_block(parser, &input)) > 0) {
++		message_part_data_parse_from_header(pool, input.part, &limits,
++						    input.hdr);
+ 		if (message_decoder_decode_next_block(decoder, &input, &output) &&
+ 		    output.hdr == NULL && output.size > 0)
+ 			str_append_data(str_out, output.data, output.size);
+@@ -507,6 +566,7 @@ int main(void)
+ 		test_message_decoder_content_transfer_encoding,
+ 		test_message_decoder_invalid_content_transfer_encoding,
+ 		test_message_decoder_charset,
++		test_message_decoder_charset_mime_part_change,
+ 		NULL
+ 	};
+ 	return test_run(test_functions);
+diff --git a/src/lib-mail/test-message-header-parser.c b/src/lib-mail/test-message-header-parser.c
+index 93d8842..eb608f9 100644
+--- a/src/lib-mail/test-message-header-parser.c
++++ b/src/lib-mail/test-message-header-parser.c
+@@ -494,11 +494,14 @@ static void test_message_header_truncation_clean_oneline(void)
+ 	struct message_header_parser_ctx *parser = message_parse_header_init(input, NULL, MESSAGE_HEADER_PARSER_FLAG_CLEAN_ONELINE);
+ 	message_parse_header_set_limit(parser, 96);
+ 
++	/* hdr->value is now also clamped cumulatively against the same
++	   header_block_max_size budget as full_value, so later chunks of a
++	   multiline header shrink or disappear once the budget is used up. */
+ 	assert_parse_line( 1, "header1", "this is short",	                     "this is short");
+ 	assert_parse_line( 2, "header2", "this is multiline", 	                     "this is multiline");
+ 	assert_parse_line( 3, "header2", " and long 343638404244464850525456586062", "this is multiline and long 343638404244464850525456586062");
+-	assert_parse_line( 4, "header2", " 64666870727476788082848688909294969800",  "this is multiline and long 343638404244464850525456586062 6466687072747678808284868");
+-	assert_parse_line( 5, "header2", " 02040608101214161820222426283032343638",  "this is multiline and long 343638404244464850525456586062 6466687072747678808284868");
++	assert_parse_line( 4, "header2", " 6466687072747678808284868",               "this is multiline and long 343638404244464850525456586062 6466687072747678808284868");
++	assert_parse_line( 5, "header2", "",                                         "this is multiline and long 343638404244464850525456586062 6466687072747678808284868");
+ 	assert_parse_line( 6, "header3", "", "");
+ 	test_assert(message_parse_header_next(parser, &hdr) > 0 && hdr->eoh);
+ 
+@@ -515,11 +518,16 @@ static void test_message_header_truncation_flag0(void)
+ 	struct message_header_parser_ctx *parser = message_parse_header_init(input, NULL, 0);
+ 	message_parse_header_set_limit(parser, 96);
+ 
++	/* hdr->value is clamped cumulatively against header_block_max_size.
++	   The \n that NO flags inserts between continuations goes into
++	   value_buf but is not added to header_block_total_size, so line 4's
++	   value hits the same 26-byte cap as in CLEAN_ONELINE and
++	   full_value_len is one byte larger than the nominal limit. */
+ 	assert_parse_line( 1, "header1", "this is short",	                     "this is short");
+ 	assert_parse_line( 2, "header2", "this is multiline", 	                     "this is multiline");
+ 	assert_parse_line( 3, "header2", " and long 343638404244464850525456586062", "this is multiline\n and long 343638404244464850525456586062");
+-	assert_parse_line( 4, "header2", " 64666870727476788082848688909294969800",  "this is multiline\n and long 343638404244464850525456586062\n 646668707274767880828486");
+-	assert_parse_line( 5, "header2", " 02040608101214161820222426283032343638",  "this is multiline\n and long 343638404244464850525456586062\n 646668707274767880828486");
++	assert_parse_line( 4, "header2", " 6466687072747678808284868",               "this is multiline\n and long 343638404244464850525456586062\n 6466687072747678808284868");
++	assert_parse_line( 5, "header2", "",                                         "this is multiline\n and long 343638404244464850525456586062\n 6466687072747678808284868");
+ 	assert_parse_line( 6, "header3", "", "");
+ 	test_assert(message_parse_header_next(parser, &hdr) > 0 && hdr->eoh);
+ 
+diff --git a/src/lib-mail/test-message-parser.c b/src/lib-mail/test-message-parser.c
+index b6bada2..60187a5 100644
+--- a/src/lib-mail/test-message-parser.c
++++ b/src/lib-mail/test-message-parser.c
+@@ -51,12 +51,13 @@ static int message_parse_stream(pool_t pool, struct istream *input,
+ 	struct message_parser_ctx *parser;
+ 	struct message_block block;
+ 
++	struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT;
+ 	i_zero(&block);
+ 	parser = message_parser_init(pool, input, set);
+ 	while ((ret = message_parser_parse_next_block(parser, &block)) > 0)
+ 		if (parse_data)
+ 			message_part_data_parse_from_header(pool, block.part,
+-							    block.hdr);
++							    &limits, block.hdr);
+ 	message_parser_deinit(&parser, parts_r);
+ 	test_assert(input->stream_errno == 0);
+ 	return ret;
+diff --git a/src/lib-storage/index/index-mail-headers.c b/src/lib-storage/index/index-mail-headers.c
+index ce23e9d..e0d8134 100644
+--- a/src/lib-storage/index/index-mail-headers.c
++++ b/src/lib-storage/index/index-mail-headers.c
+@@ -304,12 +304,15 @@ void index_mail_parse_header(struct message_part *part,
+ 	if (data->save_bodystructure_header &&
+ 	    !data->parsed_bodystructure_header) {
+ 		i_assert(part != NULL);
+-		message_part_data_parse_from_header(mail->mail.data_pool, part, hdr);
++		message_part_data_parse_from_header(mail->mail.data_pool, part,
++						    &mail->data.part_data_limits,
++						    hdr);
+ 	}
+ 
+ 	if (data->save_envelope) {
+ 		message_part_envelope_parse_from_header(mail->mail.data_pool,
+-					   &data->envelope_data, hdr);
++					   &data->envelope_data,
++					   &mail->data.part_data_limits, hdr);
+ 
+ 		if (hdr == NULL)
+                         index_mail_parse_finish_imap_envelope(mail);
+@@ -506,7 +509,8 @@ imap_envelope_parse_callback(struct message_header_line *hdr,
+ 			     struct index_mail *mail)
+ {
+ 	message_part_envelope_parse_from_header(mail->mail.data_pool,
+-				   &mail->data.envelope_data, hdr);
++				   &mail->data.envelope_data,
++				   &mail->data.part_data_limits, hdr);
+ 
+ 	if (hdr == NULL)
+ 		index_mail_parse_finish_imap_envelope(mail);
+@@ -985,6 +989,11 @@ int index_mail_get_header_stream(struct mail *_mail,
+ 					      HEADER_FILTER_HIDE_BODY,
+ 					      headers->name, headers->count,
+ 					      header_cache_callback, mail);
++	/* Cap per-header data so a single pathological header cannot exhaust
++	   memory in mail->header_data / the filter's buffer. */
++	i_stream_header_filter_set_max_header_block_size(
++		mail->data.filter_stream,
++		MESSAGE_HEADER_BLOCK_DEFAULT_MAX_SIZE);
+ 	*stream_r = mail->data.filter_stream;
+ 	return 0;
+ }
+diff --git a/src/lib-storage/index/index-mail.c b/src/lib-storage/index/index-mail.c
+index a5a280d..ab0277e 100644
+--- a/src/lib-storage/index/index-mail.c
++++ b/src/lib-storage/index/index-mail.c
+@@ -702,11 +702,16 @@ void index_mail_cache_pop3_data(struct mail *_mail,
+ 				     &order, sizeof(order));
+ }
+ 
++struct parse_bodystructure_ctx {
++	pool_t pool;
++	struct message_part_data_limits *limits;
++};
++
+ static void parse_bodystructure_part_header(struct message_part *part,
+ 					    struct message_header_line *hdr,
+-					    pool_t pool)
++					    struct parse_bodystructure_ctx *ctx)
+ {
+-	message_part_data_parse_from_header(pool, part, hdr);
++	message_part_data_parse_from_header(ctx->pool, part, ctx->limits, hdr);
+ }
+ 
+ static bool want_plain_bodystructure_cached(struct index_mail *mail)
+@@ -1321,9 +1326,13 @@ static int index_mail_parse_body(struct index_mail *mail,
+ 		/* bodystructure header is parsed, we want the body's mime
+ 		   headers too */
+ 		i_assert(data->parsed_bodystructure_header);
++		struct parse_bodystructure_ctx bsctx = {
++			.pool = mail->mail.data_pool,
++			.limits = &mail->data.part_data_limits,
++		};
+ 		message_parser_parse_body(data->parser_ctx,
+ 					  parse_bodystructure_part_header,
+-					  mail->mail.data_pool);
++					  &bsctx);
+ 	} else {
+ 		message_parser_parse_body(data->parser_ctx,
+ 			*null_message_part_header_callback, NULL);
+@@ -1851,6 +1860,8 @@ static void index_mail_init_data(struct index_mail *mail)
+ 	data->received_date = (time_t)-1;
+ 	data->sent_date.time = (uint32_t)-1;
+ 	data->dont_cache_field_idx = UINT_MAX;
++	data->part_data_limits = (struct message_part_data_limits)
++		MESSAGE_PART_DATA_LIMITS_INIT;
+ 
+ 	data->wanted_fields = mail->mail.wanted_fields;
+ 	if (mail->mail.wanted_headers != NULL) {
+@@ -2311,7 +2322,9 @@ void index_mail_cache_parse_continue(struct mail *_mail)
+ 				mail->data.header_parsed = TRUE;
+ 		} else {
+ 			message_part_data_parse_from_header(mail->mail.data_pool,
+-							block.part, block.hdr);
++							block.part,
++							&mail->data.part_data_limits,
++							block.hdr);
+ 		}
+ 	}
+ }
+diff --git a/src/lib-storage/index/index-mail.h b/src/lib-storage/index/index-mail.h
+index deb2831..1f37fab 100644
+--- a/src/lib-storage/index/index-mail.h
++++ b/src/lib-storage/index/index-mail.h
+@@ -2,6 +2,7 @@
+ #define INDEX_MAIL_H
+ 
+ #include "message-size.h"
++#include "message-part-data.h"
+ #include "mail-cache.h"
+ #include "mail-storage-private.h"
+ 
+@@ -86,6 +87,7 @@ struct index_mail_data {
+ 	const char *envelope, *body, *bodystructure, *guid, *filename;
+ 	const char *from_envelope, *body_snippet;
+ 	struct message_part_envelope *envelope_data;
++	struct message_part_data_limits part_data_limits;
+ 
+ 	uint32_t cache_flags;
+ 	uint64_t modseq, pvt_modseq;
+diff --git a/src/lib-storage/index/mbox/mbox-sync-parse.c b/src/lib-storage/index/mbox/mbox-sync-parse.c
+index bbc2da2..0fd7679 100644
+--- a/src/lib-storage/index/mbox/mbox-sync-parse.c
++++ b/src/lib-storage/index/mbox/mbox-sync-parse.c
+@@ -479,6 +479,9 @@ int mbox_sync_parse_next_mail(struct istream *input,
+ 
+         line_start_pos = 0;
+ 	hdr_ctx = message_parse_header_init(input, NULL, 0);
++	/* Rewriting the mbox requires the full raw header bytes, so disable
++	   the default per-header block size limit. */
++	message_parse_header_set_limit(hdr_ctx, SIZE_MAX);
+ 	while ((ret = message_parse_header_next(hdr_ctx, &hdr)) > 0) {
+ 		if (hdr->eoh) {
+ 			ctx->have_eoh = TRUE;
+@@ -576,6 +579,8 @@ bool mbox_sync_parse_match_mail(struct mbox_mailbox *mbox,
+         mbox_md5_ctx = mbox->md5_v.init();
+ 
+ 	hdr_ctx = message_parse_header_init(mbox->mbox_stream, NULL, 0);
++	/* MD5 matching must see the full raw header bytes. */
++	message_parse_header_set_limit(hdr_ctx, SIZE_MAX);
+ 	while ((ret = message_parse_header_next(hdr_ctx, &hdr)) > 0) {
+ 		if (hdr->eoh)
+ 			break;
diff --git a/CVE-2026-27857.patch b/CVE-2026-27857.patch
index fe94a12..dd3b8d0 100644
--- a/CVE-2026-27857.patch
+++ b/CVE-2026-27857.patch
@@ -6,7 +6,7 @@ Subject: [PATCH 12/24] lib-imap, global: Add params parameter to
 
 ---
  src/imap-login/imap-login-client.c     |  4 ++--
- src/imap-login/imap-login-cmd-id.c     |  4 +++-
+ src/imap-login/imap-login-cmd-id.c     |  3 ++-
  src/imap/cmd-append.c                  |  3 ++-
  src/imap/cmd-setmetadata.c             |  3 ++-
  src/imap/imap-client.c                 |  3 ++-
@@ -18,7 +18,7 @@ Subject: [PATCH 12/24] lib-imap, global: Add params parameter to
  src/lib-imap/imap-parser.h             |  6 +++++-
  src/lib-imap/test-imap-parser.c        | 10 +++++-----
  src/plugins/virtual/virtual-config.c   |  2 +-
- 13 files changed, 30 insertions(+), 19 deletions(-)
+ 13 files changed, 29 insertions(+), 19 deletions(-)
 
 --- a/src/imap-login/imap-login-client.c
 +++ b/src/imap-login/imap-login-client.c
@@ -42,14 +42,13 @@ Subject: [PATCH 12/24] lib-imap, global: Add params parameter to
  	imap_client->skip_line = FALSE;
 --- a/src/imap-login/imap-login-cmd-id.c
 +++ b/src/imap-login/imap-login-cmd-id.c
-@@ -237,7 +237,9 @@ int cmd_id(struct imap_client *client)
+@@ -237,7 +237,8 @@ int cmd_id(struct imap_client *client)
  		client->cmd_id = id = i_new(struct imap_client_cmd_id, 1);
  		id->parser = imap_parser_create(client->common.input,
  						client->common.output,
 -						IMAP_LOGIN_MAX_LINE_LENGTH);
 +						IMAP_LOGIN_MAX_LINE_LENGTH,
 +						NULL);
-+		id->log_reply = str_new(default_pool, 64);
  		if (client->set->imap_literal_minus)
  			imap_parser_enable_literal_minus(id->parser);
  		parser_flags = IMAP_PARSE_FLAG_STOP_AT_LIST;
@@ -479,9 +478,9 @@ grow memory usage excessively.
  						IMAP_LOGIN_MAX_LINE_LENGTH,
 -						NULL);
 +						&params);
- 		id->log_reply = str_new(default_pool, 64);
  		if (client->set->imap_literal_minus)
  			imap_parser_enable_literal_minus(id->parser);
+ 		parser_flags = IMAP_PARSE_FLAG_STOP_AT_LIST;
 
 From e0b953af76d754c2984c2867b71fccfef5231bf5 Mon Sep 17 00:00:00 2001
 From: Timo Sirainen <timo.sirainen at open-xchange.com>
diff --git a/CVE-2026-33604.patch b/CVE-2026-33604.patch
new file mode 100644
index 0000000..ccb1754
--- /dev/null
+++ b/CVE-2026-33604.patch
@@ -0,0 +1,387 @@
+Subject: [PATCH] lib-mail: ostream-dot - Don't send unguarded "." after
+ bare CR (CVE-2026-33604)
+
+A bare CR followed by "." in relayed mail (sieve redirect, submission
+relay) was not dot-stuffed, so a message could end the SMTP DATA early
+and smuggle further SMTP commands.
+
+Backport via Debian trixie 1:2.4.1+dfsg1-6+deb13u7 of:
+  https://github.com/dovecot/core/commit/02dfc4c970d7b5b6093ec0551aae727ddc8c1453
+  https://github.com/dovecot/core/commit/1da3e4dc88388bb818bcb73610489249e2458353
+  https://github.com/dovecot/core/commit/4677492d038f5187363790b5a93bd5fccc989a98
+  https://github.com/dovecot/core/commit/6e7860f07e11441d2a2e1c00f5f043d0a565b262
+  https://github.com/dovecot/core/commit/8f04979a7e72d3b3e04f3a93bd8088f5e2332dd9
+  https://github.com/dovecot/core/commit/e94a6c3cb984f9d1e5fe51714ea5015205d79fd1
+  https://github.com/dovecot/core/commit/eeeba5dee9c3fab3be595178de6c1352677e8489
+---
+ src/lib-mail/ostream-dot.c      | 92 +++++++++++++++++++++++++++------
+ src/lib-mail/test-ostream-dot.c | 86 ++++++++++++++++++++++++++++++
+ src/lib-test/test-common.c      | 33 ++++++++++++
+ src/lib-test/test-common.h      | 27 +++++++++-
+ 4 files changed, 220 insertions(+), 18 deletions(-)
+
+diff --git a/src/lib-mail/ostream-dot.c b/src/lib-mail/ostream-dot.c
+index f5bfa72..51c8bcf 100644
+--- a/src/lib-mail/ostream-dot.c
++++ b/src/lib-mail/ostream-dot.c
+@@ -71,6 +71,14 @@ o_stream_dot_close(struct iostream_private *stream, bool close_parent)
+ 		o_stream_close(dstream->ostream.parent);
+ }
+ 
++#define ADD_MAX 3
++enum o_stream_dot_sendv_add {
++	ADD_NONE,
++	ADD_CR,
++	ADD_DOT,
++	ADD_LF_DOT,
++};
++
+ static ssize_t
+ o_stream_dot_sendv(struct ostream_private *stream,
+ 		    const struct const_iovec *iov, unsigned int iov_count)
+@@ -105,31 +113,43 @@ o_stream_dot_sendv(struct ostream_private *stream,
+ 
+ 		p = data;
+ 		pend = CONST_PTR_OFFSET(data, size);
+-		for (; p < pend && (size_t)(p-data)+2 < max_bytes; p++) {
+-			char add = 0;
++		for (; p < pend && ((size_t)(p - data) + ADD_MAX) <= max_bytes; p++) {
++			enum o_stream_dot_sendv_add add = ADD_NONE;
+ 
++			size = pend - p;
+ 			switch (dstream->state) {
+ 			/* none */
+-			case STREAM_STATE_NONE:
++			case STREAM_STATE_NONE: {
++				size_t maxlen = I_MIN(size, max_bytes - ((size_t)(p - data) + ADD_MAX));
++				p = CONST_PTR_OFFSET(p, i_memcspn(p, maxlen, "\r\n", 2));
++				i_assert(p <= pend);
++				if (p == pend) {
++					p--;
++					continue;
++				}
+ 				switch (*p) {
+ 				case '\n':
+ 					dstream->state = STREAM_STATE_CRLF;
+-					/* add missing CR */
+-					add = '\r';
++					add = ADD_CR;
+ 					break;
+ 				case '\r':
+ 					dstream->state = STREAM_STATE_CR;
+ 					break;
+ 				}
+ 				break;
++			}
+ 			/* got CR */
+ 			case STREAM_STATE_CR:
++				i_assert(p < pend);
+ 				switch (*p) {
+ 				case '\r':
+ 					break;
+ 				case '\n':
+ 					dstream->state = STREAM_STATE_CRLF;
+ 					break;
++				case '.':
++					add = ADD_LF_DOT;
++					/* fall through */
+ 				default:
+ 					dstream->state = STREAM_STATE_NONE;
+ 					break;
+@@ -138,18 +158,17 @@ o_stream_dot_sendv(struct ostream_private *stream,
+ 			/* got CRLF, or the first line */
+ 			case STREAM_STATE_INIT:
+ 			case STREAM_STATE_CRLF:
++				i_assert(p < pend);
+ 				switch (*p) {
+ 				case '\r':
+ 					dstream->state = STREAM_STATE_CR;
+ 					break;
+ 				case '\n':
+ 					dstream->state = STREAM_STATE_CRLF;
+-					/* add missing CR */
+-					add = '\r';
++					add = ADD_CR;
+ 					break;
+ 				case '.':
+-					/* add dot */
+-					add = '.';
++					add = ADD_DOT;
+ 					/* fall through */
+ 				default:
+ 					dstream->state = STREAM_STATE_NONE;
+@@ -172,22 +191,61 @@ o_stream_dot_sendv(struct ostream_private *stream,
+ 					max_bytes -= chunk;
+ 					sent += chunk;
+ 				}
+-				/* insert byte (substitute one with pair) */
+ 				data++;
+-				iovn.iov_base = (add == '\r' ? "\r\n" : "..");
+-				iovn.iov_len = 2;
++
++				/* Apply the modifications required according to RFC 5321 to the
++				   stream :
++
++				   ADD_DOT    - Apply standard SMTP dot-stuffing
++
++				   ADD_CR     - Convert invalid lone LFs to CRLF to comply with
++						DATA line termination requirements, and avoid
++						potentially emitting bare "\n." sequences (same
++						threat as below for "\r." sequences).
++
++				   ADD_LF_DOT - Guard against invalid "\r." sequences.
++						A downstream MTA that incorrectly handles bare CRs
++						as line terminators could interpret a '.' at the
++						start of the next line as end-of-DATA. This would
++						allow any following bytes to be processed as SMTP
++						commands.
++
++				   ADD_CR and ADD_LF_DOT make the istream-dot round-trip lossy,
++				   as these introduce bytes not present in the original input.
++				   We accept this tradeoff, since preserving exact byte fidelity
++				   for malformed input is less important than eliminating an
++				   injection vector. */
++
++				switch(add) {
++				case ADD_DOT:
++					iovn.iov_base = "..";
++					iovn.iov_len = 2;
++					break;
++				case ADD_CR:
++					iovn.iov_base = "\r\n";
++					iovn.iov_len = 2;
++					break;
++				case ADD_LF_DOT:
++					iovn.iov_base = "\n..";
++					iovn.iov_len = 3;
++					break;
++				default:
++					i_unreached();
++				}
++
+ 				array_push_back(&iov_arr, &iovn);
+-				i_assert(max_bytes >= 2);
+-				max_bytes -= 2;
+-				added++;
++				i_assert(iovn.iov_len <= ADD_MAX);
++				i_assert(iovn.iov_len <= max_bytes);
++				max_bytes -= iovn.iov_len;
++				added += iovn.iov_len - 1;
+ 				sent++;
+ 			}
+ 		}
+ 
+ 		if (max_bytes == 0)
+ 			break;
+-		chunk = ((size_t)(p-data) >= max_bytes ?
+-				max_bytes : (size_t)(p - data));
++		i_assert(p <= pend);
++		chunk = I_MIN((size_t)(p - data), max_bytes);
+ 		if (chunk > 0) {
+ 			iovn.iov_base = data;
+ 			iovn.iov_len = chunk;
+diff --git a/src/lib-mail/test-ostream-dot.c b/src/lib-mail/test-ostream-dot.c
+index 9ddb563..4e1b297 100644
+--- a/src/lib-mail/test-ostream-dot.c
++++ b/src/lib-mail/test-ostream-dot.c
+@@ -57,6 +57,9 @@ static void test_ostream_dot(void)
+ 		{ "foo\n.\n", "foo\r\n..\r\n.\r\n" },
+ 		{ ".foo\r\n.\r\nfoo\r\n", "..foo\r\n..\r\nfoo\r\n.\r\n" },
+ 		{ ".foo\n.\nfoo\n", "..foo\r\n..\r\nfoo\r\n.\r\n" },
++		{ ".", "..\r\n.\r\n" },
++		{ "\r.", "\r\n..\r\n.\r\n" },
++		{ "\r\r.", "\r\r\n..\r\n.\r\n" },
+ 		{ "\r\n", "\r\n.\r\n" },
+ 		{ "\n", "\r\n.\r\n" },
+ 		{ "", "\r\n.\r\n" },
+@@ -92,11 +95,94 @@ static void test_ostream_dot_parent_almost_full(void)
+ 	test_end();
+ }
+ 
++static void test_ostream_dot_parent_max_bytes_boundary(void)
++{
++	buffer_t *output_data;
++	struct ostream *test_output, *output;
++	ssize_t ret;
++
++	test_begin("dot ostream parent exact fit");
++	output_data = t_buffer_create(1024);
++	test_output = test_ostream_create_nonblocking(output_data, 3);
++	test_ostream_set_max_output_size(test_output, 3);
++
++	output = o_stream_create_dot(test_output, FALSE);
++	ret = o_stream_send(output, ".", 1);
++	test_assert(ret == 1);
++	test_assert_ucmp(output_data->used, ==, 2);
++	test_assert_memcmp(output_data->data, output_data->used, "..", 2);
++
++	o_stream_unref(&output);
++	o_stream_unref(&test_output);
++	test_end();
++}
++
++/* STATE_CR must persist across sendv calls so that a bare CR ending one send
++   followed by '.' starting the next still triggers ADD_LF_DOT.
++   A stateless per-call implementation would emit the '.' unguarded and let a
++   downstream MTA that treats bare CR as EOL interpret it as end-of-DATA. */
++static void test_ostream_dot_cr_across_sendv(void)
++{
++	buffer_t *output_data;
++	struct ostream *test_output, *output;
++	ssize_t ret;
++	const char *expected = "\r\n..\r\n.\r\n";
++
++	test_begin("dot ostream CR across sendv calls");
++	output_data = t_buffer_create(1024);
++	test_output = o_stream_create_buffer(output_data);
++
++	output = o_stream_create_dot(test_output, FALSE);
++	ret = o_stream_send(output, "\r", 1);
++	test_assert(ret == 1);
++	ret = o_stream_send(output, ".", 1);
++	test_assert(ret == 1);
++	test_assert(o_stream_finish(output) > 0);
++
++	o_stream_unref(&output);
++	o_stream_unref(&test_output);
++
++	test_assert_ucmp(str_len(output_data), ==, strlen(expected));
++	test_assert_memcmp(str_c(output_data), str_len(output_data),
++	expected, strlen(expected));
++	test_end();
++}
++
++/* Off-by-one regression guard for the bare-CR + '.' injection.
++   Input "\r." places '.' at offset 1; the ADD_LF_DOT pair injects 3 bytes
++   ("\n.."). The loop guard check becomes (1 + 3) <= max_bytes, so max_bytes==4
++   is the exact-fit case. */
++static void test_ostream_dot_cr_dot_exact_fit(void)
++{
++	buffer_t *output_data;
++	struct ostream *test_output, *output;
++	ssize_t ret;
++
++	test_begin("dot ostream CR+dot exact fit");
++	output_data = t_buffer_create(1024);
++	test_output = test_ostream_create_nonblocking(output_data, 4);
++	test_ostream_set_max_output_size(test_output, 4);
++
++	output = o_stream_create_dot(test_output, FALSE);
++	ret = o_stream_send(output, "\r.", 2);
++	test_assert(ret == 2);
++	test_assert_ucmp(output_data->used, ==, 4);
++	test_assert_memcmp(output_data->data, output_data->used,
++	"\r\n..", 4);
++
++	o_stream_unref(&output);
++	o_stream_unref(&test_output);
++	test_end();
++}
++
+ int main(void)
+ {
+ 	static void (*const test_functions[])(void) = {
+ 		test_ostream_dot,
+ 		test_ostream_dot_parent_almost_full,
++		test_ostream_dot_parent_max_bytes_boundary,
++		test_ostream_dot_cr_across_sendv,
++		test_ostream_dot_cr_dot_exact_fit,
+ 		NULL
+ 	};
+ 	return test_run(test_functions);
+diff --git a/src/lib-test/test-common.c b/src/lib-test/test-common.c
+index feea7ec..8e4c7ba 100644
+--- a/src/lib-test/test-common.c
++++ b/src/lib-test/test-common.c
+@@ -82,6 +82,39 @@ void test_assert_failed_strcmp_idx(const char *code, const char *file, unsigned
+ #endif
+ }
+ 
++static void print_memcmp_data(const void *_data, size_t len)
++{
++	const unsigned char *data = _data;
++	size_t i;
++
++	for (i = 0; i < len; i++) {
++		if (data[i] >= 0x20 && data[i] < 0x7f)
++			printf("%c", data[i]);
++		else
++			printf("\\x%02X", data[i]);
++	}
++}
++
++void test_assert_failed_memcmp_idx(const char *code, const char *file, unsigned int line,
++				   const void *src, const void *dst, size_t len, long long i)
++{
++	printf("%s:%u: Assert", file, line);
++	if (i == LLONG_MIN)
++		printf(" failed: %s\n", code);
++	else
++		printf("(#%lld) failed: %s\n", i, code);
++	printf("        \"");
++	print_memcmp_data(src, len);
++	printf("\" != \"");
++	print_memcmp_data(dst, len);
++	printf("\" (len == %zu)", len);
++	fflush(stdout);
++	test_success = FALSE;
++#ifdef STATIC_CHECKER
++	i_unreached();
++#endif
++}
++
+ void test_assert_failed_cmp_intmax_idx(const char *code, const char *file,
+ 				       unsigned int line,
+ 				       intmax_t src, intmax_t dst,
+diff --git a/src/lib-test/test-common.h b/src/lib-test/test-common.h
+index f845c0d..32cf223 100644
+--- a/src/lib-test/test-common.h
++++ b/src/lib-test/test-common.h
+@@ -32,7 +32,14 @@ void test_begin(const char *name);
+ 		test_assert_strcmp_idx(s1, s2, LLONG_MIN); \
+ 	} STMT_END
+ 
+-/* Same as test_assert_strcmp expect that it takes an additional i as input.
++/* Additional parameters are m1 (source) and m2 (destination) memory and len
++ * in memcmp().
++ */
++#define test_assert_memcmp(m1, len1, m2, len2) STMT_START { \
++		test_assert_memcmp_idx(m1, len1, m2, len2, LLONG_MIN); \
++	} STMT_END
++
++/* Same as test_assert_strcmp except that it takes an additional i as input.
+  * When i is greater than or equals 0 it is used to identify the barrage of
+  * tests failed like in test_assert_idx.
+ */
+@@ -44,6 +51,21 @@ void test_begin(const char *name);
+ 						      __FILE__, __LINE__, _temp_s1, _temp_s2, i); \
+ 	} STMT_END
+ 
++/* Same as test_assert_memcmp except that it takes an additional i as input.
++ * When i is greater than or equals 0 it is used to identify the barrage of
++ * tests failed like in test_assert_idx.
++*/
++#define test_assert_memcmp_idx(_m1, _len1, _m2, _len2, i) STMT_START { \
++		const void *_temp_m1 = (_m1); \
++		const void *_temp_m2 = (_m2); \
++		const size_t _temp_len = I_MIN((_len1), (_len2)); \
++		if ((_len1) != (_len2)) \
++			test_assert_failed_ucmp_intmax_idx(#_len1 " == " #_len2, __FILE__, __LINE__, _len1, _len2, "=", i); \
++		if ((memcmp(_temp_m1, _temp_m2, _temp_len) != 0)) \
++			test_assert_failed_memcmp_idx("memcmp(" #_m1 ","  #_m2 ","  #_len2 ")", \
++						      __FILE__, __LINE__, _temp_m1, _temp_m2, _temp_len, i); \
++	} STMT_END
++
+ #define test_assert_cmp(_value1, _op, _value2) \
+ 	test_assert_cmp_idx(_value1, _op, _value2, LLONG_MIN)
+ #define test_assert_cmp_idx(_value1, _op, _value2, _idx) STMT_START { \
+@@ -81,6 +103,9 @@ void test_assert_failed_idx(const char *code, const char *file, unsigned int lin
+ void test_assert_failed_strcmp_idx(const char *code, const char *file, unsigned int line,
+ 				   const char * src, const char * dst, long long i)
+ 	ATTR_STATIC_CHECKER_NORETURN;
++void test_assert_failed_memcmp_idx(const char *code, const char *file, unsigned int line,
++				   const void *src, const void *dst, size_t len, long long i)
++	ATTR_STATIC_CHECKER_NORETURN;
+ void test_assert_failed_cmp_intmax_idx(const char *code, const char *file,
+ 				       unsigned int line,
+ 				       intmax_t src, intmax_t dst,
diff --git a/CVE-2026-40014.patch b/CVE-2026-40014.patch
new file mode 100644
index 0000000..b8373bc
--- /dev/null
+++ b/CVE-2026-40014.patch
@@ -0,0 +1,144 @@
+Subject: [PATCH] lib-storage: thread - Limit References processing
+ (CVE-2026-40014)
+
+Crafted References headers made IMAP THREAD use excessive CPU and data
+stack.  References are limited to 1000 message-ids and ancestor
+traversal depth is bounded.
+
+Backport via Debian trixie 1:2.4.1+dfsg1-6+deb13u7 of:
+  https://github.com/dovecot/core/commit/113eac6cbbae1bf292e7dd1826eede3f929fe6c9
+  https://github.com/dovecot/core/commit/ad92d716328c646e4dcd4dd2aaa14bc3e422eb8d
+  https://github.com/dovecot/core/commit/f4e7474bdb5e7557ea3d985f9f27ef8d7f91ad68
+---
+ src/lib-storage/index/index-thread-links.c   | 31 ++++++++++++++++++--
+ src/lib-storage/index/index-thread-private.h |  4 +++
+ src/lib-storage/index/index-thread.c         | 25 +++++++++++-----
+ 3 files changed, 49 insertions(+), 11 deletions(-)
+
+diff --git a/src/lib-storage/index/index-thread-links.c b/src/lib-storage/index/index-thread-links.c
+index 9affb83..0ce33a0 100644
+--- a/src/lib-storage/index/index-thread-links.c
++++ b/src/lib-storage/index/index-thread-links.c
+@@ -31,12 +31,24 @@ static uint32_t thread_msg_add(struct mail_thread_cache *cache,
+ 
+ static bool thread_node_has_ancestor(struct mail_thread_cache *cache,
+ 				     const struct mail_thread_node *node,
+-				     const struct mail_thread_node *ancestor)
++				     const struct mail_thread_node *ancestor,
++				     bool *depth_exceeded_r)
+ {
++	unsigned int n = 0;
++
++	*depth_exceeded_r = FALSE;
+ 	while (node != ancestor) {
+ 		if (node->parent_idx == 0)
+ 			return FALSE;
+-
++		if (++n > MAIL_THREAD_REFERENCES_MAX) {
++			/* Ancestor chain is deeper than the per-message
++			   References limit. Multiple crafted messages can build
++			   an arbitrarily deep chain, causing O(N^2) traversals
++			   per email even with the per-message limit. Treat the
++			   link as unsafe to prevent the DoS. */
++			*depth_exceeded_r = TRUE;
++			return FALSE;
++		}
+ 		node = array_idx(&cache->thread_nodes, node->parent_idx);
+ 	}
+ 	return TRUE;
+@@ -47,6 +59,7 @@ static void thread_link_reference(struct mail_thread_cache *cache,
+ {
+ 	struct mail_thread_node *node, *parent, *child;
+ 	uint32_t idx;
++	bool depth_exceeded;
+ 
+ 	i_assert(parent_idx < cache->first_invalid_msgid_str_idx);
+ 
+@@ -62,7 +75,7 @@ static void thread_link_reference(struct mail_thread_cache *cache,
+ 	}
+ 
+ 	child->parent_link_refcount++;
+-	if (thread_node_has_ancestor(cache, parent, child)) {
++	if (thread_node_has_ancestor(cache, parent, child, &depth_exceeded)) {
+ 		if (parent == child) {
+ 			/* loops to itself - ignore */
+ 			return;
+@@ -88,6 +101,18 @@ static void thread_link_reference(struct mail_thread_cache *cache,
+ 			node->child_unref_rebuilds = TRUE;
+ 		} while (node != child);
+ 		return;
++	} else if (depth_exceeded) {
++		/* Ancestor chain exceeded the depth limit; drop this link.
++		   parent_link_refcount was already incremented above and is
++		   intentionally kept that way: mail_thread_unref_link()
++		   walks References blindly at remove time and would hit
++		   i_assert(child->parent_link_refcount > 0) on the matching
++		   edge if we hadn't bumped it here. The trade-off is that
++		   the bumped refcount can leave child->parent_idx attached
++		   to a stale parent if another message later sets a real
++		   parent edge on this child and is then expunged - threading
++		   stays wrong until some other event triggers a rebuild. */
++		return;
+ 	} else if (child->parent_idx == parent_idx) {
+ 		/* The same link already exists */
+ 		return;
+diff --git a/src/lib-storage/index/index-thread-private.h b/src/lib-storage/index/index-thread-private.h
+index ed2837b..563c3a3 100644
+--- a/src/lib-storage/index/index-thread-private.h
++++ b/src/lib-storage/index/index-thread-private.h
+@@ -22,6 +22,10 @@
+ #define MAIL_THREAD_NODE_REF_MSGID 0
+ #define MAIL_THREAD_NODE_REF_INREPLYTO 1
+ #define MAIL_THREAD_NODE_REF_REFERENCES1 2
++/* Maximum number of References: header message-IDs stored per message.
++   Prevents O(N²) CPU usage in thread_node_has_ancestor() when a single
++   crafted message contains an abnormally long reference chain. */
++#define MAIL_THREAD_REFERENCES_MAX 1000
+ 
+ struct mail_thread_node {
+ 	/* UID of the message, or 0 for dummy nodes */
+diff --git a/src/lib-storage/index/index-thread.c b/src/lib-storage/index/index-thread.c
+index 2b1ba04..a58f968 100644
+--- a/src/lib-storage/index/index-thread.c
++++ b/src/lib-storage/index/index-thread.c
+@@ -93,9 +93,11 @@ mail_strmap_rec_get_msgid(struct mail_thread_context *ctx,
+ 
+ 	/* get the nth message-id */
+ 	msgid = message_id_get_next(&msgids);
+-	if (msgid != NULL) {
+-		for (; n > 0; n--)
++	if (msgid != NULL && n > 0) {
++		for (; n > 1; n--) T_BEGIN {
+ 			msgid = message_id_get_next(&msgids);
++		} T_END;
++		msgid = message_id_get_next(&msgids);
+ 	}
+ 
+ 	if (msgid == NULL) {
+@@ -266,13 +268,20 @@ mail_thread_map_add_mail(struct mail_thread_context *ctx, struct mail *mail)
+ 	msgid = message_id_get_next(&references);
+ 	if (msgid != NULL) {
+ 		ref_index = MAIL_THREAD_NODE_REF_REFERENCES1;
++		mail_index_strmap_view_sync_add(ctx->strmap_sync,
++						mail->uid, ref_index, msgid);
+ 		do {
+-			mail_index_strmap_view_sync_add(ctx->strmap_sync,
+-							mail->uid,
+-							ref_index, msgid);
+-			ref_index++;
+-			msgid = message_id_get_next(&references);
+-		} while (msgid != NULL);
++			T_BEGIN {
++				ref_index++;
++				msgid = message_id_get_next(&references);
++				if (msgid != NULL) {
++					mail_index_strmap_view_sync_add(
++						ctx->strmap_sync, mail->uid,
++						ref_index, msgid);
++				}
++			} T_END;
++		} while (msgid != NULL &&
++			 ref_index < MAIL_THREAD_NODE_REF_REFERENCES1 + MAIL_THREAD_REFERENCES_MAX);
+ 	} else {
+ 		/* no References:, use In-Reply-To: */
+ 		if (thread_get_mail_header(mail, HDR_IN_REPLY_TO,
diff --git a/CVE-2026-40017.patch b/CVE-2026-40017.patch
new file mode 100644
index 0000000..0e32f72
--- /dev/null
+++ b/CVE-2026-40017.patch
@@ -0,0 +1,953 @@
+Subject: [PATCH] lib-index, lib-storage: Key THREAD hashes against
+ collisions (CVE-2026-40017)
+
+Message-ids and subjects chosen by a mail sender could collide in the
+THREAD hash tables (crc32 / unkeyed str_hash), making THREAD use CPU
+quadratic in the number of messages.
+
+Backport of upstream 2.4.5 (via Debian trixie 1:2.4.1+dfsg1-6+deb13u7,
+including its big-endian xxh64 fix):
+  https://github.com/dovecot/core/commit/03bd8a3d2c2783ab3bb6ab79eab9a2fc3609a6a6
+  https://github.com/dovecot/core/commit/15689cf2cd9f078cb52187568fe7086ecf0a00b2
+  https://github.com/dovecot/core/commit/1a02e74b03cbd298ca4d863735650cc13304513b
+  https://github.com/dovecot/core/commit/3612c5ed51acb43c8142713c64cad6cc4234d4d6
+  https://github.com/dovecot/core/commit/4d886f42e4524ed4df27042e33546512f3fe20cf
+  https://github.com/dovecot/core/commit/886c06d1c46eb162af29c3d4653df91c4da3ee8d
+  https://github.com/dovecot/core/commit/8d4ff69d4a40d1073946823cd0f7c1d937f51aee
+  https://github.com/dovecot/core/commit/8fedf386644e979f731854e53aa2e26d599776a5
+  https://github.com/dovecot/core/commit/a028002fcf7d3571e043206229950fed5245b4fe
+  https://github.com/dovecot/core/commit/d3e1c7fb5845f68d84aa04d941b8116048b06195
+  https://github.com/dovecot/core/commit/ec847941fd1d958b03d5578060abd294b1dc3cf8
+  https://github.com/dovecot/core/commit/fed5164930daf472fbb759096037efd5e7ee8468
+
+2.3 adaptations:
+- The strmap v2 format (keyed xxh64) is always written; upstream gates
+  it behind dovecot_storage_version, which 2.3 doesn't have.  Older
+  versions see an unknown version in a v2 file and rebuild it, so
+  downgrades are safe.
+- str_hash() is not keyed globally as upstream does: in 2.3 it also
+  backs the %H variable modifier used in on-disk paths.  Only the THREAD
+  subject hash table uses a randomly seeded xxh64 instead.
+- The config/version/storage-version commits are not needed.
+---
+ src/lib-index/mail-index-strmap.c           | 188 ++++++++++++++------
+ src/lib-index/mail-index-strmap.h           |  14 +-
+ src/lib-storage/index/index-thread-finish.c |  20 ++-
+ src/lib/Makefile.am                         |   2 +
+ src/lib/hash-method.c                       |   2 +
+ src/lib/test-hash-method.c                  |  33 ++++
+ src/lib/xxh64.c                             | 186 +++++++++++++++++++
+ src/lib/xxh64.h                             |  30 ++++
+ 8 files changed, 422 insertions(+), 53 deletions(-)
+
+diff --git a/src/lib-index/mail-index-strmap.c b/src/lib-index/mail-index-strmap.c
+index 1287c73..7339800 100644
+--- a/src/lib-index/mail-index-strmap.c
++++ b/src/lib-index/mail-index-strmap.c
+@@ -8,6 +8,8 @@
+ #include "file-lock.h"
+ #include "file-dotlock.h"
+ #include "crc32.h"
++#include "randgen.h"
++#include "xxh64.h"
+ #include "safe-mkstemp.h"
+ #include "str.h"
+ #include "mail-index-private.h"
+@@ -24,6 +26,12 @@ struct mail_index_strmap {
+ 	struct file_lock *file_lock;
+ 	struct dotlock *dotlock;
+ 	struct dotlock_settings dotlock_settings;
++
++	/* If TRUE, new files are created in v2 format (xxh64-keyed hashes).
++	   If FALSE, new files are created in v1 format (crc32). Existing
++	   files of either version are always read; on rebuild they are
++	   recreated in this preferred format. */
++	bool enable_xxh64;
+ };
+ 
+ struct mail_index_strmap_view {
+@@ -31,9 +39,17 @@ struct mail_index_strmap_view {
+ 	struct mail_index_view *view;
+ 
+ 	ARRAY_TYPE(mail_index_strmap_rec) recs;
+-	ARRAY(uint32_t) recs_crc32;
++	ARRAY(uint32_t) recs_hash;
+ 	struct hash2_table *hash;
+ 
++	/* On-disk format version that view's hash values are computed
++	   against. v1 = crc32_str_nonzero, v2 = keyed xxh64. Set from the
++	   file header when opening an existing file; otherwise from
++	   strmap->enable_xxh64. */
++	uint8_t format_version;
++	/* Per-file random IV mixed into the xxh64 hash. Unused for v1. */
++	uint64_t hash_iv;
++
+ 	mail_index_strmap_key_cmp_t *key_compare;
+ 	mail_index_strmap_rec_cmp_t *rec_compare;
+ 	mail_index_strmap_remap_t *remap_cb;
+@@ -74,7 +90,7 @@ struct mail_index_strmap_view_sync {
+ 
+ struct mail_index_strmap_hash_key {
+ 	const char *str;
+-	uint32_t crc32;
++	uint32_t hash;
+ };
+ 
+ /* number of bytes required to store one string idx */
+@@ -105,6 +121,9 @@ mail_index_strmap_init(struct mail_index *index, const char *suffix)
+ 	strmap->index = index;
+ 	strmap->path = i_strconcat(index->filepath, suffix, NULL);
+ 	strmap->fd = -1;
++	/* Older versions discard v2 files as having an unknown version and
++	   rebuild them, so v2 is always safe to write. */
++	strmap->enable_xxh64 = TRUE;
+ 
+ 	strmap->dotlock_settings = default_dotlock_settings;
+ 	strmap->dotlock_settings.use_excl_lock =
+@@ -116,7 +135,7 @@ mail_index_strmap_init(struct mail_index *index, const char *suffix)
+ 
+ static bool
+ mail_index_strmap_read_rec_next(struct mail_index_strmap_read_context *ctx,
+-				uint32_t *crc32_r);
++				uint32_t *hash_r);
+ 
+ static void
+ mail_index_strmap_set_syscall_error(struct mail_index_strmap *strmap,
+@@ -165,7 +184,7 @@ static unsigned int mail_index_strmap_hash_key(const void *_key)
+ {
+ 	const struct mail_index_strmap_hash_key *key = _key;
+ 
+-	return key->crc32;
++	return key->hash;
+ }
+ 
+ static bool
+@@ -200,7 +219,10 @@ mail_index_strmap_view_open(struct mail_index_strmap *strmap,
+ 	view->next_str_idx = 1;
+ 
+ 	i_array_init(&view->recs, 64);
+-	i_array_init(&view->recs_crc32, 64);
++	i_array_init(&view->recs_hash, 64);
++	view->format_version = strmap->enable_xxh64 ?
++		MAIL_INDEX_STRMAP_VERSION_V2 : MAIL_INDEX_STRMAP_VERSION_V1;
++	random_fill(&view->hash_iv, sizeof(view->hash_iv));
+ 	view->hash = hash2_create(0, sizeof(struct mail_index_strmap_rec),
+ 				  mail_index_strmap_hash_key,
+ 				  mail_index_strmap_hash_cmp, view);
+@@ -215,7 +237,7 @@ void mail_index_strmap_view_close(struct mail_index_strmap_view **_view)
+ 
+ 	*_view = NULL;
+ 	array_free(&view->recs);
+-	array_free(&view->recs_crc32);
++	array_free(&view->recs_hash);
+ 	hash2_destroy(&view->hash);
+ 	i_free(view);
+ }
+@@ -229,7 +251,7 @@ static void mail_index_strmap_view_reset(struct mail_index_strmap_view *view)
+ {
+ 	view->remap_cb(NULL, 0, 0, view->cb_context);
+ 	array_clear(&view->recs);
+-	array_clear(&view->recs_crc32);
++	array_clear(&view->recs_hash);
+ 	hash2_clear(view->hash);
+ 
+ 	view->last_added_uid = 0;
+@@ -253,7 +275,7 @@ static int mail_index_strmap_open(struct mail_index_strmap_view *view)
+ 	const struct mail_index_header *idx_hdr;
+ 	struct mail_index_strmap_header hdr;
+ 	const unsigned char *data;
+-	size_t size;
++	size_t size, hdr_size;
+ 	int ret;
+ 
+ 	i_assert(strmap->fd == -1);
+@@ -266,7 +288,12 @@ static int mail_index_strmap_open(struct mail_index_strmap_view *view)
+ 		return -1;
+ 	}
+ 	strmap->input = i_stream_create_fd(strmap->fd, SIZE_MAX);
+-	ret = i_stream_read_bytes(strmap->input, &data, &size, sizeof(hdr));
++
++	/* Read the smaller v1 header first; bytes 0..7 have identical
++	   layout in both formats so we can decide based on the version
++	   byte before reading the v2 tail. */
++	ret = i_stream_read_bytes(strmap->input, &data, &size,
++				  MAIL_INDEX_STRMAP_HEADER_V1_SIZE);
+ 	if (ret <= 0) {
+ 		if (ret < 0) {
+ 			mail_index_strmap_set_syscall_error(strmap, "read()");
+@@ -277,23 +304,55 @@ static int mail_index_strmap_open(struct mail_index_strmap_view *view)
+ 		}
+ 		return ret;
+ 	}
+-	memcpy(&hdr, data, sizeof(hdr));
++
++	i_zero(&hdr);
++	hdr_size = data[0] == MAIL_INDEX_STRMAP_VERSION_V2 ?
++		MAIL_INDEX_STRMAP_HEADER_V2_SIZE :
++		MAIL_INDEX_STRMAP_HEADER_V1_SIZE;
++	if (hdr_size > MAIL_INDEX_STRMAP_HEADER_V1_SIZE) {
++		ret = i_stream_read_bytes(strmap->input, &data, &size, hdr_size);
++		if (ret <= 0) {
++			if (ret < 0) {
++				mail_index_strmap_set_syscall_error(strmap, "read()");
++				mail_index_strmap_close(strmap);
++			} else {
++				mail_index_strmap_view_set_corrupted(view);
++			}
++			return ret;
++		}
++	}
++	memcpy(&hdr, data, hdr_size);
+ 
+ 	idx_hdr = mail_index_get_header(view->view);
+-	if (hdr.version != MAIL_INDEX_STRMAP_VERSION ||
+-	    hdr.uid_validity != idx_hdr->uid_validity) {
++	uint8_t compat_flags = 0;
++#ifndef WORDS_BIGENDIAN
++	if (hdr.version >= MAIL_INDEX_STRMAP_VERSION_V2)
++		compat_flags |= MAIL_INDEX_COMPAT_LITTLE_ENDIAN;
++#endif
++	if ((hdr.version != MAIL_INDEX_STRMAP_VERSION_V1 &&
++	     hdr.version != MAIL_INDEX_STRMAP_VERSION_V2) ||
++	    hdr.compat_flags != compat_flags ||
++	    hdr.uid_validity != idx_hdr->uid_validity ||
++	    (strmap->enable_xxh64 &&
++	     hdr.version < MAIL_INDEX_STRMAP_VERSION_V2)) {
+ 		/* need to rebuild. if we already had something in the strmap,
+-		   we can keep it. */
++		   we can keep it. The enable_xxh64 case forces a v1 file to
++		   be discarded so the next write creates a v2 file - we never
++		   stay on v1 once the dovecot_storage_version threshold has
++		   been reached. */
+ 		i_unlink(strmap->path);
+ 		mail_index_strmap_close(strmap);
+ 		return 0;
+ 	}
++	view->format_version = hdr.version;
++	view->hash_iv = hdr.version >= MAIL_INDEX_STRMAP_VERSION_V2 ?
++		hdr.hash_iv : 0;
+ 
+ 	/* we'll read the entire file from the beginning */
+ 	view->last_added_uid = 0;
+ 	view->last_read_uid = 0;
+ 	view->total_ref_count = 0;
+-	view->last_read_block_offset = sizeof(struct mail_index_strmap_header);
++	view->last_read_block_offset = hdr_size;
+ 	view->next_str_idx = 1;
+ 
+ 	mail_index_strmap_view_reset(view);
+@@ -413,13 +472,13 @@ mail_index_strmap_uid_exists(struct mail_index_strmap_read_context *ctx,
+ 
+ static int
+ mail_index_strmap_read_rec_first(struct mail_index_strmap_read_context *ctx,
+-				 uint32_t *crc32_r)
++				 uint32_t *hash_r)
+ {
+ 	size_t size;
+ 	uint32_t n, i, count, str_idx;
+ 	int ret;
+ 
+-	/* <uid> <n> <crc32>*count <str_idx>*count
++	/* <uid> <n> <hash>*count <str_idx>*count
+ 	   where
+ 	     n = 0 -> count=1 (only Message-ID:)
+ 	     n = 1 -> count=2 (Message-ID: + In-Reply-To:)
+@@ -428,9 +487,12 @@ mail_index_strmap_read_rec_first(struct mail_index_strmap_read_context *ctx,
+ 	if (mail_index_strmap_read_packed(ctx, &n) <= 0)
+ 		return -1;
+ 	count = n < 2 ? n + 1 : n;
++	/* check that rec_size fits */
++	if (UINT_MAX / (sizeof(ctx->rec.str_idx) + sizeof(*hash_r)) < count)
++		return -1;
+ 	ctx->view->total_ref_count += count;
+ 
+-	ctx->rec_size = count * (sizeof(ctx->rec.str_idx) + sizeof(*crc32_r));
++	ctx->rec_size = count * (sizeof(ctx->rec.str_idx) + sizeof(*hash_r));
+ 	ret = mail_index_strmap_uid_exists(ctx, ctx->rec.uid);
+ 	if (ret < 0)
+ 		return -1;
+@@ -454,10 +516,10 @@ mail_index_strmap_read_rec_first(struct mail_index_strmap_read_context *ctx,
+ 	/* everything exists. save it. FIXME: these ref_index values
+ 	   are thread index specific, perhaps something more generic
+ 	   should be used some day */
+-	ctx->end = ctx->data + count * sizeof(*crc32_r);
++	ctx->end = ctx->data + count * sizeof(*hash_r);
+ 
+ 	ctx->next_ref_index = 0;
+-	if (!mail_index_strmap_read_rec_next(ctx, crc32_r))
++	if (!mail_index_strmap_read_rec_next(ctx, hash_r))
+ 		i_unreached();
+ 	ctx->next_ref_index = n == 1 ? 1 : 2;
+ 	return 1;
+@@ -465,7 +527,7 @@ mail_index_strmap_read_rec_first(struct mail_index_strmap_read_context *ctx,
+ 
+ static bool
+ mail_index_strmap_read_rec_next(struct mail_index_strmap_read_context *ctx,
+-				uint32_t *crc32_r)
++				uint32_t *hash_r)
+ {
+ 	if (ctx->data == ctx->end) {
+ 		i_stream_skip(ctx->view->strmap->input, ctx->rec_size);
+@@ -478,7 +540,7 @@ mail_index_strmap_read_rec_next(struct mail_index_strmap_read_context *ctx,
+ 
+ 	/* read the record contents */
+ 	memcpy(&ctx->rec.str_idx, ctx->str_idx_base, sizeof(ctx->rec.str_idx));
+-	memcpy(crc32_r, ctx->data, sizeof(*crc32_r));
++	memcpy(hash_r, ctx->data, sizeof(*hash_r));
+ 
+ 	ctx->rec.ref_index = ctx->next_ref_index++;
+ 
+@@ -486,7 +548,7 @@ mail_index_strmap_read_rec_next(struct mail_index_strmap_read_context *ctx,
+ 		ctx->highest_str_idx = ctx->rec.str_idx;
+ 
+ 	/* get to the next record */
+-	ctx->data += sizeof(*crc32_r);
++	ctx->data += sizeof(*hash_r);
+ 	ctx->str_idx_base += sizeof(ctx->rec.str_idx);
+ 	return TRUE;
+ }
+@@ -547,12 +609,12 @@ strmap_read_block_init(struct mail_index_strmap_view *view,
+ 
+ static int
+ strmap_read_block_next(struct mail_index_strmap_read_context *ctx,
+-		       uint32_t *crc32_r)
++		       uint32_t *hash_r)
+ {
+ 	uint32_t uid_diff;
+ 	int ret;
+ 
+-	if (mail_index_strmap_read_rec_next(ctx, crc32_r))
++	if (mail_index_strmap_read_rec_next(ctx, hash_r))
+ 		return 1;
+ 
+ 	/* get next UID */
+@@ -565,7 +627,7 @@ strmap_read_block_next(struct mail_index_strmap_read_context *ctx,
+ 			return -1;
+ 
+ 		ctx->rec.uid += uid_diff;
+-		ret = mail_index_strmap_read_rec_first(ctx, crc32_r);
++		ret = mail_index_strmap_read_rec_first(ctx, hash_r);
+ 	} while (ret == 0);
+ 	return ret;
+ }
+@@ -635,12 +697,12 @@ strmap_view_sync_handle_conflict(struct mail_index_strmap_read_context *ctx,
+ 
+ static int
+ strmap_view_sync_block_check_conflicts(struct mail_index_strmap_read_context *ctx,
+-				       uint32_t crc32)
++				       uint32_t hash)
+ {
+ 	struct mail_index_strmap_rec *hash_rec;
+ 	struct hash2_iter iter;
+ 
+-	if (crc32 == 0) {
++	if (hash == 0) {
+ 		/* unique string - there are no conflicts */
+ 		return 0;
+ 	}
+@@ -657,9 +719,9 @@ strmap_view_sync_block_check_conflicts(struct mail_index_strmap_read_context *ct
+ 	strmap index until X has been expunged. */
+ 	i_zero(&iter);
+ 	while ((hash_rec = hash2_iterate(ctx->view->hash,
+-					 crc32, &iter)) != NULL &&
++					 hash, &iter)) != NULL &&
+ 	       hash_rec->str_idx != ctx->rec.str_idx) {
+-		/* CRC32 matches, but string index doesn't */
++		/* hash matches, but string index doesn't */
+ 		if (!strmap_view_sync_handle_conflict(ctx, hash_rec, &iter)) {
+ 			ctx->lost_expunged_uid = hash_rec->uid;
+ 			return -1;
+@@ -672,10 +734,10 @@ static int
+ mail_index_strmap_view_sync_block(struct mail_index_strmap_read_context *ctx)
+ {
+ 	struct mail_index_strmap_rec *hash_rec;
+-	uint32_t crc32, prev_uid = 0;
++	uint32_t hash, prev_uid = 0;
+ 	int ret;
+ 
+-	while ((ret = strmap_read_block_next(ctx, &crc32)) > 0) {
++	while ((ret = strmap_read_block_next(ctx, &hash)) > 0) {
+ 		if (ctx->rec.uid <= ctx->view->last_added_uid) {
+ 			if (ctx->rec.uid < ctx->view->last_added_uid ||
+ 			    prev_uid != ctx->rec.uid) {
+@@ -685,7 +747,7 @@ mail_index_strmap_view_sync_block(struct mail_index_strmap_read_context *ctx)
+ 		}
+ 		prev_uid = ctx->rec.uid;
+ 
+-		if (strmap_view_sync_block_check_conflicts(ctx, crc32) < 0) {
++		if (strmap_view_sync_block_check_conflicts(ctx, hash) < 0) {
+ 			ret = -1;
+ 			break;
+ 		}
+@@ -693,10 +755,10 @@ mail_index_strmap_view_sync_block(struct mail_index_strmap_read_context *ctx)
+ 
+ 		/* add the record to records array */
+ 		array_push_back(&ctx->view->recs, &ctx->rec);
+-		array_push_back(&ctx->view->recs_crc32, &crc32);
++		array_push_back(&ctx->view->recs_hash, &hash);
+ 
+ 		/* add a separate copy of the record to hash */
+-		hash_rec = hash2_insert_hash(ctx->view->hash, crc32);
++		hash_rec = hash2_insert_hash(ctx->view->hash, hash);
+ 		memcpy(hash_rec, &ctx->rec, sizeof(*hash_rec));
+ 	}
+ 	return strmap_read_block_deinit(ctx, ret, TRUE);
+@@ -750,6 +812,17 @@ static inline uint32_t crc32_str_nonzero(const char *str)
+ 	return value == 0 ? 1 : value;
+ }
+ 
++static inline uint32_t
++strmap_hash_str(const struct mail_index_strmap_view *view, const char *str)
++{
++	if (view->format_version < MAIL_INDEX_STRMAP_VERSION_V2)
++		return crc32_str_nonzero(str);
++
++	uint32_t value = xxh64_to_32(xxh64_data(str, strlen(str), view->hash_iv));
++	/* 0 is reserved as a sentinel meaning "unique / no hash stored" */
++	return value == 0 ? 1 : value;
++}
++
+ void mail_index_strmap_view_sync_add(struct mail_index_strmap_view_sync *sync,
+ 				     uint32_t uid, uint32_t ref_index,
+ 				     const char *key)
+@@ -764,7 +837,7 @@ void mail_index_strmap_view_sync_add(struct mail_index_strmap_view_sync *sync,
+ 		  ref_index > view->last_ref_index));
+ 
+ 	hash_key.str = key;
+-	hash_key.crc32 = crc32_str_nonzero(key);
++	hash_key.hash = strmap_hash_str(view, key);
+ 
+ 	old_rec = hash2_lookup(view->hash, &hash_key);
+ 	if (old_rec != NULL) {
+@@ -781,7 +854,7 @@ void mail_index_strmap_view_sync_add(struct mail_index_strmap_view_sync *sync,
+ 	rec->ref_index = ref_index;
+ 	rec->str_idx = str_idx;
+ 	array_push_back(&view->recs, rec);
+-	array_push_back(&view->recs_crc32, &hash_key.crc32);
++	array_push_back(&view->recs_hash, &hash_key.hash);
+ 
+ 	view->last_added_uid = uid;
+ 	view->last_ref_index = ref_index;
+@@ -802,7 +875,7 @@ void mail_index_strmap_view_sync_add_unique(struct mail_index_strmap_view_sync *
+ 	rec.ref_index = ref_index;
+ 	rec.str_idx = view->next_str_idx++;
+ 	array_push_back(&view->recs, &rec);
+-	array_append_zero(&view->recs_crc32);
++	array_append_zero(&view->recs_hash);
+ 
+ 	view->last_added_uid = uid;
+ 	view->last_ref_index = ref_index;
+@@ -820,7 +893,7 @@ static void mail_index_strmap_view_renumber(struct mail_index_strmap_view *view)
+ {
+ 	struct mail_index_strmap_read_context ctx;
+ 	struct mail_index_strmap_rec *recs, *hash_rec;
+-	uint32_t prev_uid, str_idx, *recs_crc32, *renumber_map;
++	uint32_t prev_uid, str_idx, *recs_hash, *renumber_map;
+ 	unsigned int i, dest, count, count2;
+ 	int ret;
+ 
+@@ -833,7 +906,7 @@ static void mail_index_strmap_view_renumber(struct mail_index_strmap_view *view)
+ 	renumber_map = i_new(uint32_t, view->next_str_idx);
+ 	str_idx = 0; prev_uid = 0;
+ 	recs = array_get_modifiable(&view->recs, &count);
+-	recs_crc32 = array_get_modifiable(&view->recs_crc32, &count2);
++	recs_hash = array_get_modifiable(&view->recs_hash, &count2);
+ 	i_assert(count == count2);
+ 
+ 	for (i = dest = 0; i < count; ) {
+@@ -856,13 +929,13 @@ static void mail_index_strmap_view_renumber(struct mail_index_strmap_view *view)
+ 			renumber_map[recs[i].str_idx] = ++str_idx;
+ 		if (i != dest) {
+ 			recs[dest] = recs[i];
+-			recs_crc32[dest] = recs_crc32[i];
++			recs_hash[dest] = recs_hash[i];
+ 		}
+ 		i++; dest++;
+ 	}
+ 	i_assert(renumber_map[0] == 0);
+ 	array_delete(&view->recs, dest, i-dest);
+-	array_delete(&view->recs_crc32, dest, i-dest);
++	array_delete(&view->recs_hash, dest, i-dest);
+ 	mail_index_strmap_zero_terminate(view);
+ 
+ 	/* notify caller of the renumbering */
+@@ -875,7 +948,7 @@ static void mail_index_strmap_view_renumber(struct mail_index_strmap_view *view)
+ 	hash2_clear(view->hash);
+ 	for (i = 0; i < count; i++) {
+ 		recs[i].str_idx = renumber_map[recs[i].str_idx];
+-		hash_rec = hash2_insert_hash(view->hash, recs_crc32[i]);
++		hash_rec = hash2_insert_hash(view->hash, recs_hash[i]);
+ 		memcpy(hash_rec, &recs[i], sizeof(*hash_rec));
+ 	}
+ 
+@@ -889,7 +962,7 @@ static void mail_index_strmap_write_block(struct mail_index_strmap_view *view,
+ 					  unsigned int i, uint32_t base_uid)
+ {
+ 	const struct mail_index_strmap_rec *recs;
+-	const uint32_t *crc32;
++	const uint32_t *hashes;
+ 	unsigned int j, n, count, count2, uid_rec_count;
+ 	uint32_t block_size;
+ 	uint8_t *p, packed[MAIL_INDEX_PACK_MAX_SIZE*2];
+@@ -902,7 +975,7 @@ static void mail_index_strmap_write_block(struct mail_index_strmap_view *view,
+ 
+ 	/* write records */
+ 	recs = array_get(&view->recs, &count);
+-	crc32 = array_get(&view->recs_crc32, &count2);
++	hashes = array_get(&view->recs_hash, &count2);
+ 	i_assert(count == count2);
+ 	while (i < count) {
+ 		/* @UNSAFE: <uid diff> */
+@@ -919,7 +992,7 @@ static void mail_index_strmap_write_block(struct mail_index_strmap_view *view,
+ 		}
+ 		view->total_ref_count += uid_rec_count;
+ 
+-		/* <n> <crc32>*count <str_idx>*count -
++		/* <n> <hash>*count <str_idx>*count -
+ 		   FIXME: thread index specific code */
+ 		i_assert(recs[i].ref_index == 0);
+ 		if (uid_rec_count == 1) {
+@@ -938,7 +1011,7 @@ static void mail_index_strmap_write_block(struct mail_index_strmap_view *view,
+ 		mail_index_pack_num(&p, n);
+ 		o_stream_nsend(output, packed, p-packed);
+ 		for (j = 0; j < uid_rec_count; j++)
+-			o_stream_nsend(output, &crc32[i+j], sizeof(crc32[i+j]));
++			o_stream_nsend(output, &hashes[i+j], sizeof(hashes[i+j]));
+ 		for (j = 0; j < uid_rec_count; j++) {
+ 			i_assert(j < 2 || recs[i+j].ref_index == j+1);
+ 			o_stream_nsend(output, &recs[i+j].str_idx,
+@@ -971,14 +1044,29 @@ mail_index_strmap_recreate_write(struct mail_index_strmap_view *view,
+ {
+ 	const struct mail_index_header *idx_hdr;
+ 	struct mail_index_strmap_header hdr;
++	size_t hdr_size;
+ 
+ 	idx_hdr = mail_index_get_header(view->view);
+ 
++	/* view->format_version was set either at view_open() time (from the
++	   strmap-wide enable_xxh64 preference for fresh files) or in
++	   mail_index_strmap_open() from the existing file's header. Reuse
++	   it as-is so renumber recreates preserve the file's format. */
++
+ 	/* write header */
+ 	i_zero(&hdr);
+-	hdr.version = MAIL_INDEX_STRMAP_VERSION;
++	hdr.version = view->format_version;
+ 	hdr.uid_validity = idx_hdr->uid_validity;
+-	o_stream_nsend(output, &hdr, sizeof(hdr));
++	if (view->format_version >= MAIL_INDEX_STRMAP_VERSION_V2) {
++#ifndef WORDS_BIGENDIAN
++		hdr.compat_flags |= MAIL_INDEX_COMPAT_LITTLE_ENDIAN;
++#endif
++		hdr.hash_iv = view->hash_iv;
++		hdr_size = MAIL_INDEX_STRMAP_HEADER_V2_SIZE;
++	} else {
++		hdr_size = MAIL_INDEX_STRMAP_HEADER_V1_SIZE;
++	}
++	o_stream_nsend(output, &hdr, hdr_size);
+ 
+ 	view->total_ref_count = 0;
+ 	mail_index_strmap_write_block(view, output, 0, 1);
+@@ -1095,7 +1183,7 @@ mail_index_strmap_write_append(struct mail_index_strmap_view *view)
+ 	const struct mail_index_strmap_rec *old_recs;
+ 	unsigned int i, old_count;
+ 	struct ostream *output;
+-	uint32_t crc32, next_uid;
++	uint32_t hash, next_uid;
+ 	bool full_block;
+ 	int ret;
+ 
+@@ -1134,7 +1222,7 @@ mail_index_strmap_write_append(struct mail_index_strmap_view *view)
+ 	full_block = TRUE; ret = 0;
+ 	while (i < old_count &&
+ 	       (ret = strmap_read_block_init(view, &ctx)) > 0) {
+-		while ((ret = strmap_read_block_next(&ctx, &crc32)) > 0) {
++		while ((ret = strmap_read_block_next(&ctx, &hash)) > 0) {
+ 			if (ctx.rec.uid != old_recs[i].uid ||
+ 			    ctx.rec.str_idx != old_recs[i].str_idx) {
+ 				/* mismatch */
+diff --git a/src/lib-index/mail-index-strmap.h b/src/lib-index/mail-index-strmap.h
+index c61afa6..274200c 100644
+--- a/src/lib-index/mail-index-strmap.h
++++ b/src/lib-index/mail-index-strmap.h
+@@ -7,12 +7,22 @@ struct mail_index;
+ struct mail_index_view;
+ 
+ struct mail_index_strmap_header {
+-#define MAIL_INDEX_STRMAP_VERSION 1
++/* On-disk format version. The header struct below describes version 2;
++   version 1 files use the same first 8 bytes (version + 3 unused + uid_validity)
++   without the trailing compat_flags / unused / hash_iv fields. */
++#define MAIL_INDEX_STRMAP_VERSION_V1 1
++#define MAIL_INDEX_STRMAP_VERSION_V2 2
+ 	uint8_t version;
+-	uint8_t unused[3];
++	uint8_t compat_flags; /* enum mail_index_header_compat_flags, v2+ */
++	uint8_t unused[2];
+ 
+ 	uint32_t uid_validity;
++
++	/* v2+ fields - not present on disk for v1 files. */
++	uint64_t hash_iv; /* per-file random IV mixed into the xxh64 hash */
+ };
++#define MAIL_INDEX_STRMAP_HEADER_V1_SIZE 8
++#define MAIL_INDEX_STRMAP_HEADER_V2_SIZE sizeof(struct mail_index_strmap_header)
+ 
+ struct mail_index_strmap_rec {
+ 	uint32_t uid;
+diff --git a/src/lib-storage/index/index-thread-finish.c b/src/lib-storage/index/index-thread-finish.c
+index 42326b6..f8e582f 100644
+--- a/src/lib-storage/index/index-thread-finish.c
++++ b/src/lib-storage/index/index-thread-finish.c
+@@ -3,11 +3,24 @@
+ #include "lib.h"
+ #include "array.h"
+ #include "hash.h"
++#include "randgen.h"
++#include "xxh64.h"
+ #include "imap-base-subject.h"
+ #include "mail-storage-private.h"
+ #include "index-thread-private.h"
+ 
+ 
++/* Subjects come from mail senders, so key the subject hash with a random
++   seed to keep them from choosing colliding subjects (CVE-2026-40017). */
++static uint64_t thread_subject_hash_iv;
++static bool thread_subject_hash_iv_set = FALSE;
++
++static unsigned int thread_subject_hash(const char *subject)
++{
++	return xxh64_to_32(xxh64_data(subject, strlen(subject),
++				      thread_subject_hash_iv));
++}
++
+ struct mail_thread_shadow_node {
+ 	uint32_t first_child_idx, next_sibling_idx;
+ };
+@@ -218,8 +231,13 @@ static void gather_base_subjects(struct thread_finish_context *ctx)
+ 	gather_ctx.subject_pool =
+ 		pool_alloconly_create(MEMPOOL_GROWING"base subjects",
+ 				      nearest_power(count * 20));
++	if (!thread_subject_hash_iv_set) {
++		random_fill(&thread_subject_hash_iv,
++			    sizeof(thread_subject_hash_iv));
++		thread_subject_hash_iv_set = TRUE;
++	}
+ 	hash_table_create(&gather_ctx.subject_hash, gather_ctx.subject_pool,
+-			  count * 2, str_hash, strcmp);
++			  count * 2, thread_subject_hash, strcmp);
+ 
+ 	i_array_init(&sorted_children, 64);
+ 	for (i = 0; i < count; i++) {
+diff --git a/src/lib/Makefile.am b/src/lib/Makefile.am
+index ac5c62b..928aa47 100644
+--- a/src/lib/Makefile.am
++++ b/src/lib/Makefile.am
+@@ -176,6 +176,7 @@ liblib_la_SOURCES = \
+ 	sha1.c \
+ 	sha2.c \
+ 	sha3.c \
++	xxh64.c \
+ 	sleep.c \
+ 	sort.c \
+ 	stats-dist.c \
+@@ -335,6 +336,7 @@ headers = \
+ 	sha1.h \
+ 	sha2.h \
+ 	sha3.h \
++	xxh64.h \
+ 	sleep.h \
+ 	sort.h \
+ 	stats-dist.h \
+diff --git a/src/lib/hash-method.c b/src/lib/hash-method.c
+index d7a6bed..bdeefba 100644
+--- a/src/lib/hash-method.c
++++ b/src/lib/hash-method.c
+@@ -6,6 +6,7 @@
+ #include "sha1.h"
+ #include "sha2.h"
+ #include "sha3.h"
++#include "xxh64.h"
+ #include "hash-method.h"
+ 
+ const struct hash_method *hash_method_lookup(const char *name)
+@@ -93,6 +94,7 @@ const struct hash_method *hash_methods[] = {
+ 	&hash_method_sha512,
+ 	&hash_method_sha3_256,
+ 	&hash_method_sha3_512,
++	&hash_method_xxh64,
+ 	&hash_method_size,
+ 	NULL
+ };
+diff --git a/src/lib/test-hash-method.c b/src/lib/test-hash-method.c
+index 97db7c8..f05c759 100644
+--- a/src/lib/test-hash-method.c
++++ b/src/lib/test-hash-method.c
+@@ -425,6 +425,39 @@ static void test_hash_methods_fips() {
+ 			"\x6d\xf6\x54\x5a\x1c\xe8\xba\x00",
+ 			512 / 8,
+ 		},
++		/* xxh64 reference vectors (seed=0) */
++		{ "xxh64",
++			"",
++			0,
++			1,
++			"\xef\x46\xdb\x37\x51\xd8\xe9\x99",
++			64 / 8
++		},
++		{ "xxh64",
++			"abc",
++			3,
++			1,
++			"\x44\xbc\x2c\xf5\xad\x77\x09\x99",
++			64 / 8
++		},
++		/* 62 bytes: exercises the >= 32-byte accumulator path */
++		{ "xxh64",
++			"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"
++			"ghijklmnopqrstuvwxyz0123456789",
++			62,
++			1,
++			"\xba\x76\x1a\x9a\xa8\x0e\x0d\x36",
++			64 / 8
++		},
++		/* 16 bytes × 3 rounds: exercises chunked input across the 32-byte block boundary */
++		{ "xxh64",
++			"\x00\x01\x02\x03\x04\x05\x06\x07"
++			"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
++			16,
++			3,
++			"\x32\x0d\xcd\xab\xd8\x29\x7a\x9e",
++			64 / 8
++		},
+ 	};
+ 
+ 	for(size_t i = 0; i < N_ELEMENTS(test_vectors); i++) {
+diff --git a/src/lib/xxh64.c b/src/lib/xxh64.c
+new file mode 100644
+index 0000000..4a151bd
+--- /dev/null
++++ b/src/lib/xxh64.c
+@@ -0,0 +1,186 @@
++/* Copyright (c) 2025 Dovecot authors, see the included COPYING file */
++
++/* XXHash64 - Fast non-cryptographic hash function.
++ * Based on Yann Collet's public domain XXHash64 algorithm.
++ * Reference: https://github.com/Cyan4973/xxHash/blob/dev/doc/xxhash_spec.md
++ */
++
++#include "lib.h"
++#include "xxh64.h"
++
++#include <endian.h>
++
++#define XXH64_PRIME1  UINT64_C(0x9E3779B185EBCA87)
++#define XXH64_PRIME2  UINT64_C(0xC2B2AE3D27D4EB4F)
++#define XXH64_PRIME3  UINT64_C(0x165667B19E3779F9)
++#define XXH64_PRIME4  UINT64_C(0x85EBCA77C2B27589)
++#define XXH64_PRIME5  UINT64_C(0x27D4EB2F165667C5)
++
++#define XXH64_ROTL(x, r) (((x) << (r)) | ((x) >> (64 - (r))))
++
++static inline uint64_t xxh64_read64(const void *p)
++{
++	uint64_t v;
++	memcpy(&v, p, sizeof(v));
++	return le64toh(v);  /* Convert from little-endian to host byte order */
++}
++
++static inline uint32_t xxh64_read32(const void *p)
++{
++	uint32_t v;
++	memcpy(&v, p, sizeof(v));
++	return le32toh(v);  /* Convert from little-endian to host byte order */
++}
++
++static uint64_t ATTR_UNSIGNED_WRAPS xxh64_round(uint64_t acc, uint64_t input)
++{
++	acc += input * XXH64_PRIME2;
++	acc = XXH64_ROTL(acc, 31);
++	acc *= XXH64_PRIME1;
++	return acc;
++}
++
++static uint64_t ATTR_UNSIGNED_WRAPS xxh64_merge_acc(uint64_t h64, uint64_t acc)
++{
++	acc = xxh64_round(0, acc);
++	h64 ^= acc;
++	h64 = h64 * XXH64_PRIME1 + XXH64_PRIME4;
++	return h64;
++}
++
++void ATTR_UNSIGNED_WRAPS xxh64_init(struct xxh64_context *ctx, uint64_t seed)
++{
++	ctx->seed = seed;
++	ctx->v1 = seed + XXH64_PRIME1 + XXH64_PRIME2;
++	ctx->v2 = seed + XXH64_PRIME2;
++	ctx->v3 = seed;
++	ctx->v4 = seed - XXH64_PRIME1;
++	ctx->total_len = 0;
++	ctx->buf_used = 0;
++}
++
++void ATTR_UNSIGNED_WRAPS xxh64_loop(struct xxh64_context *ctx, const void *data, size_t size)
++{
++	const unsigned char *p = data;
++	const unsigned char *end = p + size;
++
++	ctx->total_len += size;
++
++	if (ctx->buf_used + size < 32) {
++		memcpy(ctx->buf + ctx->buf_used, p, size);
++		ctx->buf_used += size;
++		return;
++	}
++
++	if (ctx->buf_used > 0) {
++		size_t fill = 32 - ctx->buf_used;
++		memcpy(ctx->buf + ctx->buf_used, p, fill);
++		p += fill;
++		ctx->v1 = xxh64_round(ctx->v1, xxh64_read64(ctx->buf));
++		ctx->v2 = xxh64_round(ctx->v2, xxh64_read64(ctx->buf + 8));
++		ctx->v3 = xxh64_round(ctx->v3, xxh64_read64(ctx->buf + 16));
++		ctx->v4 = xxh64_round(ctx->v4, xxh64_read64(ctx->buf + 24));
++		ctx->buf_used = 0;
++	}
++
++	while (p + 32 <= end) {
++		ctx->v1 = xxh64_round(ctx->v1, xxh64_read64(p));
++		ctx->v2 = xxh64_round(ctx->v2, xxh64_read64(p + 8));
++		ctx->v3 = xxh64_round(ctx->v3, xxh64_read64(p + 16));
++		ctx->v4 = xxh64_round(ctx->v4, xxh64_read64(p + 24));
++		p += 32;
++	}
++
++	if (p < end) {
++		ctx->buf_used = (unsigned int)(end - p);
++		memcpy(ctx->buf, p, ctx->buf_used);
++	}
++}
++
++uint64_t ATTR_UNSIGNED_WRAPS xxh64_result(struct xxh64_context *ctx)
++{
++	const unsigned char *p = ctx->buf;
++	const unsigned char *end = p + ctx->buf_used;
++	uint64_t h64;
++
++	if (ctx->total_len >= 32) {
++		h64 = XXH64_ROTL(ctx->v1,  1) + XXH64_ROTL(ctx->v2,  7) +
++		      XXH64_ROTL(ctx->v3, 12) + XXH64_ROTL(ctx->v4, 18);
++		h64 = xxh64_merge_acc(h64, ctx->v1);
++		h64 = xxh64_merge_acc(h64, ctx->v2);
++		h64 = xxh64_merge_acc(h64, ctx->v3);
++		h64 = xxh64_merge_acc(h64, ctx->v4);
++	} else {
++		h64 = ctx->seed + XXH64_PRIME5;
++	}
++
++	h64 += ctx->total_len;
++
++	while (p + 8 <= end) {
++		h64 ^= xxh64_round(0, xxh64_read64(p));
++		h64 = XXH64_ROTL(h64, 27) * XXH64_PRIME1 + XXH64_PRIME4;
++		p += 8;
++	}
++	if (p + 4 <= end) {
++		h64 ^= (uint64_t)xxh64_read32(p) * XXH64_PRIME1;
++		h64 = XXH64_ROTL(h64, 23) * XXH64_PRIME2 + XXH64_PRIME3;
++		p += 4;
++	}
++	while (p < end) {
++		h64 ^= (uint64_t)*p * XXH64_PRIME5;
++		h64 = XXH64_ROTL(h64, 11) * XXH64_PRIME1;
++		p++;
++	}
++
++	/* Avalanche */
++	h64 ^= h64 >> 33;
++	h64 *= XXH64_PRIME2;
++	h64 ^= h64 >> 29;
++	h64 *= XXH64_PRIME3;
++	h64 ^= h64 >> 32;
++
++	return h64;
++}
++
++uint64_t xxh64_data(const void *data, size_t size, uint64_t seed)
++{
++	struct xxh64_context ctx;
++
++	xxh64_init(&ctx, seed);
++	xxh64_loop(&ctx, data, size);
++	return xxh64_result(&ctx);
++}
++
++static void xxh64_hash_init(void *context)
++{
++	xxh64_init(context, 0);
++}
++
++static void xxh64_hash_loop(void *context, const void *data, size_t size)
++{
++	xxh64_loop(context, data, size);
++}
++
++static void xxh64_hash_result(void *context, unsigned char *digest_r)
++{
++	uint64_t hash = xxh64_result(context);
++
++	digest_r[0] = (hash >> 56) & 0xff;
++	digest_r[1] = (hash >> 48) & 0xff;
++	digest_r[2] = (hash >> 40) & 0xff;
++	digest_r[3] = (hash >> 32) & 0xff;
++	digest_r[4] = (hash >> 24) & 0xff;
++	digest_r[5] = (hash >> 16) & 0xff;
++	digest_r[6] = (hash >>  8) & 0xff;
++	digest_r[7] = (hash >>  0) & 0xff;
++}
++
++const struct hash_method hash_method_xxh64 = {
++	.name = "xxh64",
++	.block_size = 32,
++	.context_size = sizeof(struct xxh64_context),
++	.digest_size = XXH64_RESULTLEN,
++	.init = xxh64_hash_init,
++	.loop = xxh64_hash_loop,
++	.result = xxh64_hash_result,
++};
+diff --git a/src/lib/xxh64.h b/src/lib/xxh64.h
+new file mode 100644
+index 0000000..7beb4ca
+--- /dev/null
++++ b/src/lib/xxh64.h
+@@ -0,0 +1,30 @@
++#ifndef XXH64_H
++#define XXH64_H
++
++#include "hash-method.h"
++
++#define XXH64_RESULTLEN 8
++
++struct xxh64_context {
++	uint64_t seed;
++	uint64_t v1, v2, v3, v4;
++	uint64_t total_len;
++	unsigned char buf[32];
++	unsigned int buf_used;
++};
++
++void xxh64_init(struct xxh64_context *ctx, uint64_t seed);
++void xxh64_loop(struct xxh64_context *ctx, const void *data, size_t size);
++uint64_t xxh64_result(struct xxh64_context *ctx);
++
++uint64_t xxh64_data(const void *data, size_t size, uint64_t seed) ATTR_PURE;
++
++/* XOR-fold the 64-bit hash to 32 bits */
++static inline uint32_t xxh64_to_32(uint64_t hash)
++{
++	return (uint32_t)(hash ^ (hash >> 32));
++}
++
++extern const struct hash_method hash_method_xxh64;
++
++#endif
diff --git a/CVE-2026-40018.patch b/CVE-2026-40018.patch
new file mode 100644
index 0000000..68d7bea
--- /dev/null
+++ b/CVE-2026-40018.patch
@@ -0,0 +1,135 @@
+Subject: [PATCH] lib-sql: Don't escape with guessed charset while
+ disconnected (CVE-2026-40018)
+
+While the MySQL/PostgreSQL connection is down, escaping fell back to
+mysql_escape_string()/PQescapeString(), which ignore the connection
+character set and SQL mode.  The escaped value is used once the
+connection comes back, so e.g. a GBK/SJIS/BIG5 connection or
+NO_BACKSLASH_ESCAPES allowed SQL injection through a username.
+
+Upstream fixes this by making escaping fail (2.4.5 API rewrite):
+  https://github.com/dovecot/core/commit/4190313f6c4945377341017abc50e5239464627c
+  https://github.com/dovecot/core/commit/710765b420277a6abd7ce9276f7520dcbdf91567
+  https://github.com/dovecot/core/commit/7aa8c147eb15009b56c85a00c33c2c0b972c1398
+  https://github.com/dovecot/core/commit/98282f1a02d29d6fdd0b3db63ae398d0162fe7bd
+  https://github.com/dovecot/core/commit/a78c015eae67a891a0c14b5434dd1f99838ae4cc
+  https://github.com/dovecot/core/commit/c1a03b211f368d6463eaf9527da9058b0fdc44b5
+  https://github.com/dovecot/core/commit/cf4543ce91058e81daf02b5c3cf8984cc98785b3
+  https://github.com/dovecot/core/commit/d3a4d4fc2d2c84403df6eea0da1c4b7bd1d887da
+  https://github.com/dovecot/core/commit/ec4cbb78314dc46e77a2abab205969d80708d5f2
+  https://github.com/dovecot/core/commit/ff926d0c9288f343d18a3c9ec20cf1e252d52286
+That needs the 2.4 sql/var-expand API.  This narrow 2.3 fix keeps the
+escape API: without a connection only printable ASCII other than quotes,
+backslash and backtick is passed through, everything else becomes '?',
+so the value can't break out of the string literal and the lookup simply
+doesn't match.
+---
+ src/lib-sql/driver-mysql.c    | 14 ++++----------
+ src/lib-sql/driver-pgsql.c    | 16 ++++++++++------
+ src/lib-sql/sql-api-private.h |  6 ++++++
+ src/lib-sql/sql-api.c         | 18 ++++++++++++++++++
+ 4 files changed, 38 insertions(+), 16 deletions(-)
+
+diff --git a/src/lib-sql/driver-mysql.c b/src/lib-sql/driver-mysql.c
+index 2693a07..3b3cbc0 100644
+--- a/src/lib-sql/driver-mysql.c
++++ b/src/lib-sql/driver-mysql.c
+@@ -370,16 +370,10 @@ driver_mysql_escape_string(struct sql_db *_db, const char *string)
+ 	}
+ 
+ 	if (_db->state == SQL_DB_STATE_DISCONNECTED) {
+-		/* FIXME: we don't have a valid connection, so fallback
+-		   to using default escaping. the next query will most
+-		   likely fail anyway so it shouldn't matter that much
+-		   what we return here.. Anyway, this API needs
+-		   changing so that the escaping function could already
+-		   fail the query reliably. */
+-		to = t_buffer_get(len * 2 + 1);
+-		len = mysql_escape_string(to, string, len);
+-		t_buffer_alloc(len + 1);
+-		return to;
++		/* mysql_escape_string() ignores the connection character
++		   set and NO_BACKSLASH_ESCAPES, so its result isn't safe to
++		   send once a connection comes up (CVE-2026-40018). */
++		return sql_escape_string_disconnected(string);
+ 	}
+ 
+ 	to = t_buffer_get(len * 2 + 1);
+diff --git a/src/lib-sql/driver-pgsql.c b/src/lib-sql/driver-pgsql.c
+index 63188c0..1fa15bc 100644
+--- a/src/lib-sql/driver-pgsql.c
++++ b/src/lib-sql/driver-pgsql.c
+@@ -582,17 +582,21 @@ driver_pgsql_escape_string(struct sql_db *_db, const char *string)
+ 		/* try connecting again */
+ 		(void)sql_connect(&db->api);
+ 	}
+-	if (db->api.state != SQL_DB_STATE_DISCONNECTED) {
++	if (db->api.state == SQL_DB_STATE_DISCONNECTED) {
++		/* PQescapeString() guesses the encoding and
++		   standard_conforming_strings, so its result isn't safe to
++		   send once a connection comes up (CVE-2026-40018). */
++		return sql_escape_string_disconnected(string);
++	} else {
+ 		int error;
+ 
+ 		to = t_buffer_get(len * 2 + 1);
+ 		len = PQescapeStringConn(db->pg, to, string, len, &error);
+-	} else
+-#endif
+-	{
+-		to = t_buffer_get(len * 2 + 1);
+-		len = PQescapeString(to, string, len);
+ 	}
++#else
++	to = t_buffer_get(len * 2 + 1);
++	len = PQescapeString(to, string, len);
++#endif
+ 	t_buffer_alloc(len + 1);
+ 	return to;
+ }
+diff --git a/src/lib-sql/sql-api-private.h b/src/lib-sql/sql-api-private.h
+index 3026512..9325689 100644
+--- a/src/lib-sql/sql-api-private.h
++++ b/src/lib-sql/sql-api-private.h
+@@ -241,6 +241,12 @@ int driver_sqlpool_init_full(const struct sql_settings *set, const struct sql_db
+ 			     struct sql_db **db_r, const char **error_r);
+ 
+ void sql_db_set_state(struct sql_db *db, enum sql_db_state state);
++/* Escape fallback for drivers that have no connection. The real escaping
++   depends on the connection's character set and SQL mode, which aren't known
++   yet, so return only bytes that are safe inside a quoted string literal in
++   any of them. Every other byte is replaced with '?', so the lookup won't
++   match instead of letting the value break out of the literal. */
++const char *sql_escape_string_disconnected(const char *string);
+ 
+ void sql_transaction_add_query(struct sql_transaction_context *ctx, pool_t pool,
+ 			       const char *query, unsigned int *affected_rows);
+diff --git a/src/lib-sql/sql-api.c b/src/lib-sql/sql-api.c
+index cd16a5f..cd487cc 100644
+--- a/src/lib-sql/sql-api.c
++++ b/src/lib-sql/sql-api.c
+@@ -206,6 +206,24 @@ const char *sql_escape_string(struct sql_db *db, const char *string)
+ 	return db->v.escape_string(db, string);
+ }
+ 
++const char *sql_escape_string_disconnected(const char *string)
++{
++	size_t i, len = strlen(string);
++	char *dest = t_malloc_no0(len + 1);
++
++	for (i = 0; i < len; i++) {
++		unsigned char c = string[i];
++
++		if (c < 0x20 || c >= 0x7f || c == '\'' || c == '"' ||
++		    c == '\\' || c == '`')
++			dest[i] = '?';
++		else
++			dest[i] = c;
++	}
++	dest[len] = '\0';
++	return dest;
++}
++
+ const char *sql_escape_blob(struct sql_db *db,
+ 			    const unsigned char *data, size_t size)
+ {
diff --git a/CVE-2026-40203.patch b/CVE-2026-40203.patch
new file mode 100644
index 0000000..0f846af
--- /dev/null
+++ b/CVE-2026-40203.patch
@@ -0,0 +1,174 @@
+Subject: [PATCH] imap_zlib: Reset DEFLATE dictionary after each tagged
+ reply (CVE-2026-40203)
+
+With COMPRESS=DEFLATE the compression state was shared by all responses,
+so their sizes leaked whether attacker-sent mail matched other mail in
+the mailbox.  The dictionary is now reset (Z_FULL_FLUSH) after every
+tagged reply, before any later output is compressed.
+
+Backport of upstream 2.4.5 o_stream_deflate_reset_dict() and the
+client_default_send_tagline() reset:
+  https://github.com/dovecot/core/commit/34787cb86a0147d987ab821772d310faab048ba6
+  https://github.com/dovecot/core/commit/34c2a1e6b2373afcf0e11e7a1387aced82669b9d
+  https://github.com/dovecot/core/commit/c7d4e41586ac8049839529ab20f36c6fbb485112
+  https://github.com/dovecot/core/commit/dd2cd9fec90267ed9b34e93a46a26b36fbbb457f
+In 2.3 COMPRESS lives in the imap_zlib plugin, so the reset is hooked
+into send_tagline there.  The 2.4 proxy side-channel commits are not
+needed (2.3 has no imap_compress_on_proxy).
+---
+ src/lib-compression/ostream-zlib.c       | 44 ++++++++++++++++++++++--
+ src/lib-compression/ostream-zlib.h       |  7 ++++
+ src/plugins/imap-zlib/imap-zlib-plugin.c | 20 +++++++++++
+ 3 files changed, 69 insertions(+), 2 deletions(-)
+
+diff --git a/src/lib-compression/ostream-zlib.c b/src/lib-compression/ostream-zlib.c
+index 7267917..12ab1bc 100644
+--- a/src/lib-compression/ostream-zlib.c
++++ b/src/lib-compression/ostream-zlib.c
+@@ -25,6 +25,7 @@ struct zlib_ostream {
+ 
+ 	bool gz:1;
+ 	bool flushed:1;
++	bool pending_dict_reset:1;
+ };
+ 
+ int compression_get_min_level_gz(void)
+@@ -212,8 +213,14 @@ o_stream_zlib_send_flush(struct zlib_ostream *zstream, bool final)
+ 	if ((ret = o_stream_zlib_send_outbuf(zstream)) <= 0)
+ 		return ret;
+ 
+-	flush = final ? Z_FINISH :
+-		(!zstream->gz ? Z_SYNC_FLUSH : Z_NO_FLUSH);
++	if (final)
++		flush = Z_FINISH;
++	else if (zstream->gz)
++		flush = Z_NO_FLUSH;
++	else if (zstream->pending_dict_reset)
++		flush = Z_FULL_FLUSH;
++	else
++		flush = Z_SYNC_FLUSH;
+ 
+ 	i_assert(zstream->outbuf_used == 0);
+ 	do {
+@@ -243,6 +250,10 @@ o_stream_zlib_send_flush(struct zlib_ostream *zstream, bool final)
+ 		}
+ 	} while (zs->avail_out != sizeof(zstream->outbuf));
+ 
++	/* Z_FULL_FLUSH completes here; clear the request so subsequent flushes
++	   use the normal Z_SYNC_FLUSH again. */
++	zstream->pending_dict_reset = FALSE;
++
+ 	if (final) {
+ 		if (o_stream_zlib_send_gz_trailer(zstream) < 0)
+ 			return -1;
+@@ -299,6 +310,12 @@ o_stream_zlib_sendv(struct ostream_private *stream,
+ 		   parent stream. */
+ 		return ret;
+ 	}
++	if (zstream->pending_dict_reset) {
++		/* data written after o_stream_deflate_reset_dict() must not
++		   be compressed against the old dictionary */
++		if ((ret = o_stream_zlib_send_flush(zstream, FALSE)) <= 0)
++			return ret;
++	}
+ 
+ 	for (i = 0; i < iov_count; i++) {
+ 		ret = o_stream_zlib_send_chunk(zstream, iov[i].iov_base,
+@@ -389,4 +406,27 @@ struct ostream *o_stream_create_deflate(struct ostream *output, int level)
+ {
+ 	return o_stream_create_zlib(output, level, FALSE);
+ }
++
++void o_stream_deflate_reset_dict(struct ostream *_output)
++{
++	struct ostream_private *stream = _output->real_stream;
++
++	/* Traverse the ostream parent chain to find the deflate ostream.
++	   The caller may pass a rawlog-wrapped stream or the deflate stream
++	   itself; either way we find it by its sendv function pointer. */
++	while (stream != NULL) {
++		if (stream->sendv == o_stream_zlib_sendv) {
++			struct zlib_ostream *zstream =
++				container_of(stream, struct zlib_ostream, ostream);
++			i_assert(!zstream->gz);
++			zstream->pending_dict_reset = TRUE;
++			o_stream_set_flush_pending(
++				&zstream->ostream.ostream, TRUE);
++			return;
++		}
++		stream = (stream->parent != NULL) ?
++			stream->parent->real_stream : NULL;
++	}
++	/* No deflate ostream found in the chain - nothing to reset. */
++}
+ #endif
+diff --git a/src/lib-compression/ostream-zlib.h b/src/lib-compression/ostream-zlib.h
+index ac038b5..3311c50 100644
+--- a/src/lib-compression/ostream-zlib.h
++++ b/src/lib-compression/ostream-zlib.h
+@@ -7,6 +7,13 @@ struct ostream *o_stream_create_bz2(struct ostream *output, int level);
+ struct ostream *o_stream_create_lz4(struct ostream *output, int level);
+ struct ostream *o_stream_create_zstd(struct ostream *output, int level);
+ 
++/* Reset the deflate compression dictionary so that subsequent compressed
++   output cannot reference data from before this call.  Pass any ostream in
++   the chain (e.g. a rawlog wrapper); the function locates the deflate stream
++   internally.  Safe to call when compression is not active - it is a no-op
++   in that case. */
++void o_stream_deflate_reset_dict(struct ostream *output);
++
+ int compression_get_min_level_gz(void);
+ int compression_get_default_level_gz(void);
+ int compression_get_max_level_gz(void);
+diff --git a/src/plugins/imap-zlib/imap-zlib-plugin.c b/src/plugins/imap-zlib/imap-zlib-plugin.c
+index df5508b..0091300 100644
+--- a/src/plugins/imap-zlib/imap-zlib-plugin.c
++++ b/src/plugins/imap-zlib/imap-zlib-plugin.c
+@@ -7,6 +7,7 @@
+ #include "module-context.h"
+ #include "imap-commands.h"
+ #include "compression.h"
++#include "ostream-zlib.h"
+ #include "imap-zlib-plugin.h"
+ 
+ 
+@@ -20,6 +21,8 @@ struct zlib_client {
+ 
+ 	int (*next_state_export)(struct client *client, bool internal,
+ 				 buffer_t *dest, const char **error_r);
++	void (*next_send_tagline)(struct client_command_context *cmd,
++				  const char *data);
+ 	const struct compression_handler *handler;
+ };
+ 
+@@ -144,6 +147,21 @@ imap_zlib_state_export(struct client *client, bool internal,
+ 	return zclient->next_state_export(client, internal, dest, error_r);
+ }
+ 
++static void
++imap_zlib_send_tagline(struct client_command_context *cmd, const char *data)
++{
++	struct zlib_client *zclient = IMAP_ZLIB_IMAP_CONTEXT(cmd->client);
++
++	zclient->next_send_tagline(cmd, data);
++
++	/* Reset the DEFLATE dictionary after every tagged reply, so the
++	   compressed size of one command's output can't depend on data
++	   from earlier commands (CRIME-style side channel). */
++	if (zclient->handler != NULL &&
++	    strcmp(zclient->handler->name, "deflate") == 0)
++		o_stream_deflate_reset_dict(cmd->client->output);
++}
++
+ static void imap_zlib_client_created(struct client **clientp)
+ {
+ 	struct client *client = *clientp;
+@@ -157,6 +175,8 @@ static void imap_zlib_client_created(struct client **clientp)
+ 
+ 		zclient->next_state_export = (*clientp)->v.state_export;
+ 		(*clientp)->v.state_export = imap_zlib_state_export;
++		zclient->next_send_tagline = (*clientp)->v.send_tagline;
++		(*clientp)->v.send_tagline = imap_zlib_send_tagline;
+ 
+ 		client_add_capability(*clientp, "COMPRESS=DEFLATE");
+ 	}
diff --git a/CVE-2026-42391.patch b/CVE-2026-42391.patch
new file mode 100644
index 0000000..d7ef62d
--- /dev/null
+++ b/CVE-2026-42391.patch
@@ -0,0 +1,63 @@
+Subject: [PATCH] imap-login: Limit accounted ID command pairs
+ (CVE-2026-42391)
+
+An unauthenticated client could send an ID command with an unlimited
+number of field-value pairs; every pair grew the logged ID string, so
+imap-login memory and the "ID sent" log line were unbounded.  Only the
+first 30 external and 30 internal (x-*) pairs are now logged and kept in
+client_id.
+
+Rewritten for 2.3.21.1 (2.4 tracks pairs differently) after upstream:
+  https://github.com/dovecot/core/commit/277e5c880a7f6a7741e717036570812910fff7b7
+  https://github.com/dovecot/core/commit/78518c10c7aa1236c1ed1ebb2d558ce24e6bc122
+---
+ src/imap-login/imap-login-client.h |  4 ++++
+ src/imap-login/imap-login-cmd-id.c | 13 +++++++++++++
+ 2 files changed, 17 insertions(+)
+
+diff --git a/src/imap-login/imap-login-client.h b/src/imap-login/imap-login-client.h
+index 67839b7..0648cd6 100644
+--- a/src/imap-login/imap-login-client.h
++++ b/src/imap-login/imap-login-client.h
+@@ -53,6 +53,10 @@ struct imap_client_cmd_id {
+ 
+ 	char **log_keys;
+ 	string_t *log_reply;
++	/* Number of external / internal (x-*) key-value pairs accounted
++	   into client_id and log_reply so far. Bounds the pre-login
++	   accounting that grows per pair. */
++	unsigned int external_pairs_count, internal_pairs_count;
+ };
+ 
+ struct imap_client {
+diff --git a/src/imap-login/imap-login-cmd-id.c b/src/imap-login/imap-login-cmd-id.c
+index 595bc71..6fd9395 100644
+--- a/src/imap-login/imap-login-cmd-id.c
++++ b/src/imap-login/imap-login-cmd-id.c
+@@ -7,6 +7,12 @@
+ #include "imap-login-settings.h"
+ #include "imap-login-client.h"
+ 
++/* RFC 2971 says a client SHOULD NOT send more than 30 field-value pairs.
++   Allow that many of both external and internal (x-*) pairs to be logged /
++   kept in client_id. Pairs beyond this are still parsed and internal x-*
++   handlers still run, but they no longer grow the per-pair accounting. */
++#define IMAP_ID_MAX_ACCOUNTED_PAIRS 30
++
+ struct imap_id_param_handler {
+ 	const char *key;
+ 	bool key_is_prefix;
+@@ -134,6 +140,13 @@ static void cmd_id_handle_keyvalue(struct imap_client *client,
+ 
+ 	client_id_str = !client_try_update_info(client, key, value);
+ 
++	unsigned int *pairs_count = client_id_str ?
++		&client->cmd_id->external_pairs_count :
++		&client->cmd_id->internal_pairs_count;
++	if (*pairs_count >= IMAP_ID_MAX_ACCOUNTED_PAIRS)
++		return;
++	(*pairs_count)++;
++
+ 	if (client->set->imap_id_retain && client_id_str &&
+ 	    (client->common.client_id == NULL ||
+ 	     str_len(client->common.client_id) + kvlen < LOGIN_MAX_CLIENT_ID_LEN)) {
================================================================

---- gitweb:

http://git.pld-linux.org/gitweb.cgi/packages/dovecot.git/commitdiff/45c5baf96cab7033346d2640d9f1b3d9817074e8



More information about the pld-cvs-commit mailing list