From 160f0e908f76079ad060baccd7d9ae63acf37106 Mon Sep 17 00:00:00 2001
From: Ander Juaristi <ajuaristi@gmx.es>
Date: Wed, 9 Dec 2015 17:12:51 +0100
Subject: [PATCH] Fix Coverity issues

 * src/ftp.c (getftp): on error, close the file and attempt to remove it
   before exiting.
 * src/hsts.c (hsts_store_open): update modification time in the end.
---
 src/ftp.c  | 16 +++++++++++++---
 src/hsts.c | 16 +++++++++-------
 2 files changed, 22 insertions(+), 10 deletions(-)

diff --git a/src/ftp.c b/src/ftp.c
index 5394b713..002842ea 100644
--- a/src/ftp.c
+++ b/src/ftp.c
@@ -321,7 +321,8 @@ getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread,
 {
   int csock, dtsock, local_sock, res;
   uerr_t err = RETROK;          /* appease the compiler */
-  FILE *fp;
+  FILE *fp = NULL;
+  struct_fstat st;
   char *respline, *tms;
   const char *user, *passwd, *tmrate;
   int cmd = con->cmd;
@@ -1514,8 +1515,9 @@ Error in server response, closing control connection.\n"));
             {
               fd_close (csock);
               fd_close (dtsock);
+              err = CONERROR;
               logputs (LOG_NOTQUIET, "Could not perform SSL handshake.\n");
-              return CONERROR;
+              goto exit_error;
             }
         }
       else
@@ -1525,7 +1527,8 @@ Error in server response, closing control connection.\n"));
         {
           fd_close (csock);
           fd_close (dtsock);
-          return CONERROR;
+          err = CONERROR;
+          goto exit_error;
         }
     }
 #endif
@@ -1762,6 +1765,13 @@ Error in server response, closing control connection.\n"));
     }
   } while (try_again);
   return RETRFINISHED;
+
+exit_error:
+
+  /* If fp is a regular file, close and try to remove it */
+  if (fp && !output_stream)
+    fclose (fp);
+  return err;
 }
 
 /* A one-file FTP loop.  This is the part where FTP retrieval is
diff --git a/src/hsts.c b/src/hsts.c
index 3ddbf723..15836596 100644
--- a/src/hsts.c
+++ b/src/hsts.c
@@ -464,7 +464,7 @@ hsts_store_t
 hsts_store_open (const char *filename)
 {
   hsts_store_t store = NULL;
-  struct stat st;
+  struct_stat st;
   FILE *fp = NULL;
 
   store = xnew0 (struct hsts_store);
@@ -473,27 +473,29 @@ hsts_store_open (const char *filename)
 
   if (file_exists_p (filename))
     {
-      if (stat (filename, &st) == 0)
-        store->last_mtime = st.st_mtime;
-
       fp = fopen (filename, "r");
+
       if (!fp || !hsts_read_database (store, fp, false))
         {
           /* abort! */
           hsts_store_close (store);
           xfree (store);
+          goto out;
         }
-      if (fp)
-        fclose (fp);
+
+      if (fstat (fileno (fp), &st) == 0)
+        store->last_mtime = st.st_mtime;
+      fclose (fp);
     }
 
+out:
   return store;
 }
 
 void
 hsts_store_save (hsts_store_t store, const char *filename)
 {
-  struct stat st;
+  struct_stat st;
   FILE *fp = NULL;
   int fd = 0;