/* utils.c PUBLIC DOMAIN 2016 */ /* part of dqrs */ /* I, Tom Vajzovic, am the author of this software and its documentation. I permanently abandon all intellectual property rights in them, including copyright, trademarks, design rights, database right, patents, and the right to be identified as the author. I am fairly certain that the software does what the documentation says it does, but I do not guarantee that it does, or that it does what you think it should. I do not guarantee that it will not have undesirable side effects. You are free to use, modify and distribute this software as you please, but you do so at your own risk. If you do not pass on this warning then you may be responsible for any problems encountered by those who obtain the software through you. */ #include #include #include #include #include #include #include #include "utils.h" DIR *opendirat (int dir_fd_parent, const char *name) {{{ DIR *dir_ptr_child = NULL; int dir_fd_child = openat (dir_fd_parent, name, (O_RDONLY | O_DIRECTORY | O_NOFOLLOW)); if (dir_fd_child >= 0) { dir_ptr_child = fdopendir (dir_fd_child); if (!dir_ptr_child) { int save_errno = errno; (void)close (dir_fd_child); errno = save_errno; } } return dir_ptr_child; }}} char *readlinkata (int dir_fd, const char *name) {{{ #ifdef O_PATH int link_fd = openat (dir_fd, name, (O_PATH | O_NOFOLLOW)); if (link_fd < 0) { return NULL; } struct stat stat_buf; if (fstat (link_fd, &stat_buf)) { int save_errno = errno; close (link_fd); errno = save_errno; return NULL; } if (!S_ISLNK(stat_buf.st_mode)) { close (link_fd); errno = EINVAL; return NULL; } size_t size = stat_buf.st_size; char *name_buf = malloc (size + 1); if (!name_buf) { int save_errno = errno; close (link_fd); errno = save_errno; return NULL; } ssize_t link_length = readlinkat (link_fd, "", name_buf, (size + 1)); if (link_length < 0) { int save_errno = errno; free (name_buf); close (link_fd); errno = save_errno; return NULL; } if ((size_t)link_length != size) { free (name_buf); close (link_fd); errno = EAGAIN; return NULL; } close (link_fd); name_buf[size] = 0; return name_buf; #else unsigned int i; for (i = 10; i < 32; i++) { size_t size = (1uL << i); char *buf = malloc (size); ssize_t link_length = readlinkat (dir_fd, name, buf, size); if (link_length < 0) { int save_errno = errno; free (buf); errno = save_errno; return NULL; } if ((size_t)link_length < size) { buf [(size_t)link_length] = 0; return buf; } free (buf); } errno = ENAMETOOLONG; return NULL; #endif }}} int open_file_only (int dir_fd, const char *name, off_t *size_p) {{{ int fd = openat (dir_fd, name, (O_RDONLY | O_NOFOLLOW)); if (fd < 0) { return fd; } struct stat sb; if (fstat (fd, &sb)) { int save_errno = errno; (void)close (fd); errno = save_errno; return -1; } if (!S_ISREG (sb.st_mode)) { (void)close (fd); errno = ESPIPE; return -1; } *size_p = sb.st_size; return fd; }}}