2 * Routines to create temporary files
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
46 #include <wsutil/file_util.h>
49 setup_tmpdir(const char *dir)
51 size_t len = strlen(dir);
54 /* Append path separator if necessary */
55 if (len != 0 && dir[len - 1] == G_DIR_SEPARATOR) {
59 newdir = g_strdup_printf("%s%s", dir, G_DIR_SEPARATOR_S);
65 try_tempfile(char *namebuf, int namebuflen, const char *dir, const char *pfx)
67 static const char suffix[] = "XXXXXXXXXX";
68 int namelen = strlen(dir) + strlen(pfx) + sizeof suffix;
72 g_snprintf(namebuf, namebuflen, "%s%s%s", dir, pfx, suffix);
73 if (namebuflen < namelen) {
74 /* Stick with the truncated name, so that if this error is
75 reported with the file name, you at least get
81 /* The Single UNIX Specification doesn't say that "mkstemp()"
82 creates the temporary file with mode rw-------, so we
83 won't assume that all UNIXes will do so; instead, we set
84 the umask to 0077 to take away all group and other
85 permissions, attempt to create the file, and then put
87 old_umask = umask(0077);
88 tmp_fd = mkstemp(namebuf);
93 static const char *tmpdir = NULL;
95 static const char *temp = NULL;
97 static const char *E_tmpdir;
100 #define P_tmpdir "/var/tmp"
103 /* create a tempfile with the given prefix (e.g. "ether")
104 * namebuf (and namebuflen) should be 128+1 bytes long (BTW: why?)
105 * returns the file descriptor of the new tempfile and
106 * the name of the new file in namebuf
109 create_tempfile(char *namebuf, int namebuflen, const char *pfx)
113 static gboolean initialized;
116 if ((dir = getenv("TMPDIR")) != NULL)
117 tmpdir = setup_tmpdir(dir);
119 if ((dir = getenv("TEMP")) != NULL)
120 temp = setup_tmpdir(dir);
123 E_tmpdir = setup_tmpdir(P_tmpdir);
127 if (tmpdir != NULL) {
128 fd = try_tempfile(namebuf, namebuflen, tmpdir, pfx);
135 fd = try_tempfile(namebuf, namebuflen, temp, pfx);
141 fd = try_tempfile(namebuf, namebuflen, E_tmpdir, pfx);
145 return try_tempfile(namebuf, namebuflen, G_DIR_SEPARATOR_S "tmp", pfx);