git: 3d7c8f088796 - main - cp: avoid a resource leak

From: Warner Losh <imp_at_FreeBSD.org>
Date: Thu, 23 May 2024 18:28:33 UTC
The branch main has been updated by imp:

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

commit 3d7c8f088796ec6ceb1d54005657dee78fd01fbe
Author:     Pierre Pronchery <pierre@freebsdfoundation.org>
AuthorDate: 2024-05-16 14:19:44 +0000
Commit:     Warner Losh <imp@FreeBSD.org>
CommitDate: 2024-05-23 18:04:43 +0000

    cp: avoid a resource leak
    
    In copy_file(), make sure the from_fd file descriptor is closed even
    when the operation failed early.
    
    Reported by:    Coverity Scan
    CID:            1545036
    Sponsored by:   The FreeBSD Foundation
    
    Reviewed by: imp, emaste
    Pull Request: https://github.com/freebsd/freebsd-src/pull/1238
---
 bin/cp/utils.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/bin/cp/utils.c b/bin/cp/utils.c
index d102fb076139..cfbb2022caaf 100644
--- a/bin/cp/utils.c
+++ b/bin/cp/utils.c
@@ -112,6 +112,8 @@ copy_file(const FTSENT *entp, int dne)
 		if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) < 0 ||
 		    fstat(from_fd, &sb) != 0) {
 			warn("%s", entp->fts_path);
+			if (from_fd >= 0)
+				(void)close(from_fd);
 			return (1);
 		}
 		/*
@@ -124,6 +126,7 @@ copy_file(const FTSENT *entp, int dne)
 		 */
 		if ((sb.st_mode & S_IFMT) != (fs->st_mode & S_IFMT)) {
 			warnx("%s: File changed", entp->fts_path);
+			(void)close(from_fd);
 			return (1);
 		}
 	}