From e73f3e7454ff516a12361346e04d3bcf8309ce4f Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <dgustafsson@postgresql.org>
Date: Thu, 18 Apr 2024 21:39:33 +0200
Subject: [PATCH v15 2/2] Only perform pg_strong_random init when required

The random number generator in OpenSSL 1.1.1 was redesigned to provide
fork safety by default, thus removing the need for calling RAND_poll
after forking to ensure that two processes cannot share the same state.
Since we now support 1.1.0 as the minumum version, and 1.1.0 is being
increasingly phased out from production use, only perform the RAND_poll
initialization for installations running 1.1.0 by checking the OpenSSL
version number. This saves the vast majority of installations from the
init function call overhead.

LibreSSL changed random number generator when forking OpenSSL and has
provided fork safety since version 2.0.2.

This removes the overhead of initializing the RNG for strong random
for the vast majority of users for whom it is no longer required.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/CA+hUKGKh7QrYzu=8yWEUJvXtMVm_CNWH1L_TLWCbZMwbi1XP2Q@mail.gmail.com
---
 src/port/pg_strong_random.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/src/port/pg_strong_random.c b/src/port/pg_strong_random.c
index 5f2b248425..a8efb2b188 100644
--- a/src/port/pg_strong_random.c
+++ b/src/port/pg_strong_random.c
@@ -50,17 +50,20 @@
 
 #ifdef USE_OPENSSL
 
+#include <openssl/opensslv.h>
 #include <openssl/rand.h>
 
 void
 pg_strong_random_init(void)
 {
+#if (OPENSSL_VERSION_NUMBER < 0x10101000L)
 	/*
-	 * Make sure processes do not share OpenSSL randomness state.  This is no
-	 * longer required in OpenSSL 1.1.1 and later versions, but until we drop
-	 * support for version < 1.1.1 we need to do this.
+	 * Make sure processes do not share OpenSSL randomness state.  This is not
+	 * required on LibreSSL and no longer required in OpenSSL 1.1.1 and later
+	 * versions.
 	 */
 	RAND_poll();
+#endif
 }
 
 bool
-- 
2.39.3 (Apple Git-146)

