From e84a8d53231add66f99d70da0237408218a20e08 Mon Sep 17 00:00:00 2001
From: Benno Schulenberg <bensberg@telfort.nl>
Date: Fri, 20 Aug 2021 10:28:42 +0200
Subject: [PATCH 18/34] files: check the result of fdopen(), to avoid a
 possible crash

When safe_tempfile() returns a valid filename, it should also
return a valid open stream.

This fixes https://savannah.gnu.org/bugs/?61064.

Bug existed since version 1.3.8, commit 5e068c60.
---
 src/files.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/src/files.c b/src/files.c
index 2c4af674..582965c6 100644
--- a/src/files.c
+++ b/src/files.c
@@ -1447,13 +1447,15 @@ char *safe_tempfile(FILE **stream)
 
 	fd = mkstemp(tempfile_name);
 
-	if (fd == -1) {
+	*stream = (fd > 0) ? fdopen(fd, "r+b") : NULL;
+
+	if (*stream == NULL) {
+		if (fd > 0)
+			close(fd);
 		free(tempfile_name);
 		return NULL;
 	}
 
-	*stream = fdopen(fd, "r+b");
-
 	return tempfile_name;
 }
 
-- 
2.29.3

