From 63fb41b9aa654a6450a4c2f08d8bf204a5916b08 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <jelte.fennema@microsoft.com>
Date: Fri, 26 Jan 2024 17:01:28 +0100
Subject: [PATCH v26 2/5] libpq: Add pq_release_conn_hosts function

In a follow up PR we'll need to free this connhost field in a function
defined in fe-cancel.c

So this extracts the logic to a dedicated extern function.
---
 src/interfaces/libpq/fe-connect.c | 39 ++++++++++++++++++++-----------
 src/interfaces/libpq/libpq-int.h  |  1 +
 2 files changed, 27 insertions(+), 13 deletions(-)

diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index 5357b0a9d22..0622fe32253 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -4395,19 +4395,7 @@ freePGconn(PGconn *conn)
 		free(conn->events[i].name);
 	}
 
-	/* clean up pg_conn_host structures */
-	for (int i = 0; i < conn->nconnhost; ++i)
-	{
-		free(conn->connhost[i].host);
-		free(conn->connhost[i].hostaddr);
-		free(conn->connhost[i].port);
-		if (conn->connhost[i].password != NULL)
-		{
-			explicit_bzero(conn->connhost[i].password, strlen(conn->connhost[i].password));
-			free(conn->connhost[i].password);
-		}
-	}
-	free(conn->connhost);
+	pq_release_conn_hosts(conn);
 
 	free(conn->client_encoding_initial);
 	free(conn->events);
@@ -4526,6 +4514,31 @@ release_conn_addrinfo(PGconn *conn)
 	}
 }
 
+/*
+ * pq_release_conn_hosts
+ *	 - Free the host list in the PGconn.
+ */
+void
+pq_release_conn_hosts(PGconn *conn)
+{
+	if (conn->connhost)
+	{
+		for (int i = 0; i < conn->nconnhost; ++i)
+		{
+			free(conn->connhost[i].host);
+			free(conn->connhost[i].hostaddr);
+			free(conn->connhost[i].port);
+			if (conn->connhost[i].password != NULL)
+			{
+				explicit_bzero(conn->connhost[i].password, strlen(conn->connhost[i].password));
+				free(conn->connhost[i].password);
+			}
+		}
+		free(conn->connhost);
+	}
+}
+
+
 /*
  * sendTerminateConn
  *	 - Send a terminate message to backend.
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 66b77e75e18..a0da7356584 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -680,6 +680,7 @@ extern int	pqPacketSend(PGconn *conn, char pack_type,
 extern bool pqGetHomeDirectory(char *buf, int bufsize);
 extern bool pq_parse_int_param(const char *value, int *result, PGconn *conn,
 							   const char *context);
+extern void pq_release_conn_hosts(PGconn *conn);
 
 extern pgthreadlock_t pg_g_threadlock;
 
-- 
2.34.1

