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