6

I have a directory that have the r permission bit:

dr-------- 3 robert robert 4096 2017-12-17 03:47 dir

This directory has two files and one directory:

file 1.txt  file 2.txt  subdir

When I run the command ls dir (from the robert account), I get an error alongside the content of the directory:

ls: cannot access dir/file 1.txt: Permission denied
ls: cannot access dir/file 2.txt: Permission denied
ls: cannot access dir/subdir: Permission denied
file 1.txt  file 2.txt  subdir

Why does ls display an error even though it is able to display the contents of directory without any problem?

Amol
  • 109

1 Answers1

14

ls calls readdir() (or getdents()) on the directory itself, which amounts to "reading" the directory. I think some Unixes implement this as actual calls to read(), as if the directory was a file. That works, since you have read permission to the directory, but it only gives the names of the files.

In addition to that, ls often wants to find the types of the files (to show different types with different colors, or to put the trailing slashes and asterisks etc. with ls -F). But finding the type generally requires calling stat() on the files themselves, and that requires access (+x) permission to the directory, in the same way actually opening the files would require. And you don't have that.

ilkkachu
  • 138,973
  • For quite some time now the on-disk format of a directory isn't any simple list of names, and read(3) of directories is forbidden. – vonbrand Feb 03 '20 at 12:43
  • @vonbrand, the kernel could still generate the results of the read() as a list of names. Perhaps only for backwards compatibility, but anyway. But I'm not sure, I seem to recall seeing that on some BSD, but I don't have any current ones to check on. – ilkkachu Feb 03 '20 at 18:09