git: 1ccf8075eaa8 - main - pw: remove mail file with unlinkat instead of building a path

From: Baptiste Daroussin <bapt_at_FreeBSD.org>
Date: Fri, 04 Sep 2026 14:28:58 UTC
The branch main has been updated by bapt:

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

commit 1ccf8075eaa84088ad4acb65aabb1e59c3fddd3f
Author:     Baptiste Daroussin <bapt@FreeBSD.org>
AuthorDate: 2026-09-04 14:00:07 +0000
Commit:     Baptiste Daroussin <bapt@FreeBSD.org>
CommitDate: 2026-09-04 14:28:47 +0000

    pw: remove mail file with unlinkat instead of building a path
    
    This is consistent with how at jobs and crontabs are removed.
    
    MFC After:      1 week
---
 usr.sbin/pw/pw_user.c                | 11 +++++++----
 usr.sbin/pw/tests/pw_userdel_test.sh | 16 ++++++++++++++++
 2 files changed, 23 insertions(+), 4 deletions(-)

diff --git a/usr.sbin/pw/pw_user.c b/usr.sbin/pw/pw_user.c
index 26e414831448..e8611b1323af 100644
--- a/usr.sbin/pw/pw_user.c
+++ b/usr.sbin/pw/pw_user.c
@@ -837,7 +837,6 @@ pw_user_del(int argc, char **argv, char *arg1)
 	char *name = NULL;
 	char grname[MAXLOGNAME];
 	char *nispasswd = NULL;
-	char file[MAXPATHLEN];
 	char home[MAXPATHLEN];
 	const char *cfg = NULL;
 	struct stat st;
@@ -936,7 +935,6 @@ pw_user_del(int argc, char **argv, char *arg1)
 	 * Save these for later, since contents of pwd may be
 	 * invalidated by deletion
 	 */
-	snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
 	strlcpy(home, pwd->pw_dir, sizeof(home));
 	gr = GETGRGID(pwd->pw_gid);
 	if (gr != NULL)
@@ -987,8 +985,13 @@ pw_user_del(int argc, char **argv, char *arg1)
 	    (uintmax_t)id);
 
 	/* Remove mail file */
-	if (PWALTDIR() != PWF_ALT)
-		unlinkat(conf.rootfd, file + 1, 0);
+	if (PWALTDIR() != PWF_ALT) {
+		int mfd = openat(conf.rootfd, &_PATH_MAILDIR[1], O_DIRECTORY | O_CLOEXEC);
+		if (mfd != -1) {
+			unlinkat(mfd, pwd->pw_name, 0);
+			close(mfd);
+		}
+	}
 
 	/* Remove at jobs */
 	if (PWALTDIR() != PWF_ALT && GETPWUID(id) == NULL)
diff --git a/usr.sbin/pw/tests/pw_userdel_test.sh b/usr.sbin/pw/tests/pw_userdel_test.sh
index 23c85ef185cb..1c77dd83cd89 100755
--- a/usr.sbin/pw/tests/pw_userdel_test.sh
+++ b/usr.sbin/pw/tests/pw_userdel_test.sh
@@ -127,6 +127,21 @@ delete_crontab_cleanup() {
 	rm -rf ${HOME}/var/cron/tabs
 }
 
+atf_test_case delete_mail cleanup
+delete_mail_body() {
+	populate_root_etc_skel
+
+	mkdir -p ${HOME}/var/mail
+
+	atf_check -s exit:0 ${RPW} useradd foo
+	atf_check -s exit:0 ${RPW} userdel foo
+
+	[ ! -e ${HOME}/var/mail/foo ] || atf_fail "mail file not removed"
+}
+delete_mail_cleanup() {
+	rm -rf ${HOME}/var/mail
+}
+
 atf_init_test_cases() {
 	atf_add_test_case rmuser_seperate_group
 	atf_add_test_case user_do_not_try_to_delete_root_if_user_unknown
@@ -137,4 +152,5 @@ atf_init_test_cases() {
 	atf_add_test_case home_regular_dir
 	atf_add_test_case delete_at_jobs
 	atf_add_test_case delete_crontab
+	atf_add_test_case delete_mail
 }