From b0a8b8cd9c34600dda7d0503aac2dc0af3012fdc Mon Sep 17 00:00:00 2001
From: Karel Zak <kzak@redhat.com>
Date: Thu, 21 Oct 2021 16:00:01 +0200
Subject: [PATCH] logger: realloc buffer when header size changed

This is probably paranoid optimization, but when we generate a new
header we need to be sure that buffer is not smaller than calculated
maximal size of user's data.

Signed-off-by: Karel Zak <kzak@redhat.com>
---
 misc-utils/logger.c | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)

diff --git a/misc-utils/logger.c b/misc-utils/logger.c
index 23da164cd6..4511ab1141 100644
--- a/misc-utils/logger.c
+++ b/misc-utils/logger.c
@@ -979,11 +979,11 @@ static void logger_stdin(struct logger_ctl *ctl)
 	 * update header timestamps and to reflect possible priority changes.
 	 * The initial header is generated by logger_open().
 	 */
-	int has_header = 1;
 	int default_priority = ctl->pri;
 	int last_pri = default_priority;
 	size_t max_usrmsg_size = ctl->max_message_size - strlen(ctl->hdr);
-	char *const buf = xmalloc(max_usrmsg_size + 2 + 2);
+	size_t allocated_usrmsg_size = max_usrmsg_size;
+	char *buf = xmalloc(allocated_usrmsg_size + 2 + 2);
 	int pri;
 	int c;
 	size_t i;
@@ -1010,9 +1010,14 @@ static void logger_stdin(struct logger_ctl *ctl)
 				ctl->pri = default_priority;
 
 			if (ctl->pri != last_pri) {
-				has_header = 0;
-				max_usrmsg_size =
-				    ctl->max_message_size - strlen(ctl->hdr);
+				generate_syslog_header(ctl);
+				max_usrmsg_size = ctl->max_message_size - strlen(ctl->hdr);
+
+				if (max_usrmsg_size > allocated_usrmsg_size) {
+					allocated_usrmsg_size = max_usrmsg_size;
+					buf = xrealloc(buf, allocated_usrmsg_size + 2 + 2);
+				}
+
 				last_pri = ctl->pri;
 			}
 			if (c != EOF && c != '\n')
@@ -1025,12 +1030,8 @@ static void logger_stdin(struct logger_ctl *ctl)
 		}
 		buf[i] = '\0';
 
-		if (i > 0 || !ctl->skip_empty_lines) {
-			if (!has_header)
-				generate_syslog_header(ctl);
+		if (i > 0 || !ctl->skip_empty_lines)
 			write_output(ctl, buf);
-			has_header = 0;
-		}
 
 		if (c == '\n')	/* discard line terminator */
 			c = getchar();
