faccessat.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Test for access to file, relative to open directory. Linux version.
  2. Copyright (C) 2006-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <stddef.h>
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <sys/types.h>
  22. #include <alloca.h>
  23. #include <sysdep.h>
  24. int
  25. faccessat (int fd, const char *file, int mode, int flag)
  26. {
  27. if (flag & ~(AT_SYMLINK_NOFOLLOW | AT_EACCESS))
  28. return INLINE_SYSCALL_ERROR_RETURN_VALUE (EINVAL);
  29. if ((flag == 0 || ((flag & ~AT_EACCESS) == 0 && ! __libc_enable_secure)))
  30. return INLINE_SYSCALL (faccessat, 3, fd, file, mode);
  31. struct stat64 stats;
  32. if (__fxstatat64 (_STAT_VER, fd, file, &stats, flag & AT_SYMLINK_NOFOLLOW))
  33. return -1;
  34. mode &= (X_OK | W_OK | R_OK); /* Clear any bogus bits. */
  35. #if R_OK != S_IROTH || W_OK != S_IWOTH || X_OK != S_IXOTH
  36. # error Oops, portability assumptions incorrect.
  37. #endif
  38. if (mode == F_OK)
  39. return 0; /* The file exists. */
  40. uid_t uid = (flag & AT_EACCESS) ? __geteuid () : __getuid ();
  41. /* The super-user can read and write any file, and execute any file
  42. that anyone can execute. */
  43. if (uid == 0 && ((mode & X_OK) == 0
  44. || (stats.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
  45. return 0;
  46. int granted = (uid == stats.st_uid
  47. ? (unsigned int) (stats.st_mode & (mode << 6)) >> 6
  48. : (stats.st_gid == ((flag & AT_EACCESS)
  49. ? __getegid () : __getgid ())
  50. || __group_member (stats.st_gid))
  51. ? (unsigned int) (stats.st_mode & (mode << 3)) >> 3
  52. : (stats.st_mode & mode));
  53. if (granted == mode)
  54. return 0;
  55. return INLINE_SYSCALL_ERROR_RETURN_VALUE (EACCES);
  56. }