summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--color.c2
-rw-r--r--mtab.c2
-rw-r--r--parse.c2
-rw-r--r--util.c45
-rw-r--r--util.h10
5 files changed, 58 insertions, 3 deletions
diff --git a/color.c b/color.c
index 509e646..09070f2 100644
--- a/color.c
+++ b/color.c
@@ -526,7 +526,7 @@ CFILE *cfopen(const char *path, const struct colors *colors) {
return NULL;
}
- cfile->file = fopen(path, "wb");
+ cfile->file = xfopen(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC);
if (!cfile->file) {
cfclose(cfile);
return NULL;
diff --git a/mtab.c b/mtab.c
index 91a40aa..cb6a59a 100644
--- a/mtab.c
+++ b/mtab.c
@@ -162,7 +162,7 @@ struct bfs_mtab *bfs_mtab_parse() {
#elif BFS_MNTTAB
- FILE *file = fopen(MNTTAB, "r");
+ FILE *file = xfopen(MNTTAB, O_RDONLY | O_CLOEXEC);
if (!file) {
error = errno;
goto fail;
diff --git a/parse.c b/parse.c
index ad8e89c..98e7dbb 100644
--- a/parse.c
+++ b/parse.c
@@ -1278,7 +1278,7 @@ static struct expr *parse_files0_from(struct parser_state *state, int arg1, int
if (strcmp(from, "-") == 0) {
file = stdin;
} else {
- file = fopen(from, "rb");
+ file = xfopen(from, O_RDONLY | O_CLOEXEC);
}
if (!file) {
parse_error(state, "${blu}%s${rs} ${bld}%s${rs}: %m.\n", arg, from);
diff --git a/util.c b/util.c
index d913b7d..728f962 100644
--- a/util.c
+++ b/util.c
@@ -16,6 +16,7 @@
#include "util.h"
#include "dstring.h"
+#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <langinfo.h>
@@ -426,3 +427,47 @@ char *xgetdelim(FILE *file, char delim) {
return NULL;
}
}
+
+FILE *xfopen(const char *path, int flags) {
+ char mode[4];
+
+ switch (flags & O_ACCMODE) {
+ case O_RDONLY:
+ strcpy(mode, "rb");
+ break;
+ case O_WRONLY:
+ strcpy(mode, "wb");
+ break;
+ case O_RDWR:
+ strcpy(mode, "r+b");
+ break;
+ default:
+ assert(!"Invalid access mode");
+ return NULL;
+ }
+
+ if (flags & O_APPEND) {
+ mode[0] = 'a';
+ }
+
+ int fd;
+ if (flags & O_CREAT) {
+ fd = open(path, flags, 0666);
+ } else {
+ fd = open(path, flags);
+ }
+
+ if (fd < 0) {
+ return NULL;
+ }
+
+ FILE *ret = fdopen(fd, mode);
+ if (!ret) {
+ int error = errno;
+ close(fd);
+ errno = error;
+ return NULL;
+ }
+
+ return ret;
+}
diff --git a/util.h b/util.h
index be38db5..ccac549 100644
--- a/util.h
+++ b/util.h
@@ -288,4 +288,14 @@ char *xconfstr(int name);
*/
char *xgetdelim(FILE *file, char delim);
+/**
+ * fopen() variant that takes open() style flags.
+ *
+ * @param path
+ * The path to open.
+ * @param flags
+ * Flags to pass to open().
+ */
+FILE *xfopen(const char *path, int flags);
+
#endif // BFS_UTIL_H