[Libguestfs] [PATCH libnbd v2 7/8] lib/crypto.c: Don't use empty vector

Nir Soffer
Sun, 31 Oct 2021 15:38:56 -0000

getlogin_r() with empty buffer will always fail since the underlying
array is NULL. Reserve space before using the vector.

Signed-off-by: Nir Soffer <nsoffer at redhat.com>
---
 lib/crypto.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/lib/crypto.c b/lib/crypto.c
index 2ce4d4d..09d98fd 100644
--- a/lib/crypto.c
+++ b/lib/crypto.c
@@ -141,6 +141,12 @@ nbd_unlocked_get_tls_username (struct nbd_handle *h)
   }

   for (;;) {
+    /* Increase capacity (str.cap starts at 0) */
+    if (string_reserve (&str, 16) == -1) {
+      set_error (errno, "realloc");
+      free (str.ptr);
+      return NULL;
+    }
     if (getlogin_r (str.ptr, str.cap) == 0) {
       return str.ptr;
     }
@@ -149,12 +155,6 @@ nbd_unlocked_get_tls_username (struct nbd_handle *h)
       free (str.ptr);
       return NULL;
     }
-    /* Try again with a larger buffer. */
-    if (string_reserve (&str, 16) == -1) {
-      set_error (errno, "realloc");
-      free (str.ptr);
-      return NULL;
-    }
   }
 }

--
2.31.1