git: f7398d2d0ab6 - stable/13 - logger(1): MFC: fix timestamps in case of long run

From: Eugene Grosbein <eugen_at_FreeBSD.org>
Date: Thu, 04 May 2023 05:42:39 UTC
The branch stable/13 has been updated by eugen:

URL: https://cgit.FreeBSD.org/src/commit/?id=f7398d2d0ab6b22d88296f7daff48ed3fe74aa56

commit f7398d2d0ab6b22d88296f7daff48ed3fe74aa56
Author:     Eugene Grosbein <eugen@FreeBSD.org>
AuthorDate: 2023-04-27 16:43:16 +0000
Commit:     Eugene Grosbein <eugen@FreeBSD.org>
CommitDate: 2023-05-04 05:41:55 +0000

    logger(1): MFC: fix timestamps in case of long run
    
    An example:
    
    ( echo test; sleep 2; echo test2 ) | logger -h /var/run/log
    
    Before fix, logger assigned same timestamp to both records.
    
    Fixes:          65547fb33db901a9f352aacb0ed45ce68b0bd275
    Reported by:    Vadim Goncharov
    
    (cherry picked from commit 83fd35b3f3fa580d2b99874abd1f67ee61dcb659)
---
 usr.bin/logger/logger.c | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/usr.bin/logger/logger.c b/usr.bin/logger/logger.c
index 1ce8d81db6f6..32fda60717d6 100644
--- a/usr.bin/logger/logger.c
+++ b/usr.bin/logger/logger.c
@@ -198,22 +198,23 @@ main(int argc, char *argv[])
 	if (host == NULL)
 		cap_openlog(capsyslog, tag, logflags, 0);
 
-	(void )time(&now);
-	(void )ctime_r(&now, tbuf);
-	tbuf[19] = '\0';
-	timestamp = tbuf + 4;
-
 	if (hostname == NULL) {
 		hostname = hbuf;
 		(void )gethostname(hbuf, MAXHOSTNAMELEN);
 		*strchrnul(hostname, '.') = '\0';
 	}
 
+	timestamp = tbuf + 4;
+
 	/* log input line if appropriate */
 	if (argc > 0) {
 		char *p, *endp;
 		size_t len;
 
+		(void )time(&now);
+		(void )ctime_r(&now, tbuf);
+		tbuf[19] = '\0';
+
 		for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
 			len = strlen(*argv);
 			if (p + len > endp && p > buf) {
@@ -235,9 +236,14 @@ main(int argc, char *argv[])
 			logmessage(pri, timestamp, hostname, tag, socks, nsock,
 			    buf);
 	} else
-		while (fgets(buf, sizeof(buf), stdin) != NULL)
+		while (fgets(buf, sizeof(buf), stdin) != NULL) {
+			(void )time(&now);
+			(void )ctime_r(&now, tbuf);
+			tbuf[19] = '\0';
+
 			logmessage(pri, timestamp, hostname, tag, socks, nsock,
 			    buf);
+		}
 	exit(0);
 }