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