From d9d86d6a36f9133ed5b081892f9342cbdc5b8eed Mon Sep 17 00:00:00 2001
From: "Rob Swindell (on Debian Linux)" <rob@synchro.net>
Date: Mon, 11 Nov 2024 00:58:50 -0800
Subject: [PATCH] Revert the lock() change in commit 043feff8

So this change is needed or else fcntl() will fail with errno=BADF if trying
to write-lock a file that was opened read-only. Oh well. Added a comment
explaining the rationale.
---
 src/xpdev/filewrap.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/src/xpdev/filewrap.c b/src/xpdev/filewrap.c
index a13b1da4ef..459a948843 100644
--- a/src/xpdev/filewrap.c
+++ b/src/xpdev/filewrap.c
@@ -89,7 +89,14 @@ int lock(int fd, off_t pos, off_t len)
 		cmd = F_OFD_SETLK;
 	#endif
 
-	alock.l_type = F_WRLCK; /* set write lock to prevent all access */
+	// fcntl() will return EBADF if we try to set a write lock a file opened O_RDONLY
+	int	flags;
+	if((flags=fcntl(fd,F_GETFL))==-1)
+		return -1;
+	if((flags & (O_RDONLY|O_RDWR|O_WRONLY))==O_RDONLY)
+		alock.l_type = F_RDLCK; /* set read lock to prevent writes */
+	else
+		alock.l_type = F_WRLCK; /* set write lock to prevent all access */
 	alock.l_whence = L_SET;		/* SEEK_SET */
 	alock.l_start = pos;
 	alock.l_len = (int)len;
-- 
GitLab