From 6b6ba1dc29857f5eb4c31fed3d63619fea99d5f4 Mon Sep 17 00:00:00 2001
From: Kamil Dudka <kdudka@redhat.com>
Date: Mon, 15 Oct 2018 16:03:46 +0200
Subject: [PATCH 186/557] tool_cb_hdr: handle failure of rename()

Detected by Coverity.

Closes #3140
Reviewed-by: Jay Satiro
---
 src/tool_cb_hdr.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/src/tool_cb_hdr.c b/src/tool_cb_hdr.c
index 983258c..7a7a836 100644
--- a/src/tool_cb_hdr.c
+++ b/src/tool_cb_hdr.c
@@ -132,15 +132,24 @@ size_t tool_header_cb(char *ptr, size_t size, size_t nmemb, void *userdata)
       filename = parse_filename(p, len);
       if(filename) {
         if(outs->stream) {
+          int rc;
           /* already opened and possibly written to */
           if(outs->fopened)
             fclose(outs->stream);
           outs->stream = NULL;
 
           /* rename the initial file name to the new file name */
-          rename(outs->filename, filename);
+          rc = rename(outs->filename, filename);
+          if(rc != 0) {
+            warnf(outs->config->global, "Failed to rename %s -> %s: %s\n",
+                  outs->filename, filename, strerror(errno));
+          }
           if(outs->alloc_filename)
-            free(outs->filename);
+            Curl_safefree(outs->filename);
+          if(rc != 0) {
+            free(filename);
+            return failure;
+          }
         }
         outs->is_cd_filename = TRUE;
         outs->s_isreg = TRUE;
-- 
1.8.3.1

