git: fa4ac142ef99 - stable/13 - mktemp: don't double up on trailing slashes for -t paths

From: Kyle Evans <kevans_at_FreeBSD.org>
Date: Sun, 13 Nov 2022 05:38:09 UTC
The branch stable/13 has been updated by kevans:

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

commit fa4ac142ef99d271f5045595cf978ab0c406af10
Author:     Kyle Evans <kevans@FreeBSD.org>
AuthorDate: 2022-11-02 20:29:16 +0000
Commit:     Kyle Evans <kevans@FreeBSD.org>
CommitDate: 2022-11-13 05:37:36 +0000

    mktemp: don't double up on trailing slashes for -t paths
    
    This is a minor cosmetic change; re-organize slightly to set tmpdir to
    _PATH_TMP if we didn't otherwise have a tmpdir candidate, then check the
    trailing char before appending another slash.
    
    While we're here, remove some bogus whitespace and add a test case for
    this change.
    
    Obtained from:  https://github.com/apple-oss-distributions/shell_cmds
    Sponsored by:   Klara, Inc.
    
    (cherry picked from commit a6346c02f646c6b74f007c64a9b546deb06182ae)
---
 usr.bin/mktemp/mktemp.c             |  8 ++++++--
 usr.bin/mktemp/tests/mktemp_test.sh | 14 ++++++++++++++
 2 files changed, 20 insertions(+), 2 deletions(-)

diff --git a/usr.bin/mktemp/mktemp.c b/usr.bin/mktemp/mktemp.c
index 77245d2fa0d3..b61db66070dc 100644
--- a/usr.bin/mktemp/mktemp.c
+++ b/usr.bin/mktemp/mktemp.c
@@ -126,6 +126,7 @@ main(int argc, char **argv)
 
 	if (tflag) {
 		const char *envtmp;
+		size_t len;
 
 		envtmp = NULL;
 
@@ -137,7 +138,10 @@ main(int argc, char **argv)
 		if (envtmp != NULL)
 			tmpdir = envtmp;
 		if (tmpdir == NULL)
-			asprintf(&name, "%s%s.XXXXXXXX", _PATH_TMP, prefix);
+			tmpdir = _PATH_TMP;
+		len = strlen(tmpdir);
+		if (len > 0 && tmpdir[len - 1] == '/')
+			asprintf(&name, "%s%s.XXXXXXXX", tmpdir, prefix);
 		else
 			asprintf(&name, "%s/%s.XXXXXXXX", tmpdir, prefix);
 		/* if this fails, the program is in big trouble already */
@@ -148,7 +152,7 @@ main(int argc, char **argv)
 				errx(1, "cannot generate template");
 		}
 	}
-		
+
 	/* generate all requested files */
 	while (name != NULL || argc > 0) {
 		if (name == NULL) {
diff --git a/usr.bin/mktemp/tests/mktemp_test.sh b/usr.bin/mktemp/tests/mktemp_test.sh
index c424030fac4f..505c60536b34 100755
--- a/usr.bin/mktemp/tests/mktemp_test.sh
+++ b/usr.bin/mktemp/tests/mktemp_test.sh
@@ -109,10 +109,24 @@ tmpdir_pflag_noarg_body()
 	atf_check -o match:"^$tmpdir/foo\..+$" cat tmpname
 }
 
+atf_test_case tmpdir_tflag_oneslash
+tmpdir_tflag_oneslash_body()
+{
+
+	tmpdir="$PWD"
+
+	# Provided a trailing slash, we shouldn't end up with two trailing
+	# slashes.
+	atf_check -o save:tmpname \
+	    env TMPDIR="$tmpdir/" mktemp -t foo
+	atf_check -o match:"^$tmpdir/foo\..+$" cat tmpname
+}
+
 atf_init_test_cases()
 {
 	atf_add_test_case tmpdir_env
 	atf_add_test_case tmpdir_pflag
 	atf_add_test_case tmpdir_pflag_dir
 	atf_add_test_case tmpdir_pflag_noarg
+	atf_add_test_case tmpdir_tflag_oneslash
 }