+static FILE *
+safely_open_log_file(const char *path)
+{
+ int fd = open(path, O_CREAT | O_APPEND | O_WRONLY | O_NOFOLLOW, 0666);
+ if (fd < 0)
+ return NULL;
+
+ struct stat sb;
+ if (fstat(fd, &sb) || !S_ISREG(sb.st_mode)) {
+ close(fd);
+ errno = EPERM;
+ return NULL;
+ }
+
+ return fdopen(fd, "a");
+}