From 15c7e02e4a5fe127bd55bce2b9aa63a5da8eb228 Mon Sep 17 00:00:00 2001
From: Oswald Buddenhagen <ossi@users.sf.net>
Date: Sun, 24 Nov 2024 13:11:32 +0100
Subject: [PATCH] accept zero-sized messages from IMAP

while such a thing is rather pointless, completely empty messages are
not forbidden. consequently, we should be able to deal with them, and
above all not crash.

Upstream-Status: Backport [https://sourceforge.net/p/isync/isync/ci/15c7e02e4a5fe127bd55bce2b9aa63a5da8eb228/]
---
 src/drv_imap.c | 5 ++++-
 src/socket.c   | 1 -
 src/util.c     | 5 +++++
 3 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/drv_imap.c b/src/drv_imap.c
index 1280e3c..b0be1fd 100644
--- ./src/drv_imap.c
+++ ./src/drv_imap.c
@@ -780,6 +780,8 @@ parse_imap_list( imap_store_t *ctx, char **sp, parse_list_state_t *sts )
 				if (sts->callback->atom( ctx, NULL, bytes, AtomChunkedLiteral ) != LIST_OK)
 					goto bail;
 				sts->in_literal = ChunkedLiteral;
+				if (!bytes)
+					goto nobytes;
 				sts->big_literal = 1;
 			  get_chunked:
 				n = 1;
@@ -806,7 +808,7 @@ parse_imap_list( imap_store_t *ctx, char **sp, parse_list_state_t *sts )
 				} else if (DFlags & DEBUG_NET_ALL) {
 					printf( "%s=========\n", ctx->label );
 					fwrite( p, n, 1, stdout );
-					if (p[n - 1] != '\n')
+					if (n && p[n - 1] != '\n')
 						fputs( "\n(no-nl) ", stdout );
 					printf( "%s=========\n", ctx->label );
 				} else {
@@ -819,6 +821,7 @@ parse_imap_list( imap_store_t *ctx, char **sp, parse_list_state_t *sts )
 			bytes -= n;
 			if (bytes > 0)
 				goto postpone;
+		  nobytes:
 			if (sts->in_literal == ChunkedLiteral && sts->callback->atom( ctx, NULL, 0, AtomLiteral ) != LIST_OK)
 				goto bail;
 		  getline:
diff --git a/src/socket.c b/src/socket.c
index afd3f18..1ef0e95 100644
--- ./src/socket.c
+++ ./src/socket.c
@@ -952,7 +952,6 @@ socket_expect_bytes( conn_t *conn, uint len )
 char *
 socket_read( conn_t *conn, uint min_len, uint max_len, uint *out_len )
 {
-	assert( min_len > 0 );
 	assert( min_len <= sizeof(conn->buf) );
 	assert( min_len <= max_len );
 
diff --git a/src/util.c b/src/util.c
index e697cfb..121ab0a 100644
--- ./src/util.c
+++ ./src/util.c
@@ -637,6 +637,11 @@ nfmalloc( size_t sz )
 {
 	void *ret;
 
+#ifndef __GLIBC__
+	// The C standard allows NULL returns for zero-sized allocations.
+	if (!sz)
+		sz = 1;
+#endif
 	if (!(ret = malloc( sz )))
 		oom();
 	return ret;
-- 
2.47.1

