From a4c8f14364c27508233f8a31ac4b10a4c90235a9 Mon Sep 17 00:00:00 2001
From: Bruce Momjian <bruce@momjian.us>
Date: Thu, 20 Mar 2014 11:48:31 -0400
Subject: [PATCH] libpq:  pass a memory allocation failure error up to
 PQconndefaults()

Previously user name memory allocation failures were ignored and the
default user name set to NULL.
---
 src/interfaces/libpq/fe-auth.c    | 16 +++++++++-------
 src/interfaces/libpq/fe-connect.c |  7 +++++++
 2 files changed, 16 insertions(+), 7 deletions(-)

diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c
index e10c970910..5ddd17d5df 100644
--- a/src/interfaces/libpq/fe-auth.c
+++ b/src/interfaces/libpq/fe-auth.c
@@ -741,16 +741,18 @@ pg_fe_getauthname(void)
 	 */
 	pglock_thread();
 
-	if (!name)
-	{
+	/*
+	 *	We document PQconndefaults() to return NULL for a memory allocation
+	 *	failure.  We don't have an API to return a user name lookup failure,
+	 *	so we just assume it always succeeds.
+	 */
 #ifdef WIN32
-		if (GetUserName(username, &namesize))
-			name = username;
+	if (GetUserName(username, &namesize))
+		name = username;
 #else
-		if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pw) == 0)
-			name = pw->pw_name;
+	if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pw) == 0)
+		name = pw->pw_name;
 #endif
-	}
 
 	authn = name ? strdup(name) : NULL;
 
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index da8335e680..d53c41f6a3 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -4482,6 +4482,13 @@ conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
 		if (strcmp(option->keyword, "user") == 0)
 		{
 			option->val = pg_fe_getauthname();
+			if (!option->val)
+			{
+				if (errorMessage)
+					printfPQExpBuffer(errorMessage,
+									  libpq_gettext("out of memory\n"));
+				return false;
+			}
 			continue;
 		}
 	}
-- 
2.40.0