• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <errno.h>
4 #include <sys/stat.h>
5 #include <limits.h>
6 #include <string.h>
7 #include <stdlib.h>
8 #include "syscall.h"
9 #include "kstat.h"
10 
11 #define MAXTRIES 100
12 
tempnam(const char * dir,const char * pfx)13 char *tempnam(const char *dir, const char *pfx)
14 {
15 	char s[PATH_MAX];
16 	size_t l, dl, pl;
17 	int try;
18 	int r;
19 
20 	if (!dir) dir = P_tmpdir;
21 	if (!pfx) pfx = "temp";
22 
23 	dl = strlen(dir);
24 	pl = strlen(pfx);
25 	l = dl + 1 + pl + 1 + 6;
26 
27 	if (l >= PATH_MAX) {
28 		errno = ENAMETOOLONG;
29 		return 0;
30 	}
31 
32 	memcpy(s, dir, dl);
33 	s[dl] = '/';
34 	memcpy(s+dl+1, pfx, pl);
35 	s[dl+1+pl] = '_';
36 	s[l] = 0;
37 
38 	for (try=0; try<MAXTRIES; try++) {
39 		__randname(s+l-6);
40 #ifdef SYS_lstat
41 		r = __syscall(SYS_lstat, s, &(struct kstat){0});
42 #else
43 		r = __syscall(SYS_fstatat, AT_FDCWD, s,
44 			&(struct kstat){0}, AT_SYMLINK_NOFOLLOW);
45 #endif
46 		if (r == -ENOENT) return strdup(s);
47 	}
48 	return 0;
49 }
50