initial check-in, version 0.5.0
[musl] / src / stdio / tmpnam.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <limits.h>
5 #include <unistd.h>
6 #include "libc.h"
7
8 char *tmpnam(char *s)
9 {
10         static int lock;
11         static int index;
12         static char *s2;
13         int pid = getpid();
14         char *dir = getenv("TMPDIR");
15
16         if (!s) {
17                 if (!s2) s2 = malloc(L_tmpnam);
18                 s = s2;
19         }
20
21         /* this interface is insecure anyway but at least we can try.. */
22         if (!dir || strlen(dir) > L_tmpnam-32)
23                 dir = P_tmpdir;
24
25         if (access(dir, R_OK|W_OK|X_OK) != 0)
26                 return NULL;
27
28         LOCK(&lock);
29         for (index++; index < TMP_MAX; index++) {
30                 snprintf(s, L_tmpnam, "%s/temp%d-%d", dir, pid, index);
31                 if (access(s, F_OK) != 0) {
32                         UNLOCK(&lock);
33                         return s;
34                 }
35         }
36         UNLOCK(&lock);
37         return NULL;
38 }