git: f518229d5520 - main - config: fix some common issues with path() usage

From: Kyle Evans <kevans_at_FreeBSD.org>
Date: Thu, 16 Feb 2023 20:37:33 UTC
The branch main has been updated by kevans:

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

commit f518229d552012bfb1129b2bf1d18dfc89a03b58
Author:     Kyle Evans <kevans@FreeBSD.org>
AuthorDate: 2023-02-16 20:36:16 +0000
Commit:     Kyle Evans <kevans@FreeBSD.org>
CommitDate: 2023-02-16 20:36:16 +0000

    config: fix some common issues with path() usage
    
    None of the callers check that the allocation in path() failed, so let's
    check in path() and abort instead of failing.
    
    Along those lines, none of the callers seem to acknowledge that the
    returned string needs to be free()d -- let's do that as well.  There are
    a couple not addressed in this commit that will be addressed in a future
    commit by pushing the path() call down into moveifchanged() instead and
    freeing it properly there.
    
    CID:    1505271, 1505250, 1505279
    Reviewed by:    emaste, imp
---
 usr.sbin/config/main.cc      | 8 +++++++-
 usr.sbin/config/mkoptions.cc | 5 ++++-
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/usr.sbin/config/main.cc b/usr.sbin/config/main.cc
index ef24d373c8b0..f155b7c5387a 100644
--- a/usr.sbin/config/main.cc
+++ b/usr.sbin/config/main.cc
@@ -457,6 +457,8 @@ path(const char *file)
 		asprintf(&cp, "%s/%s", destdir, file);
 	else
 		cp = strdup(destdir);
+	if (cp == NULL)
+		err(EXIT_FAILURE, "malloc");
 	return (cp);
 }
 
@@ -553,6 +555,8 @@ configfile(void)
 	fo = fopen(p, "w");
 	if (!fo)
 		err(2, "%s", p);
+	free(p);
+
 	if (filebased) {
 		/* Is needed, can be used for backward compatibility. */
 		configfile_filebased(cfg);
@@ -673,8 +677,10 @@ cleanheaders(char *p)
 		if (hl)
 			continue;
 		printf("Removing stale header: %s\n", dp->d_name);
-		if (unlink(path(dp->d_name)) == -1)
+		p = path(dp->d_name);
+		if (unlink(p) == -1)
 			warn("unlink %s", dp->d_name);
+		free(p);
 	}
 	(void)closedir(dirp);
 }
diff --git a/usr.sbin/config/mkoptions.cc b/usr.sbin/config/mkoptions.cc
index f45c1026417c..134c09c2d074 100644
--- a/usr.sbin/config/mkoptions.cc
+++ b/usr.sbin/config/mkoptions.cc
@@ -294,6 +294,7 @@ tooption(char *name)
 	static char hbuf[MAXPATHLEN];
 	char nbuf[MAXPATHLEN];
 	struct opt_list *po;
+	char *fpath;
 
 	/* "cannot happen"?  the otab list should be complete.. */
 	(void)strlcpy(nbuf, "options.h", sizeof(nbuf));
@@ -305,7 +306,9 @@ tooption(char *name)
 		}
 	}
 
-	(void)strlcpy(hbuf, path(nbuf), sizeof(hbuf));
+	fpath = path(nbuf);
+	(void)strlcpy(hbuf, fpath, sizeof(hbuf));
+	free(fpath);
 	return (hbuf);
 }