From 2f21b92ca5c7629ffef16e5240124dac686da08f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Deuc=D0=B5?= <shurd@sasktel.net>
Date: Mon, 12 Jun 2023 20:05:18 -0400
Subject: [PATCH] This is exactly the sort of race condition pthread_once() is
 for.

---
 src/sbbs3/sbbscon.c | 21 ++++++++++-----------
 1 file changed, 10 insertions(+), 11 deletions(-)

diff --git a/src/sbbs3/sbbscon.c b/src/sbbs3/sbbscon.c
index a2974c0483..9083e1c1f2 100644
--- a/src/sbbs3/sbbscon.c
+++ b/src/sbbs3/sbbscon.c
@@ -316,8 +316,15 @@ static void recycle_all()
 }
 
 #ifdef __unix__
+pthread_once_t setid_mutex_once = PTHREAD_ONCE_INIT;
 static pthread_mutex_t setid_mutex;
-static BOOL setid_mutex_initialized=0;
+
+static void
+init_setuid_mutex(void)
+{
+	pthread_mutex_init(&setid_mutex, NULL);
+}
+
 /**********************************************************
 * Change uid of the calling process to the user if specified
 * **********************************************************/
@@ -334,11 +341,7 @@ static BOOL do_seteuid(BOOL to_new)
 	if(old_uid==new_uid && old_gid==new_gid)
 		return(TRUE);		/* do nothing */
 
-	if(!setid_mutex_initialized) {
-		pthread_mutex_init(&setid_mutex,NULL);
-		setid_mutex_initialized=TRUE;
-	}
-
+	pthread_once(&setid_mutex_once, init_setuid_mutex);
 	pthread_mutex_lock(&setid_mutex);
 
 	if(to_new) {
@@ -383,11 +386,7 @@ BOOL do_setuid(BOOL force)
 	if(old_uid==new_uid && old_gid==new_gid)
 		return(TRUE);		/* do nothing */
 
-	if(!setid_mutex_initialized) {
-		pthread_mutex_init(&setid_mutex,NULL);
-		setid_mutex_initialized=TRUE;
-	}
-
+	pthread_once(&setid_mutex_once, init_setuid_mutex);
 	pthread_mutex_lock(&setid_mutex);
 
 	if(getegid()!=old_gid) {
-- 
GitLab