From 1fbf8aeb4e78b8b4afeeaafcbc97b3cbf7cfeaba Mon Sep 17 00:00:00 2001
From: Panu Matilainen <pmatilai@redhat.com>
Date: Tue, 17 Sep 2024 08:31:35 +0300
Subject: [PATCH] Enforce the same sanity checks on db add and rebuild

Conflict:adapt context; don't use RPMTAG_HEADERIMMUTABLE because
e484d99 is not merged; use int type instead of bool in validHeader()
Reference:https://github.com/rpm-software-management/rpm/commit/1fbf8aeb4e78b8b4afeeaafcbc97b3cbf7cfeaba

It doesn't make a whole lot of sense to allow inserting headers
that will get removed as invalid on the next rebuild. Funny what
oddities have survived all this time...

Fixes: #3306
---
 lib/rpmdb.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)

diff --git a/lib/rpmdb.c b/lib/rpmdb.c
index 3bf3457f3..dccdf80cd 100644
--- a/lib/rpmdb.c
+++ b/lib/rpmdb.c
@@ -2176,6 +2176,17 @@ exit:
     return (rc == 0) ? RPMRC_OK : RPMRC_FAIL;
 }
 
+static int validHeader(Header h)
+{
+    if (!(headerIsEntry(h, RPMTAG_NAME) &&
+	headerIsEntry(h, RPMTAG_VERSION) &&
+	headerIsEntry(h, RPMTAG_RELEASE)))
+    {
+	return 0;
+    }
+    return 1;
+}
+
 int rpmdbAdd(rpmdb db, Header h)
 {
     dbiIndex dbi = NULL;
@@ -2189,7 +2200,7 @@ int rpmdbAdd(rpmdb db, Header h)
 	return 0;
 
     hdrBlob = headerExport(h, &hdrLen);
-    if (hdrBlob == NULL || hdrLen == 0) {
+    if (!validHeader(h) || hdrBlob == NULL || hdrLen == 0) {
 	ret = -1;
 	goto exit;
     }
@@ -2424,10 +2435,7 @@ int rpmdbRebuild(const char * prefix, rpmts ts,
 	while ((h = rpmdbNextIterator(mi)) != NULL) {
 
 	    /* let's sanity check this record a bit, otherwise just skip it */
-	    if (!(headerIsEntry(h, RPMTAG_NAME) &&
-		headerIsEntry(h, RPMTAG_VERSION) &&
-		headerIsEntry(h, RPMTAG_RELEASE)))
-	    {
+	    if (!validHeader(h)) {
 		rpmlog(RPMLOG_ERR,
 			_("header #%u in the database is bad -- skipping.\n"),
 			rpmdbGetIteratorOffset(mi));
-- 
2.33.0

