Blob Blame History Raw
From 049e5728ad3e8b48c521467fb7c3f98fb073ab54 Mon Sep 17 00:00:00 2001
From: Flos Qi Guo <qguo@redhat.com>
Date: Fri, 26 Nov 2021 03:32:11 +0000
Subject: [PATCH] Avoid allocating huge arrays by maxing the fd number to
 MAX_CLOSE_FD

 - Partially backport patch from rhbz#1723106

diff --git a/src/database.c b/src/database.c
index e1ec309..73da572 100644
--- a/src/database.c
+++ b/src/database.c
@@ -47,9 +47,6 @@
 #include "globals.h"
 #include "pathnames.h"
 
-#define TMAX(a,b) ((a)>(b)?(a):(b))
-#define TMIN(a,b) ((a)<(b)?(a):(b))
-
 /* size of the event structure, not counting name */
 #define EVENT_SIZE  (sizeof (struct inotify_event))
 
diff --git a/src/macros.h b/src/macros.h
index 6c7ca6d..238012a 100644
--- a/src/macros.h
+++ b/src/macros.h
@@ -58,6 +58,7 @@
 #define	MAX_UNAME	256	/* max length of username  */
 #define	ROOT_UID	0	/* don't change this, it really must be root */
 #define	ROOT_USER	"root"	/* ditto */
+#define	MAX_CLOSE_FD	10000	/* max fd num to close when spawning a child process */
 
 				/* NOTE: these correspond to DebugFlagNames,
 				 *	defined below.
@@ -126,6 +127,9 @@
 #define	LAST_DOW	7
 #define	DOW_COUNT	(LAST_DOW - FIRST_DOW + 1)
 
+#define TMAX(a,b) ((a)>(b)?(a):(b))
+#define TMIN(a,b) ((a)<(b)?(a):(b))
+
 /*
  * Because crontab/at files may be owned by their respective users we
  * take extreme care in opening them.  If the OS lacks the O_NOFOLLOW
diff --git a/src/popen.c b/src/popen.c
index aa36ff7..6262d8c 100644
--- a/src/popen.c
+++ b/src/popen.c
@@ -80,12 +80,19 @@ FILE *cron_popen(char *program, const char *type, struct passwd *pw) {
 	if (!pids) {
 		if ((fds = getdtablesize()) <= 0)
 			return (NULL);
+		if (fds > MAX_CLOSE_FD)
+			fds = MAX_CLOSE_FD; /* avoid allocating too much memory */
 		if (!(pids = (PID_T *) malloc((u_int) (fds * sizeof (PID_T)))))
 			return (NULL);
-		memset((char *) pids, 0, fds * sizeof (PID_T));
+		memset((char *) pids, 0, (u_int)(fds * sizeof (PID_T)));
 	}
 	if (pipe(pdes) < 0)
 		return (NULL);
+	if (pdes[0] >= fds || pdes[1] >= fds) {
+		(void) close(pdes[0]);
+		(void) close(pdes[1]);
+		return NULL;
+	}
 
 	/* break up string into pieces */
 	for (argc = 0, cp = program; argc < MAX_ARGS; cp = NULL)