2

I can get the real and effective UIDs of the current user, so, given some file or directory, how can I use these UIDs to check the rights, rwx, that this specific user has for accessing/modifying the file or directory?

Kusalananda
  • 333,661
slashmais
  • 551
  • So, for a given file or directory, return the permissions that applies to a specific user given their UID and/or group memberships? – Kusalananda Aug 03 '19 at 09:41
  • @Kusalananda: yes, I currently use stat to check owner against uid,s only; but groups also apply, and users with root-access. I am hoping for some fast method to check all the possibilities.. (ps thx for edits) – slashmais Aug 03 '19 at 09:48
  • 1
    See man 1 access for a starting point, but IIRC there are caveats when using it with effective UID/GID values. I can't test right now so not offering a proper answer. – Chris Davies Aug 03 '19 at 09:55
  • Another thought. Can you simply use exception handling at the point you need to make a change to the file or directory? – Chris Davies Aug 03 '19 at 10:10
  • @roaima: your reference to man access gave me the solution, thx. Calling bcanR=(faccessat(0, fullpath, R_OK, AT_EACCESS)==0); (same for W_OK & X_OK) solves my need (I think, unless there's a gotcha:) – slashmais Aug 03 '19 at 10:21
  • You could just try. However this seems like you have some bad architecture in your program. Why do you now know which of the users will own each file? – ctrl-alt-delor Aug 03 '19 at 10:29

1 Answers1

1

Thanks to roaima's comment I came up with the following:

//snip...
#include <fcntl.h>
#include <unistd.h>
...
    bool bcanR, bcanW, bcanX;
    //'fullpath' is to file or directory..
    bcanR=(faccessat(0, fullpath, R_OK, AT_EACCESS)==0);
    bcanW=(faccessat(0, fullpath, W_OK, AT_EACCESS)==0);
    bcanX=(faccessat(0, fullpath, X_OK, AT_EACCESS)==0);
...
//snip

which answers my need since it uses effective UID to check permissions.

Also based on this answer need to keep in mind that changing the permissions (using chmod) can only be done by the owner or root.

slashmais
  • 551