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#define FOR_mktemp
28#include "toys.h"
29
30GLOBALS(
31 char *p;
32)
33
34void mktemp_main(void)
35{
36 char *template = *toys.optargs, *dir = TT.p, *te = getenv("TMPDIR");
37 int len;
38
39
40 if (!dir || !*dir || (FLAG(t) && te && *te)) dir = te;
41 if (!dir || !*dir) dir = "/tmp";
42 if (!template) template = "tmp.XXXXXXXXXX";
43 else {
44 if (*template == '/' && TT.p && *TT.p) perror_exit("-p + /template");
45 if (!FLAG(p)&&!FLAG(t)) dir = 0;
46 }
47
48
49 template = dir ? xmprintf("%s/%s", dir, template) : xstrdup(template);
50 len = strlen(template);
51 if (len<3 || strcmp(template+len-3, "XXX")) perror_exit("need XXX");
52
53
54
55 if (toys.optflags & FLAG_u) {
56 long long rr;
57 char *s = template+len;
58
59
60 if (!xgetrandom(&rr, sizeof(rr), WARN_ONLY)) {
61 struct timespec ts;
62
63 clock_gettime(CLOCK_REALTIME, &ts);
64 rr = ts.tv_nsec*65537+(long)template+getpid()+(long)&template;
65 }
66
67 while (--s>template) {
68 if (*s != 'X') break;
69 *s = '-'+(rr&63);
70 if (*s>'.') ++*s;
71 if (*s>'9') (*s) += 7;
72 if (*s>'Z') (*s) += 6;
73 rr>>=6;
74 }
75 } else if ((toys.optflags & FLAG_d) ? !mkdtemp(template) : mkstemp(template) == -1) {
76 if (toys.optflags & FLAG_q) {
77 toys.exitval = 1;
78 return;
79 } else perror_exit("Failed to create %s %s/%s",
80 (toys.optflags & FLAG_d) ? "directory" : "file", TT.p, template);
81 }
82
83 xputs(template);
84 if (CFG_TOYBOX_FREE) free(template);
85}
86