[Automatic manuf, services and enterprise-numbers update for 2011-11-06]
[obnox/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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <glib.h>
30
31 #include <time.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <errno.h>
36
37 #ifdef HAVE_FCNTL_H
38 #include <fcntl.h>
39 #endif
40
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44
45 #ifdef HAVE_WINDOWS_H
46 #include <windows.h>
47 #endif
48
49 #ifdef _WIN32
50 #include <process.h>    /* For getpid() */
51 #endif
52
53 #include "tempfile.h"
54 #include <wsutil/file_util.h>
55
56 #ifndef __set_errno
57 #define __set_errno(x) errno=(x)
58 #endif
59
60 #define INITIAL_PATH_SIZE   128
61 #define TMP_FILE_SUFFIX     "XXXXXX"
62
63 #ifndef HAVE_MKSTEMP
64 /* Generate a unique temporary file name from TEMPLATE.
65    The last six characters of TEMPLATE must be TMP_FILE_SUFFIX;
66    they are replaced with a string that makes the filename unique.
67    Returns a file descriptor open on the file for reading and writing.  */
68 static int
69 mkstemp (template)
70      char *template;
71 {
72   static const char letters[]
73     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
74   size_t len;
75   size_t i;
76
77   len = strlen (template);
78   if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX))
79     {
80       __set_errno (EINVAL);
81       return -1;
82     }
83
84   if (g_snprintf (&template[len - 5], 6, "%.5u",
85                (unsigned int) getpid () % 100000) != 5)
86     /* Inconceivable lossage.  */
87     return -1;
88
89   for (i = 0; i < sizeof (letters); ++i)
90     {
91       int fd;
92
93       template[len - 6] = letters[i];
94
95       fd = ws_open (template, O_RDWR|O_BINARY|O_CREAT|O_EXCL, 0600);
96       if (fd >= 0)
97         return fd;
98     }
99
100   /* We return the null string if we can't find a unique file name.  */
101
102   template[0] = '\0';
103   return -1;
104 }
105
106 #endif /* HAVE_MKSTEMP */
107
108 #ifndef HAVE_MKDTEMP
109 /* Generate a unique temporary directory name from TEMPLATE.
110    The last six characters of TEMPLATE must be TMP_FILE_SUFFIX;
111    they are replaced with a string that makes the filename unique.
112    Returns 0 on success or -1 on error (from mkdir(2)).  */
113 char *
114 mkdtemp (template)
115      char *template;
116 {
117   static const char letters[]
118     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
119   size_t len;
120   size_t i;
121
122   len = strlen (template);
123   if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX))
124     {
125       __set_errno (EINVAL);
126       return NULL;
127     }
128
129   if (g_snprintf (&template[len - 5], 6, "%.5u",
130                (unsigned int) getpid () % 100000) != 5)
131     /* Inconceivable lossage.  */
132     return NULL;
133
134   for (i = 0; i < sizeof (letters); ++i)
135     {
136       int ret;
137
138       template[len - 6] = letters[i];
139
140       ret = ws_mkdir(template, 0700);
141       if (ret >= 0)
142         return template;
143     }
144
145   /* We return the null string if we can't find a unique file name.  */
146
147   template[0] = '\0';
148   return NULL;
149 }
150
151 #endif /* HAVE_MKDTEMP */
152
153 #define MAX_TEMPFILES   3
154
155 /**
156  * Create a tempfile with the given prefix (e.g. "wireshark").
157  * 
158  * @param namebuf If not NULL, receives the full path of the temp file.
159  *                Should NOT be freed.
160  * @param pfx A prefix for the temporary file.
161  * @return The file descriptor of the new tempfile, from mkstemp().
162  */
163 int
164 create_tempfile(char **namebuf, const char *pfx)
165 {
166         static struct _tf {
167                 char *path;
168                 unsigned long len;
169         } tf[MAX_TEMPFILES];
170         static int idx;
171
172         const char *tmp_dir;
173         int old_umask;
174         int fd;
175         time_t current_time;
176         char timestr[14 + 1];
177         gchar *tmp_file;
178         gchar sep[2] = {0, 0};
179
180         idx = (idx + 1) % MAX_TEMPFILES;
181         
182         /*
183          * Allocate the buffer if it's not already allocated.
184          */
185         if (tf[idx].path == NULL) {
186                 tf[idx].len = INITIAL_PATH_SIZE;
187                 tf[idx].path = (char *)g_malloc(tf[idx].len);
188         }
189
190         /*
191          * We can't use get_tempfile_path here because we're called from dumpcap.c.
192          */
193         tmp_dir = g_get_tmp_dir();
194
195 #ifdef _WIN32
196         _tzset();
197 #endif
198         current_time = time(NULL);
199         strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
200         sep[0] = G_DIR_SEPARATOR;
201         tmp_file = g_strconcat(tmp_dir, sep, pfx, "_", timestr, "_", TMP_FILE_SUFFIX, NULL);
202         if (strlen(tmp_file) > tf[idx].len) {
203                 tf[idx].len = (int)strlen(tmp_file) + 1;
204                 tf[idx].path = (char *)g_realloc(tf[idx].path, tf[idx].len);
205         }
206         g_strlcpy(tf[idx].path, tmp_file, tf[idx].len);
207         g_free(tmp_file);
208
209         if (namebuf) {
210                 *namebuf = tf[idx].path;
211         }
212         /* The Single UNIX Specification doesn't say that "mkstemp()"
213            creates the temporary file with mode rw-------, so we
214            won't assume that all UNIXes will do so; instead, we set
215            the umask to 0077 to take away all group and other
216            permissions, attempt to create the file, and then put
217            the umask back. */
218         old_umask = umask(0077);
219         fd = mkstemp(tf[idx].path);
220         umask(old_umask);
221         return fd;
222 }
223
224 /**
225  * Create a directory with the given prefix (e.g. "wireshark"). The path
226  * is created using g_get_tmp_dir and mkdtemp.
227  * 
228  * @param namebuf 
229  * @param pfx A prefix for the temporary directory.
230  * @return The temporary directory path on success, or NULL on failure.
231  *         Must NOT be freed.
232  */
233 const char *
234 create_tempdir(char **namebuf, const char *pfx)
235 {
236         static char *td_path[3];
237         static int td_path_len[3];
238         static int idx;
239         const char *tmp_dir;
240
241         idx = (idx + 1) % 3;
242         
243         /*
244          * Allocate the buffer if it's not already allocated.
245          */
246         if (td_path[idx] == NULL) {
247                 td_path_len[idx] = INITIAL_PATH_SIZE;
248                 td_path[idx] = (char *)g_malloc(td_path_len[idx]);
249         }
250
251         /*
252          * We can't use get_tempfile_path here because we're called from dumpcap.c.
253          */
254         tmp_dir = g_get_tmp_dir();
255
256         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]) {
257                 td_path_len[idx] *= 2;
258                 td_path[idx] = (char *)g_realloc(td_path[idx], td_path_len[idx]);
259         }
260
261         if (namebuf) {
262                 *namebuf = td_path[idx];
263         }
264         return mkdtemp(td_path[idx]);
265 }