[PATCH] scan-path: fix recursive directory infinite loops

varphone at qq.com varphone at qq.com
Sat Apr 15 16:09:49 CEST 2017


From: Varphone Wong <varphone at qq.com>

If there is some symbol in the scan-path that links to the . or .. or self more than one,
the program will run in infinite loops, CPU 100%.

For example:
	# cgitrc
	scan-path=$HOME/cgit-test/repos

	$ mkdir -p ~/cgit-test/repos
	$ (cd ~/cgit-test/repos && ln -s . current && ln -s . another-current)
	  or
	$ (cd ~/cgit-test/repos && ln -s .. parent && ln -s .. another-parent)
	  or
	$ ln -s ~/cgit-test/repos ~/cgit-test/repos/self
	$ ln -s ~/cgit-test/repos ~/cgit-test/repos/another-self
	$ ./cgit

Signed-off-by: Varphone Wong <varphone at qq.com>
---
 scan-tree.c | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)

diff --git a/scan-tree.c b/scan-tree.c
index 08f3f1d..b7cce8c 100644
--- a/scan-tree.c
+++ b/scan-tree.c
@@ -183,6 +183,33 @@ static void add_repo(const char *base, struct strbuf *path, repo_config_fn fn)
 	strbuf_release(&rel);
 }
 
+/* if dir link to "." or ".." or "$dir" return 1, otherwise return 0 */
+static int is_recursive_dir(const char *dir)
+{
+	ssize_t r;
+	struct stat st;
+	char *ln = NULL;
+	if (lstat(dir, &st) == -1)
+		goto not;
+
+	ln = xmalloc(st.st_size + 1);
+	r = readlink(dir, ln, st.st_size + 1);
+	if (r == -1)
+		goto not;
+
+	if (r > st.st_size)
+		goto not;
+
+	ln[r] = '\0';
+	if (strcmp(ln, ".") == 0 ||
+	    strcmp(ln, "..") == 0 ||
+	    strcmp(ln, dir) == 0)
+		return 1;
+not:
+	free(ln);
+	return 0;
+}
+
 static void scan_path(const char *base, const char *path, repo_config_fn fn)
 {
 	DIR *dir = opendir(path);
@@ -228,7 +255,7 @@ static void scan_path(const char *base, const char *path, repo_config_fn fn)
 				pathbuf.buf, strerror(errno), errno);
 			continue;
 		}
-		if (S_ISDIR(st.st_mode))
+		if (S_ISDIR(st.st_mode) && !is_recursive_dir(pathbuf.buf))
 			scan_path(base, pathbuf.buf, fn);
 	}
 end:
-- 
2.7.4



More information about the CGit mailing list