Fix an unintialized-value-used warning that Valgrind detected in the capture
[metze/wireshark/wip.git] / tempfile.c
1 /* tempfile.c
2  * Routines to create temporary files
3  *
4  * $Id$
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
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.
14  *
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.
19  *
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include "config.h"
26
27 #include <glib.h>
28
29 #include <time.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <errno.h>
34
35 #ifdef HAVE_FCNTL_H
36 #include <fcntl.h>
37 #endif
38
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42
43 #ifdef HAVE_WINDOWS_H
44 #include <windows.h>
45 #endif
46
47 #ifdef _WIN32
48 #include <process.h>    /* For getpid() */
49 #endif
50
51 #include "tempfile.h"
52 #include <wsutil/file_util.h>
53
54 #ifndef __set_errno
55 #define __set_errno(x) errno=(x)
56 #endif
57
58 #define INITIAL_PATH_SIZE   128
59 #define TMP_FILE_SUFFIX     "XXXXXX"
60
61 #ifndef HAVE_MKSTEMP
62 /* Generate a unique temporary file name from TEMPLATE.
63    The last six characters of TEMPLATE must be TMP_FILE_SUFFIX;
64    they are replaced with a string that makes the filename unique.
65    Returns a file descriptor open on the file for reading and writing.  */
66 static int
67 mkstemp (char *template)
68 {
69   static const char letters[]
70     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
71   size_t len;
72   size_t i;
73
74   len = strlen (template);
75   if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX))
76     {
77       __set_errno (EINVAL);
78       return -1;
79     }
80
81   if (g_snprintf (&template[len - 5], 6, "%.5u",
82                (unsigned int) getpid () % 100000) != 5)
83     /* Inconceivable lossage.  */
84     return -1;
85
86   for (i = 0; i < sizeof (letters); ++i)
87     {
88       int fd;
89
90       template[len - 6] = letters[i];
91
92       fd = ws_open (template, O_RDWR|O_BINARY|O_CREAT|O_EXCL, 0600);
93       if (fd >= 0)
94         return fd;
95     }
96
97   /* We return the null string if we can't find a unique file name.  */
98
99   template[0] = '\0';
100   return -1;
101 }
102
103 #endif /* HAVE_MKSTEMP */
104
105 #ifndef HAVE_MKDTEMP
106 /* Generate a unique temporary directory name from TEMPLATE.
107    The last six characters of TEMPLATE must be TMP_FILE_SUFFIX;
108    they are replaced with a string that makes the filename unique.
109    Returns 0 on success or -1 on error (from mkdir(2)).  */
110 char *
111 mkdtemp (char *template)
112 {
113   static const char letters[]
114     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
115   size_t len;
116   size_t i;
117
118   len = strlen (template);
119   if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX))
120     {
121       __set_errno (EINVAL);
122       return NULL;
123     }
124
125   if (g_snprintf (&template[len - 5], 6, "%.5u",
126                (unsigned int) getpid () % 100000) != 5)
127     /* Inconceivable lossage.  */
128     return NULL;
129
130   for (i = 0; i < sizeof (letters); ++i)
131     {
132       int ret;
133
134       template[len - 6] = letters[i];
135
136       ret = ws_mkdir(template, 0700);
137       if (ret >= 0)
138         return template;
139     }
140
141   /* We return the null string if we can't find a unique file name.  */
142
143   template[0] = '\0';
144   return NULL;
145 }
146
147 #endif /* HAVE_MKDTEMP */
148
149 #define MAX_TEMPFILES   3
150
151 /**
152  * Create a tempfile with the given prefix (e.g. "wireshark").
153  *
154  * @param namebuf If not NULL, receives the full path of the temp file.
155  *                Should NOT be freed.
156  * @param pfx A prefix for the temporary file.
157  * @return The file descriptor of the new tempfile, from mkstemp().
158  * @todo Switch from mkstemp() to something like mkstemps(), so the caller
159  *       can optionally indicate that part of the pfx is actually a suffix,
160  *       such as "pcap" or "pcapng".
161  */
162 int
163 create_tempfile(char **namebuf, const char *pfx)
164 {
165         static struct _tf {
166                 char *path;
167                 unsigned long len;
168         } tf[MAX_TEMPFILES];
169         static int idx;
170
171         const char *tmp_dir;
172         int old_umask;
173         int fd;
174         time_t current_time;
175         char timestr[14 + 1];
176         gchar *tmp_file;
177         gchar *safe_pfx;
178         gchar sep[2] = {0, 0};
179
180         /* The characters in "delimiters" come from:
181          * http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx.
182          * Add to the list as necessary for other OS's.
183          */
184         const gchar *delimiters = "<>:\"/\\|?*"
185                 "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a"
186                 "\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
187                 "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f";
188
189         /* Sanitize the pfx to resolve bug 7877 */
190         safe_pfx = g_strdup(pfx);
191         safe_pfx = g_strdelimit(safe_pfx, delimiters, '-');
192
193         idx = (idx + 1) % MAX_TEMPFILES;
194
195         /*
196          * Allocate the buffer if it's not already allocated.
197          */
198         if (tf[idx].path == NULL) {
199                 tf[idx].len = INITIAL_PATH_SIZE;
200                 tf[idx].path = (char *)g_malloc(tf[idx].len);
201         }
202
203         /*
204          * We can't use get_tempfile_path here because we're called from dumpcap.c.
205          */
206         tmp_dir = g_get_tmp_dir();
207
208 #ifdef _WIN32
209         _tzset();
210 #endif
211         current_time = time(NULL);
212         strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
213         sep[0] = G_DIR_SEPARATOR;
214         tmp_file = g_strconcat(tmp_dir, sep, safe_pfx, "_", timestr, "_", TMP_FILE_SUFFIX, NULL);
215         g_free(safe_pfx);
216         if (strlen(tmp_file) > tf[idx].len) {
217                 tf[idx].len = (int)strlen(tmp_file) + 1;
218                 tf[idx].path = (char *)g_realloc(tf[idx].path, tf[idx].len);
219         }
220         g_strlcpy(tf[idx].path, tmp_file, tf[idx].len);
221         g_free(tmp_file);
222
223         if (namebuf) {
224                 *namebuf = tf[idx].path;
225         }
226         /* The Single UNIX Specification doesn't say that "mkstemp()"
227            creates the temporary file with mode rw-------, so we
228            won't assume that all UNIXes will do so; instead, we set
229            the umask to 0077 to take away all group and other
230            permissions, attempt to create the file, and then put
231            the umask back. */
232         old_umask = umask(0077);
233         fd = mkstemp(tf[idx].path);
234         umask(old_umask);
235         return fd;
236 }
237
238 /**
239  * Create a directory with the given prefix (e.g. "wireshark"). The path
240  * is created using g_get_tmp_dir and mkdtemp.
241  *
242  * @param namebuf
243  * @param pfx A prefix for the temporary directory.
244  * @return The temporary directory path on success, or NULL on failure.
245  *         Must NOT be freed.
246  */
247 const char *
248 create_tempdir(char **namebuf, const char *pfx)
249 {
250         static char *td_path[3];
251         static int td_path_len[3];
252         static int idx;
253         const char *tmp_dir;
254
255         idx = (idx + 1) % 3;
256
257         /*
258          * Allocate the buffer if it's not already allocated.
259          */
260         if (td_path[idx] == NULL) {
261                 td_path_len[idx] = INITIAL_PATH_SIZE;
262                 td_path[idx] = (char *)g_malloc(td_path_len[idx]);
263         }
264
265         /*
266          * We can't use get_tempfile_path here because we're called from dumpcap.c.
267          */
268         tmp_dir = g_get_tmp_dir();
269
270         while (g_snprintf(td_path[idx], td_path_len[idx], "%s%c%s" TMP_FILE_SUFFIX, tmp_dir, G_DIR_SEPARATOR, pfx) > td_path_len[idx]) {
271                 td_path_len[idx] *= 2;
272                 td_path[idx] = (char *)g_realloc(td_path[idx], td_path_len[idx]);
273         }
274
275         if (namebuf) {
276                 *namebuf = td_path[idx];
277         }
278         return mkdtemp(td_path[idx]);
279 }