views:

282

answers:

3

I can use stat() to figure out what permissions the owner, group, or others have and I can use geteuid() and getpwuid() to get the user name of the process. I'm not quite sure how to get the groups a user belongs to without a system call though.

Even knowing how to get the groups, it seems like a lot of work to integrate all of this information. Is there an easier way?

+7  A: 

The access() POSIX function can check the permissions without opening it. However, it needs to a syscall.

The access() function shall check the file named by the pathname pointed to by the path argument for accessibility according to the bit pattern contained in amode, using the real user ID in place of the effective user ID and the real group ID in place of the effective group ID.

For example:

access("/etc/passwd",W_OK)

checks if you have write access to the passwd file. With R_OK, read permissions are checked.

The eaccess() function (euidaccess is a synonym) uses the effective user and group id. While eaccess seems to be widely supported, as far as I know it is not part of the POSIX standard.

dmeister
eaccess is non-standard, but POSIX.1-2008 added faccessat, which can be used with the flag AT_EACCESS to perform the access check using the effective ids. However this is not yet widely supported. http://www.opengroup.org/onlinepubs/9699919799/functions/faccessat.html
mark4o
+2  A: 

unistd.h defines an access() function,

int access(const char *path, int amode);

where path is your filename and amode is a bitwise inclusive OR of access permissions to check against.

R_OK, W_OK, and X_OK hold mode values for checking read, write, and search/execute permissions respectively.

int readable, readwritable;

//checking for read access
readable = access("/usr/bin/file", R_OK);

//checking for read and write access
readwritable = access("/usr/bin/file", R_OK|W_OK);

You can find a full description of access() in the unix man pages.

keparo
+1  A: 

The acccess() checks the file name pointed by the path argument. The drawback here is each file permission has to be chekced individually using the flags below. R_OK Test for read permission. W_OK Test for write permission. X_OK Test for execute or search permission. F_OK Check existence of file

Sachin Chourasiya