git: 38f57faa06cf - main - cat: ensure serrno is always set

From: Warner Losh <imp_at_FreeBSD.org>
Date: Fri, 07 Jul 2023 21:56:56 UTC
The branch main has been updated by imp:

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

commit 38f57faa06cf1b96568eac6cb270c1748f3fde43
Author:     Alfonso Gregory <gfunni234@gmail.com>
AuthorDate: 2023-07-07 21:54:26 +0000
Commit:     Warner Losh <imp@FreeBSD.org>
CommitDate: 2023-07-07 21:56:35 +0000

    cat: ensure serrno is always set
    
    Set serrno to errno before the loop begins for the edge case that res0
    is immediately NULL.
    
    Reviewed by: imp
    Pull Request: https://github.com/freebsd/freebsd-src/pull/724
---
 bin/cat/cat.c | 54 +++++++++++++++++++++++++++++-------------------------
 1 file changed, 29 insertions(+), 25 deletions(-)

diff --git a/bin/cat/cat.c b/bin/cat/cat.c
index 5a1fab0c26a0..a58bbe93835e 100644
--- a/bin/cat/cat.c
+++ b/bin/cat/cat.c
@@ -436,7 +436,6 @@ udom_open(const char *path, int flags)
 	 */
 	bzero(&hints, sizeof(hints));
 	hints.ai_family = AF_LOCAL;
-	fd = -1;
 
 	if (fileargs_realpath(fa, path, rpath) == NULL)
 		return (-1);
@@ -449,6 +448,10 @@ udom_open(const char *path, int flags)
 	}
 	cap_rights_init(&rights, CAP_CONNECT, CAP_READ, CAP_WRITE,
 	    CAP_SHUTDOWN, CAP_FSTAT, CAP_FCNTL);
+
+	/* Default error if something goes wrong. */
+	serrno = EINVAL;
+
 	for (res = res0; res != NULL; res = res->ai_next) {
 		fd = socket(res->ai_family, res->ai_socktype,
 		    res->ai_protocol);
@@ -471,39 +474,40 @@ udom_open(const char *path, int flags)
 		else {
 			serrno = errno;
 			close(fd);
-			fd = -1;
 		}
 	}
 	freeaddrinfo(res0);
 
+	if (res == NULL) {
+		errno = serrno;
+		return (-1);
+	}
+
 	/*
 	 * handle the open flags by shutting down appropriate directions
 	 */
-	if (fd >= 0) {
-		switch(flags & O_ACCMODE) {
-		case O_RDONLY:
-			cap_rights_clear(&rights, CAP_WRITE);
-			if (shutdown(fd, SHUT_WR) == -1)
-				warn(NULL);
-			break;
-		case O_WRONLY:
-			cap_rights_clear(&rights, CAP_READ);
-			if (shutdown(fd, SHUT_RD) == -1)
-				warn(NULL);
-			break;
-		default:
-			break;
-		}
 
-		cap_rights_clear(&rights, CAP_CONNECT, CAP_SHUTDOWN);
-		if (caph_rights_limit(fd, &rights) < 0) {
-			serrno = errno;
-			close(fd);
-			errno = serrno;
-			return (-1);
-		}
-	} else {
+	switch (flags & O_ACCMODE) {
+	case O_RDONLY:
+		cap_rights_clear(&rights, CAP_WRITE);
+		if (shutdown(fd, SHUT_WR) == -1)
+			warn(NULL);
+		break;
+	case O_WRONLY:
+		cap_rights_clear(&rights, CAP_READ);
+		if (shutdown(fd, SHUT_RD) == -1)
+			warn(NULL);
+		break;
+	default:
+		break;
+	}
+
+	cap_rights_clear(&rights, CAP_CONNECT, CAP_SHUTDOWN);
+	if (caph_rights_limit(fd, &rights) < 0) {
+		serrno = errno;
+		close(fd);
 		errno = serrno;
+		return (-1);
 	}
 	return (fd);
 }