Checking whether a user has file permissions

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm writing an application that has to know whether a given user is allowed
to read a given file. The application will be running under a user that has
root permission. How can I query the operating system to find out what a
non-root user can see?

The app is written in Java, but I can interface to native code written in C
if necessary.

Re: Checking whether a user has file permissions

"Chris" <anon> wrote:

Quoted text here. Click to load it

I'm not sure how you would do it in Java, but in C, if you were the user,
and not root, then you could use the access() function in unistd.h.

However, given you are running this as someone other than the user in
question, you'd have to use the stat() or lstat() function in unistd.h,
check the resulting struct stat's st_uid and st_gid against the user of
interest's user id and group ids respectively, and check the file
permissions in st_mode--you need to either shift the constants (S_IREAD,
S_IWRITE, S_IEXEC defined in sys/stat.h) to the right or shift st_mode to
the left by 3 to get the group and by 6 to get other users.  Putting aside
checking user id and group ids, to check who has read access on a file, you
would do something like this:

#include <sys/stat.h>
#include <unistd.h>


  struct stat st;

  if(lstat("/some/file", &st) < 0)
    /* some error occurred */

  if(st.st_mode & S_IREAD)
    /* owner has read */
  if(st.st_mode & (S_IREAD >> 3))
    /* group has read */

  if(st.st_mode & (S_IREAD >> 6))
    /* everyone else has read */



Site Timeline