Skip to content

Commit aea56f4

Browse files
committed
listdir(): reuse a single buffer to store every file name to display
Allocating a new buffer for each entry is useless. And as these buffers are allocated on the stack, on systems with a small stack size, with many entries, the limit can easily be reached, causing a stack exhaustion and aborting the user session. Reported by Antonio Morales from the GitHub Security Lab team, thanks!
1 parent 75ae1c9 commit aea56f4

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/ls.c

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,8 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
661661
char *names;
662662
PureFileInfo *s;
663663
PureFileInfo *r;
664+
char *alloca_subdir;
665+
size_t sizeof_subdir;
664666
int d;
665667

666668
if (depth >= max_ls_depth || matches >= max_ls_files) {
@@ -690,14 +692,12 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
690692
}
691693
outputfiles(f, tls_fd);
692694
r = dir;
695+
sizeof_subdir = PATH_MAX + 1U;
696+
if ((alloca_subdir = ALLOCA(sizeof_subdir)) == NULL) {
697+
goto toomany;
698+
}
693699
while (opt_R && r != s) {
694700
if (r->name_offset != (size_t) -1 && !chdir(FI_NAME(r))) {
695-
char *alloca_subdir;
696-
const size_t sizeof_subdir = PATH_MAX + 1U;
697-
698-
if ((alloca_subdir = ALLOCA(sizeof_subdir)) == NULL) {
699-
goto toomany;
700-
}
701701
if (SNCHECK(snprintf(alloca_subdir, sizeof_subdir, "%s/%s",
702702
name, FI_NAME(r)), sizeof_subdir)) {
703703
goto nolist;
@@ -706,8 +706,8 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
706706
wrstr(f, tls_fd, alloca_subdir);
707707
wrstr(f, tls_fd, ":\r\n\r\n");
708708
listdir(depth + 1U, f, tls_fd, alloca_subdir);
709+
709710
nolist:
710-
ALLOCA_FREE(alloca_subdir);
711711
if (matches >= max_ls_files) {
712712
goto toomany;
713713
}
@@ -720,6 +720,7 @@ static void listdir(unsigned int depth, int f, void * const tls_fd,
720720
r++;
721721
}
722722
toomany:
723+
ALLOCA_FREE(alloca_subdir);
723724
free(names);
724725
free(dir);
725726
names = NULL;

0 commit comments

Comments
 (0)