From cb6731309469d8e751c4fb9405634e2d8d82313b Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@otacoo.com>
Date: Tue, 11 Aug 2015 20:43:26 +0900
Subject: [PATCH 4/6] Refactor RandomSalt to handle salts of different lengths

---
 src/backend/postmaster/postmaster.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 000524d..c2d5b0e 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -401,7 +401,7 @@ static int	initMasks(fd_set *rmask);
 static void report_fork_failure_to_client(Port *port, int errnum);
 static CAC_state canAcceptConnections(void);
 static long PostmasterRandom(void);
-static void RandomSalt(char *md5Salt);
+static void RandomSalt(char *salt, int len);
 static void signal_child(pid_t pid, int signal);
 static bool SignalSomeChildren(int signal, int targets);
 static bool SignalUnconnectedWorkers(int signal);
@@ -2282,7 +2282,7 @@ ConnCreate(int serverFd)
 	 * after.  Else the postmaster's random sequence won't get advanced, and
 	 * all backends would end up using the same salt...
 	 */
-	RandomSalt(port->md5Salt);
+	RandomSalt(port->md5Salt, sizeof(port->md5Salt));
 
 	/*
 	 * Allocate GSSAPI specific state struct
@@ -5039,23 +5039,21 @@ StartupPacketTimeoutHandler(void)
  * RandomSalt
  */
 static void
-RandomSalt(char *md5Salt)
+RandomSalt(char *md5Salt, int len)
 {
 	long		rand;
+	int			i;
 
 	/*
 	 * We use % 255, sacrificing one possible byte value, so as to ensure that
 	 * all bits of the random() value participate in the result. While at it,
 	 * add one to avoid generating any null bytes.
 	 */
-	rand = PostmasterRandom();
-	md5Salt[0] = (rand % 255) + 1;
-	rand = PostmasterRandom();
-	md5Salt[1] = (rand % 255) + 1;
-	rand = PostmasterRandom();
-	md5Salt[2] = (rand % 255) + 1;
-	rand = PostmasterRandom();
-	md5Salt[3] = (rand % 255) + 1;
+	for (i = 0; i < len; i++)
+	{
+		rand = PostmasterRandom();
+		md5Salt[i] = (rand % 255) + 1;
+	}
 }
 
 /*
-- 
2.5.0

