/* Reading inputs that are files by nature (see input.h). */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "input.h"
static int trusted(const struct stat *st) { return (st->st_uid == getuid() || st->st_uid == 0) && (st->st_mode & 022) == 0; }
char *pic_input_read(const char *path, size_t max, int flags, size_t *len, int *truncated) {
struct stat st, dst;
char *buf;
size_t got = 0;
int fd;
*len = 0;
if (truncated) {
*truncated = 0;
}
fd = open(path, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
if (fd < 0) {
return NULL;
}
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
close(fd);
errno = ENOENT;
return NULL;
}
if (flags & PIC_INPUT_TRUSTED) {
char dir[4096];
const char *slash = strrchr(path, '/');
(void)snprintf(dir, sizeof dir, "%.*s", slash ? (int)(slash - path) + 1 : 1, slash ? path : ".");
if (!trusted(&st) || stat(dir, &dst) != 0 || !trusted(&dst)) {
close(fd);
errno = EPERM;
return NULL;
}
}
if (!(buf = malloc(max + 2))) {
close(fd);
errno = ENOMEM;
return NULL;
}
for (;;) { /* one byte past max tells "over" from "exactly max" */
ssize_t n = read(fd, buf + got, max + 1 - got);
if (n < 0 && errno == EINTR) {
continue;
}
if (n < 0) {
int e = errno;
close(fd);
free(buf);
errno = e;
return NULL;
}
got += (size_t)n;
if (n == 0 || got > max) {
break;
}
}
close(fd);
if (got > max) {
if (!(flags & PIC_INPUT_TRUNCATE)) {
free(buf);
errno = EFBIG;
return NULL;
}
got = max;
if (truncated) {
*truncated = 1;
}
}
buf[got] = '\0';
*len = got;
return buf;
}