| 1 | #include <errno.h> |
| 2 | #include <libproc.h> |
| 3 | #include <stdlib.h> |
| 4 | #include <sys/file.h> |
| 5 | #include <sys/proc_info.h> |
| 6 | #include <sys/stat.h> |
| 7 | |
| 8 | |
| 9 | |
| 10 | int cage_file_has_writer(int root, const char *path) { |
| 11 | struct stat target; |
| 12 | if (lstat(path, &target) != 0 || !S_ISREG(target.st_mode)) return -1; |
| 13 | int pids[256] = {root}; |
| 14 | int count = 1; |
| 15 | for (int index = 0; index < count; index++) { |
| 16 | int children[256]; |
| 17 | int child_count = proc_listchildpids(pids[index], children, sizeof(children)); |
| 18 | if (child_count < 0 || child_count >= 256) return -1; |
| 19 | for (int child = 0; child < child_count; child++) { |
| 20 | int seen = 0; |
| 21 | for (int prior = 0; prior < count; prior++) seen |= pids[prior] == children[child]; |
| 22 | if (!seen && children[child] > 0) { |
| 23 | if (count == 256) return -1; |
| 24 | pids[count++] = children[child]; |
| 25 | } |
| 26 | } |
| 27 | int needed = proc_pidinfo(pids[index], PROC_PIDLISTFDS, 0, NULL, 0); |
| 28 | if (needed <= 0) { |
| 29 | if (errno == ESRCH) continue; |
| 30 | return -1; |
| 31 | } |
| 32 | if (needed > 32768 * (int)sizeof(struct proc_fdinfo)) return -1; |
| 33 | int capacity = needed + 128 * (int)sizeof(struct proc_fdinfo); |
| 34 | struct proc_fdinfo *fds = malloc((size_t)capacity); |
| 35 | if (!fds) return -1; |
| 36 | int received = proc_pidinfo(pids[index], PROC_PIDLISTFDS, 0, fds, capacity); |
| 37 | if (received <= 0 || received >= capacity) { free(fds); return -1; } |
| 38 | for (int fd = 0; fd < received / (int)sizeof(*fds); fd++) { |
| 39 | if (fds[fd].proc_fdtype != PROX_FDTYPE_VNODE) continue; |
| 40 | struct vnode_fdinfo info; |
| 41 | int size = proc_pidfdinfo(pids[index], fds[fd].proc_fd, PROC_PIDFDVNODEINFO, &info, sizeof(info)); |
| 42 | if (size != sizeof(info)) { |
| 43 | if (errno == EBADF || errno == ESRCH || errno == ENOENT) continue; |
| 44 | free(fds); return -1; |
| 45 | } |
| 46 | if (info.pvi.vi_stat.vst_dev == (uint32_t)target.st_dev && info.pvi.vi_stat.vst_ino == target.st_ino && |
| 47 | (info.pfi.fi_openflags & FWRITE) != 0) { free(fds); return 1; } |
| 48 | } |
| 49 | free(fds); |
| 50 | } |
| 51 | return 0; |
| 52 | } |