blob: 17b7e7d932e2d6e47999378e0b674c1e254d2c27 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
Index: b/lib/routines.c
===================================================================
--- a/lib/routines.c
+++ b/lib/routines.c
@@ -242,3 +242,50 @@
/* Don't complain if you can't unlink. Who cares of a tmp file? */
unlink (filename);
}
+
+/*
+ * Securely generate a temp file, and make sure it gets
+ * deleted upon exit.
+ */
+static char ** tempfiles;
+static unsigned ntempfiles;
+
+static void
+cleanup_tempfiles()
+{
+ while (ntempfiles--)
+ unlink(tempfiles[ntempfiles]);
+}
+
+char *
+safe_tempnam(const char *pfx)
+{
+ char *dirname, *filename;
+ int fd;
+
+ if (!(dirname = getenv("TMPDIR")))
+ dirname = "/tmp";
+
+ tempfiles = (char **) realloc(tempfiles,
+ (ntempfiles+1) * sizeof(char *));
+ if (tempfiles == NULL)
+ return NULL;
+
+ filename = malloc(strlen(dirname) + strlen(pfx) + sizeof("/XXXXXX"));
+ if (!filename)
+ return NULL;
+
+ sprintf(filename, "%s/%sXXXXXX", dirname, pfx);
+
+ if ((fd = mkstemp(filename)) < 0) {
+ free(filename);
+ return NULL;
+ }
+ close(fd);
+
+ if (ntempfiles == 0)
+ atexit(cleanup_tempfiles);
+ tempfiles[ntempfiles++] = filename;
+
+ return filename;
+}
Index: b/lib/routines.h
===================================================================
--- a/lib/routines.h
+++ b/lib/routines.h
@@ -255,7 +255,8 @@
/* If _STR_ is not defined, give it a tempname in _TMPDIR_ */
#define tempname_ensure(Str) \
do { \
- (Str) = (Str) ? (Str) : tempnam (NULL, "a2_"); \
+ (Str) = (Str) ? (Str) : safe_tempnam("a2_"); \
} while (0)
+char * safe_tempnam(const char *);
#endif
|