From 2faad1230a01fee8a00aa51a9646555615885a1e Mon Sep 17 00:00:00 2001
From: Benno Schulenberg <bensberg@justemail.net>
Date: Sat, 23 Apr 2016 20:39:02 +0200
Subject: [PATCH] locking: don't try to read more bytes than the buffer can
 hold

A normal lock file is apparently 1024 bytes in size, so the second
attempt at reading bytes from the file would try to read 8192 more
bytes into a buffer that has room for only 7168 left.  According to
valgrind, the read() function doesn't like that -- and true: if for
some reason the lock file had suddenly expanded, the buffer would
overflow.

This fixes https://savannah.gnu.org/bugs/?47156.
---
 src/files.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/src/files.c b/src/files.c
index fceb7bc5..76b38ead 100644
--- a/src/files.c
+++ b/src/files.c
@@ -32,6 +32,8 @@
 #include <pwd.h>
 #include <libgen.h>
 
+#define LOCKBUFSIZE 8192
+
 /* Verify that the containing directory of the given filename exists. */
 bool has_valid_path(const char *filename)
 {
@@ -337,11 +339,11 @@ int do_lockfile(const char *filename)
 	    goto free_the_name;
 	}
 
-	lockbuf = charalloc(8192);
+	lockbuf = charalloc(LOCKBUFSIZE);
 	do {
-	    readamt = read(lockfd, &lockbuf[readtot], BUFSIZ);
+	    readamt = read(lockfd, &lockbuf[readtot], LOCKBUFSIZE - readtot);
 	    readtot += readamt;
-	} while (readtot < 8192 && readamt > 0);
+	} while (readamt > 0 && readtot < LOCKBUFSIZE);
 
 	if (readtot < 48) {
 	    statusbar(_("Error reading lock file %s: Not enough data read"),
-- 
GitLab