1 /* Copyright (C) 1999, 2001-2002, 2006, 2009-2010 Free Software Foundation,
3 This file is part of the GNU C Library.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* Extracted from sysdeps/posix/tempname.c. */
31 # define __set_errno(Val) errno = (Val)
36 # define P_tmpdir "/tmp"
42 # define struct_stat64 struct stat64
44 # define struct_stat64 struct stat
45 # define __xstat64(version, path, buf) stat (path, buf)
48 #if ! (HAVE___SECURE_GETENV || _LIBC)
49 # define __secure_getenv getenv
53 ISSLASH(C) tests whether C is a directory separator character.
55 #if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
56 /* Win32, Cygwin, OS/2, DOS */
57 # define ISSLASH(C) ((C) == '/' || (C) == '\\')
60 # define ISSLASH(C) ((C) == '/')
64 /* Return nonzero if DIR is an existent directory. */
66 direxists (const char *dir)
69 return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
72 /* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
73 non-null and exists, uses it; otherwise uses the first of $TMPDIR,
74 P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
75 for use with mk[s]temp. Will fail (-1) if DIR is non-null and
76 doesn't exist, none of the searched dirs exists, or there's not
77 enough space in TMPL. */
79 path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
99 d = __secure_getenv ("TMPDIR");
100 if (d != NULL && direxists (d))
102 else if (dir != NULL && direxists (dir))
109 if (direxists (P_tmpdir))
111 else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
115 __set_errno (ENOENT);
121 while (dlen >= 1 && ISSLASH (dir[dlen - 1]))
122 dlen--; /* remove trailing slashes */
124 /* check we have room for "${dir}/${pfx}XXXXXX\0" */
125 if (tmpl_len < dlen + 1 + plen + 6 + 1)
127 __set_errno (EINVAL);
131 sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);