Rename "Secure Socket Layer" to "Secure Sockets Layer" (plural) and update
[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 <stdlib.h>
32 #include <string.h>
33 #include <stdio.h>
34 #include <errno.h>
35
36 #ifdef HAVE_FCNTL_H
37 #include <fcntl.h>
38 #endif
39
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43
44 #ifdef HAVE_WINDOWS_H
45 #include <windows.h>
46 #endif
47
48 #ifdef _WIN32
49 #include <process.h>    /* For getpid() */
50 #endif
51
52 #include "tempfile.h"
53 #include <wsutil/file_util.h>
54
55 #ifndef __set_errno
56 #define __set_errno(x) errno=(x)
57 #endif
58
59 #define INITIAL_PATH_SIZE   128
60 #define TMP_FILE_SUFFIX     "XXXXXX"
61
62 #ifndef HAVE_MKSTEMP
63 /* Generate a unique temporary file name from TEMPLATE.
64    The last six characters of TEMPLATE must be TMP_FILE_SUFFIX;
65    they are replaced with a string that makes the filename unique.
66    Returns a file descriptor open on the file for reading and writing.  */
67 static int
68 mkstemp (template)
69      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 (template)
114      char *template;
115 {
116   static const char letters[]
117     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
118   size_t len;
119   size_t i;
120
121   len = strlen (template);
122   if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX))
123     {
124       __set_errno (EINVAL);
125       return NULL;
126     }
127
128   if (g_snprintf (&template[len - 5], 6, "%.5u",
129                (unsigned int) getpid () % 100000) != 5)
130     /* Inconceivable lossage.  */
131     return NULL;
132
133   for (i = 0; i < sizeof (letters); ++i)
134     {
135       int ret;
136
137       template[len - 6] = letters[i];
138
139       ret = ws_mkdir(template, 0700);
140       if (ret >= 0)
141         return template;
142     }
143
144   /* We return the null string if we can't find a unique file name.  */
145
146   template[0] = '\0';
147   return NULL;
148 }
149
150 #endif /* HAVE_MKDTEMP */
151
152 #define MAX_TEMPFILES   3
153
154 /**
155  * Create a tempfile with the given prefix (e.g. "wireshark").
156  * 
157  * @param namebuf If not NULL, receives the full path of the temp file.
158  *                Should NOT be freed.
159  * @param pfx A prefix for the temporary file.
160  * @return The file descriptor of the new tempfile, from mkstemp().
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 sep[2] = {0, 0};
178
179         idx = (idx + 1) % MAX_TEMPFILES;
180         
181         /*
182          * Allocate the buffer if it's not already allocated.
183          */
184         if (tf[idx].path == NULL) {
185                 tf[idx].len = INITIAL_PATH_SIZE;
186                 tf[idx].path = (char *)g_malloc(tf[idx].len);
187         }
188
189         /*
190          * We can't use get_tempfile_path here because we're called from dumpcap.c.
191          */
192         tmp_dir = g_get_tmp_dir();
193
194 #ifdef _WIN32
195         _tzset();
196 #endif
197         current_time = time(NULL);
198         strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
199         sep[0] = G_DIR_SEPARATOR;
200         tmp_file = g_strconcat(tmp_dir, sep, pfx, "_", timestr, "_", TMP_FILE_SUFFIX, NULL);
201         if (strlen(tmp_file) > tf[idx].len) {
202                 tf[idx].len = (int)strlen(tmp_file) + 1;
203                 tf[idx].path = (char *)g_realloc(tf[idx].path, tf[idx].len);
204         }
205         g_strlcpy(tf[idx].path, tmp_file, tf[idx].len);
206         g_free(tmp_file);
207
208         if (namebuf) {
209                 *namebuf = tf[idx].path;
210         }
211         /* The Single UNIX Specification doesn't say that "mkstemp()"
212            creates the temporary file with mode rw-------, so we
213            won't assume that all UNIXes will do so; instead, we set
214            the umask to 0077 to take away all group and other
215            permissions, attempt to create the file, and then put
216            the umask back. */
217         old_umask = umask(0077);
218         fd = mkstemp(tf[idx].path);
219         umask(old_umask);
220         return fd;
221 }
222
223 /**
224  * Create a directory with the given prefix (e.g. "wireshark"). The path
225  * is created using g_get_tmp_dir and mkdtemp.
226  * 
227  * @param namebuf 
228  * @param pfx A prefix for the temporary directory.
229  * @return The temporary directory path on success, or NULL on failure.
230  *         Must NOT be freed.
231  */
232 const char *
233 create_tempdir(char **namebuf, const char *pfx)
234 {
235         static char *td_path[3];
236         static int td_path_len[3];
237         static int idx;
238         const char *tmp_dir;
239
240         idx = (idx + 1) % 3;
241         
242         /*
243          * Allocate the buffer if it's not already allocated.
244          */
245         if (td_path[idx] == NULL) {
246                 td_path_len[idx] = INITIAL_PATH_SIZE;
247                 td_path[idx] = (char *)g_malloc(td_path_len[idx]);
248         }
249
250         /*
251          * We can't use get_tempfile_path here because we're called from dumpcap.c.
252          */
253         tmp_dir = g_get_tmp_dir();
254
255         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]) {
256                 td_path_len[idx] *= 2;
257                 td_path[idx] = (char *)g_realloc(td_path[idx], td_path_len[idx]);
258         }
259
260         if (namebuf) {
261                 *namebuf = td_path[idx];
262         }
263         return mkdtemp(td_path[idx]);
264 }