summaryrefslogtreecommitdiff
path: root/lib/fileutils.c
diff options
context:
space:
mode:
authorSami Kerola <kerolasa@iki.fi>2012-02-29 15:58:51 +0100
committerSami Kerola <kerolasa@iki.fi>2012-03-18 14:28:04 +0100
commit6b79eb38ba46a7635a635623b91c2e3aa9326c7d (patch)
treeb0e41bc4dd28196b6008329a5be83d7a976f1118 /lib/fileutils.c
parentc900336d8b011278822dbc4e38ff9f6419f57ac2 (diff)
downloadutil-linux-6b79eb38ba46a7635a635623b91c2e3aa9326c7d.tar.gz
lib: add fileutils function collection
The fileutils contains xmkstemp function will create temporary file safe and reusable manner. Reference: http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO.html#TEMPORARY-FILES CC: Davidlohr Bueso <dave@gnu.org> Signed-off-by: Sami Kerola <kerolasa@iki.fi>
Diffstat (limited to 'lib/fileutils.c')
-rw-r--r--lib/fileutils.c55
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/fileutils.c b/lib/fileutils.c
new file mode 100644
index 000000000..ed97967a3
--- /dev/null
+++ b/lib/fileutils.c
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2012 Sami Kerola <kerolasa@iki.fi>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "c.h"
+#include "pathnames.h"
+
+/* Create open temporary file in safe way. Please notice that the
+ * file permissions are -rw------- by default. */
+FILE *xmkstemp(char **tmpname)
+{
+ char *localtmp;
+ char *tmpenv;
+ mode_t old_mode;
+ int fd;
+ FILE *ret;
+
+ tmpenv = getenv("TMPDIR");
+ if (tmpenv)
+ asprintf(&localtmp, "%s/%s.XXXXXX", tmpenv,
+ program_invocation_short_name);
+ else
+ asprintf(&localtmp, "%s/%s.XXXXXX", _PATH_TMP,
+ program_invocation_short_name);
+ old_mode = umask(077);
+ fd = mkstemp(localtmp);
+ umask(old_mode);
+ if (fd == -1)
+ return NULL;
+ if (!(ret = fdopen(fd, "w+")))
+ goto err;
+ *tmpname = localtmp;
+ return ret;
+ err:
+ close(fd);
+ return NULL;
+}
+
+#ifdef TEST_PROGRAM
+int main(void)
+{
+ FILE *f;
+ char *tmpname;
+ f = xmkstemp(&tmpname);
+ unlink(tmpname);
+ free(tmpname);
+ fclose(f);
+ return EXIT_FAILURE;
+}
+#endif