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