1 /* Copyright (C) 1999, 2001-2002, 2006 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Extracted from sysdeps/posix/tempname.c. */
33 # define __set_errno(Val) errno = (Val)
38 # define P_tmpdir "/tmp"
42 #if !defined S_ISDIR && defined S_IFDIR
43 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
45 #if !S_IRUSR && S_IREAD
46 # define S_IRUSR S_IREAD
49 # define S_IRUSR 00400
51 #if !S_IWUSR && S_IWRITE
52 # define S_IWUSR S_IWRITE
55 # define S_IWUSR 00200
57 #if !S_IXUSR && S_IEXEC
58 # define S_IXUSR S_IEXEC
61 # define S_IXUSR 00100
65 # define struct_stat64 struct stat64
67 # define struct_stat64 struct stat
68 # define __xstat64(version, path, buf) stat (path, buf)
71 #if ! (HAVE___SECURE_GETENV || _LIBC)
72 # define __secure_getenv getenv
76 ISSLASH(C) tests whether C is a directory separator character.
78 #if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
79 /* Win32, Cygwin, OS/2, DOS */
80 # define ISSLASH(C) ((C) == '/' || (C) == '\\')
83 # define ISSLASH(C) ((C) == '/')
87 /* Return nonzero if DIR is an existent directory. */
89 direxists (const char *dir)
92 return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
95 /* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
96 non-null and exists, uses it; otherwise uses the first of $TMPDIR,
97 P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
98 for use with mk[s]temp. Will fail (-1) if DIR is non-null and
99 doesn't exist, none of the searched dirs exists, or there's not
100 enough space in TMPL. */
102 path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
122 d = __secure_getenv ("TMPDIR");
123 if (d != NULL && direxists (d))
125 else if (dir != NULL && direxists (dir))
132 if (direxists (P_tmpdir))
134 else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
138 __set_errno (ENOENT);
144 while (dlen >= 1 && ISSLASH (dir[dlen - 1]))
145 dlen--; /* remove trailing slashes */
147 /* check we have room for "${dir}/${pfx}XXXXXX\0" */
148 if (tmpl_len < dlen + 1 + plen + 6 + 1)
150 __set_errno (EINVAL);
154 sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);