From a675f4b6808c695d3691ad8a1a5e004ed71312c3 Mon Sep 17 00:00:00 2001
From: Jacob Champion <pchampion@vmware.com>
Date: Tue, 15 Jun 2021 15:59:39 -0700
Subject: [PATCH 1/4] nss: move SSL_ClearSessionCache

Don't clear the cache if no context exists.
---
 src/interfaces/libpq/fe-secure-nss.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 613e7d6a1d..87e18fdde2 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -141,8 +141,6 @@ pgtls_close(PGconn *conn)
 	 * All NSS references must be cleaned up before we close out the
 	 * context.
 	 */
-	SSL_ClearSessionCache();
-
 	if (conn->pr_fd)
 	{
 		PRStatus	status;
@@ -161,6 +159,10 @@ pgtls_close(PGconn *conn)
 	if (conn->nss_context)
 	{
 		SECStatus	status;
+
+		/* The session cache must be cleared, or we'll leak references. */
+		SSL_ClearSessionCache();
+
 		status = NSS_ShutdownContext(conn->nss_context);
 
 		if (status != SECSuccess)
-- 
2.25.1

