Re: [PATCH] user.c (save_form_data_to_file): paranoid error handling

Laurent MONIN <[email protected]>
Newsgroups gmane.comp.web.links
Message-ID <[email protected]>
On Tue, 27 Feb 2007 13:35:37 +0300
Alexey Tourbin <[email protected]> wrote:

> 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
> 

Thanks, committed in master branch.

Kind regards,

--

Zas
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.