From 0644e4e79c841b03d606fc8bb035ec311f4bfb17 Mon Sep 17 00:00:00 2001
From: Michael Schroeder <mls@suse.de>
Date: Tue, 1 Dec 2020 13:42:45 +0100
Subject: [PATCH] Allow database probing if _db_backend is not set

There is no harm in allowing read access in this case. We still
error out in the database rebuild case, just to be on the safe
side. We now have the following logic:

_db_backend unset:
  * error out for rebuilddb or read-write access
  * use detected backend and print a debug message
_db_backend unknown:
  * error out for rebuilddb or read-write access
  * use detected backend and print a warning message
_db_backend set:
  * use detected backend and print a warning message if it
    does not match the configured backend
---
 lib/backend/dbi.c | 24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)

diff --git a/lib/backend/dbi.c b/lib/backend/dbi.c
index 8fbe5f374..809d013bf 100644
--- a/lib/backend/dbi.c
+++ b/lib/backend/dbi.c
@@ -5,6 +5,7 @@
 #include "system.h"
 
 #include <stdlib.h>
+#include <fcntl.h>
 #include <rpm/rpmtypes.h>
 #include <rpm/rpmstring.h>
 #include <rpm/rpmmacro.h>
@@ -77,7 +78,7 @@ dbDetectBackend(rpmdb rdb)
 	}
     }
 
-    if (!cfg) {
+    if (!cfg && ((rdb->db_mode & O_ACCMODE) != O_RDONLY || (rdb->db_flags & RPMDB_FLAG_REBUILD) != 0)) {
 	rpmlog(RPMLOG_WARNING, _("invalid %%_db_backend: %s\n"), db_backend);
 	goto exit;
     }
@@ -93,15 +94,20 @@ dbDetectBackend(rpmdb rdb)
 
 	/* On-disk database differs from configuration */
 	if (ondisk && ondisk != cfg) {
-	    if (rdb->db_flags & RPMDB_FLAG_REBUILD) {
-		rpmlog(RPMLOG_WARNING,
-			_("Converting database from %s to %s backend\n"),
-			ondisk->name, cfg->name);
+	    if (*db_backend) {
+		if (rdb->db_flags & RPMDB_FLAG_REBUILD) {
+		    rpmlog(RPMLOG_WARNING,
+			    _("Converting database from %s to %s backend\n"),
+			    ondisk->name, db_backend);
+		} else {
+		    rpmlog(RPMLOG_WARNING,
+			_("Found %s %s database while attempting %s backend: "
+			"using %s backend.\n"),
+			ondisk->name, ondisk->path, db_backend, ondisk->name);
+		}
 	    } else {
-		rpmlog(RPMLOG_WARNING,
-		    _("Found %s %s database while attempting %s backend: "
-		    "using %s backend.\n"),
-		    ondisk->name, ondisk->path, db_backend, ondisk->name);
+		rpmlog(RPMLOG_DEBUG, "Found %s %s database: using %s backend.\n",
+		    ondisk->name, ondisk->path, ondisk->name);
 	    }
 	    rdb->db_ops = ondisk;
 	}
-- 
2.27.0

