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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define nil ((void*)0)
char*
mkfname(char *tmpdir, char *prefix)
{
int n;
char *p, *fname;
if((p = getenv("TMPDIR")) != nil)
goto Mktemp;
if((p = tmpdir) != nil)
goto Mktemp;
p = "/tmp";
Mktemp:
n = strlen(p)+1+strlen(prefix)+1+8+1;
if((fname = malloc(n)) == nil)
return nil;
memset(fname, 0, n);
strcat(fname, p);
if((n = strlen(p)) > 0 && p[n-1] != '/')
strcat(fname, "/");
strcat(fname, prefix);
strcat(fname, ".XXXXXXXX");
return fname;
}
extern int mkstemp(char*);
char*
safe_tempnam(char *tmpdir, char *prefix)
{
int fd;
char *fname;
if((fname = mkfname(tmpdir, prefix)) == nil)
return nil;
if((fd = mkstemp(fname)) < 0){ /* XXX: leak fd, fname */
free(fname);
return nil;
}
return fname;
}
int
safe_tmpnam(char *fname)
{
char *p;
if((p = mkfname(nil, "tmpfile")) == nil)
return -1;
strcpy(fname, p);
free(p);
return mkstemp(fname);
}
|