[elinks-dev] [PATCH] user.c (save_form_data_to_file): paranoid error handling

Alexey Tourbin at at altlinux.ru
Tue Feb 27 03:35:37 MST 2007


This is basically to fix gcc warning:
user.c: In function 'save_form_data_to_file':
user.c:243: warning: ignoring return value of 'fwrite', declared with attribute warn_unused_result

Now fwrite() return value must be checked.  But I also noticed that
temporary file is not being freed on error conditions.  And since stdio
is buffered, fclose() return value must be checked, too.

After a few --amend's I noticed the routine does not look quite the same
anymore.
---
 src/protocol/user.c |   39 +++++++++++++++++++++++++--------------
 1 files changed, 25 insertions(+), 14 deletions(-)

diff --git a/src/protocol/user.c b/src/protocol/user.c
index e00cf72..fe45968 100644
--- a/src/protocol/user.c
+++ b/src/protocol/user.c
@@ -217,32 +217,43 @@ static unsigned char *
 save_form_data_to_file(struct uri *uri)
 {
 	unsigned char *filename = get_tempdir_filename("elinks-XXXXXX");
-	int formfd;
-	FILE *formfile;
+	int fd;
+	FILE *fp;
+	unsigned char *formdata;
+	size_t len, nmemb;
 
 	if (!filename) return NULL;
 
-	formfd = safe_mkstemp(filename);
-	if (formfd < 0) {
+	fd = safe_mkstemp(filename);
+	if (fd < 0) {
 		mem_free(filename);
 		return NULL;
 	}
 
-	formfile = fdopen(formfd, "w");
-	if (!formfile) {
+	if (!uri->post) return filename;
+
+	/* Jump the content type */
+	formdata = strchr(uri->post, '\n');
+	formdata = formdata ? formdata + 1 : uri->post;
+	len = strlen(formdata);
+	if (len == 0) return filename;
+
+	fp = fdopen(fd, "w");
+	if (!fp) {
+error:		unlink(filename);
 		mem_free(filename);
-		close(formfd);
+		close(fd);
 		return NULL;
 	}
 
-	if (uri->post) {
-		/* Jump the content type */
-		unsigned char *formdata = strchr(uri->post, '\n');
-
-		formdata = formdata ? formdata + 1 : uri->post;
-		fwrite(formdata, strlen(formdata), 1, formfile);
+	nmemb = fwrite(formdata, len, 1, fp);
+	if (nmemb != 1) {
+		fclose(fp);
+		goto error;
 	}
-	fclose(formfile);
+
+	if (fclose(fp) != 0)
+		goto error;
 
 	return filename;
 }
-- 
1.5.0.1.GIT



More information about the elinks-dev mailing list