fiemap copy: don't let write failure go unreported; adjust style, etc.
[coreutils.git] / src / mktemp.c
blobc6d0e58ec1af5ec3457d0093e9c43ed5ffeb35b2
1 /* Create a temporary file or directory, safely.
2 Copyright (C) 2007-2011 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Jim Meyering and Eric Blake. */
19 #include <config.h>
20 #include <sys/types.h>
21 #include <getopt.h>
23 #include "system.h"
25 #include "close-stream.h"
26 #include "error.h"
27 #include "filenamecat.h"
28 #include "quote.h"
29 #include "stdio--.h"
30 #include "tempname.h"
32 /* The official name of this program (e.g., no `g' prefix). */
33 #define PROGRAM_NAME "mktemp"
35 #define AUTHORS \
36 proper_name ("Jim Meyering"), \
37 proper_name ("Eric Blake")
39 static const char *default_template = "tmp.XXXXXXXXXX";
41 /* For long options that have no equivalent short option, use a
42 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
43 enum
45 SUFFIX_OPTION = CHAR_MAX + 1,
46 TMPDIR_OPTION
49 static struct option const longopts[] =
51 {"directory", no_argument, NULL, 'd'},
52 {"quiet", no_argument, NULL, 'q'},
53 {"dry-run", no_argument, NULL, 'u'},
54 {"suffix", required_argument, NULL, SUFFIX_OPTION},
55 {"tmpdir", optional_argument, NULL, TMPDIR_OPTION},
56 {GETOPT_HELP_OPTION_DECL},
57 {GETOPT_VERSION_OPTION_DECL},
58 {NULL, 0, NULL, 0}
61 void
62 usage (int status)
64 if (status != EXIT_SUCCESS)
65 fprintf (stderr, _("Try `%s --help' for more information.\n"),
66 program_name);
67 else
69 printf (_("Usage: %s [OPTION]... [TEMPLATE]\n"), program_name);
70 fputs (_("\
71 Create a temporary file or directory, safely, and print its name.\n\
72 TEMPLATE must contain at least 3 consecutive `X's in last component.\n\
73 If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.\n\
74 "), stdout);
75 fputs ("\n", stdout);
76 fputs (_("\
77 -d, --directory create a directory, not a file\n\
78 -u, --dry-run do not create anything; merely print a name (unsafe)\n\
79 -q, --quiet suppress diagnostics about file/dir-creation failure\n\
80 "), stdout);
81 fputs (_("\
82 --suffix=SUFF append SUFF to TEMPLATE. SUFF must not contain slash.\n\
83 This option is implied if TEMPLATE does not end in X.\n\
84 "), stdout);
85 fputs (_("\
86 --tmpdir[=DIR] interpret TEMPLATE relative to DIR. If DIR is not\n\
87 specified, use $TMPDIR if set, else /tmp. With\n\
88 this option, TEMPLATE must not be an absolute name.\n\
89 Unlike with -t, TEMPLATE may contain slashes, but\n\
90 mktemp creates only the final component\n\
91 "), stdout);
92 fputs ("\n", stdout);
93 fputs (_("\
94 -p DIR use DIR as a prefix; implies -t [deprecated]\n\
95 -t interpret TEMPLATE as a single file name component,\n\
96 relative to a directory: $TMPDIR, if set; else the\n\
97 directory specified via -p; else /tmp [deprecated]\n\
98 "), stdout);
99 fputs ("\n", stdout);
100 fputs (HELP_OPTION_DESCRIPTION, stdout);
101 fputs (VERSION_OPTION_DESCRIPTION, stdout);
102 emit_ancillary_info ();
105 exit (status);
108 static size_t
109 count_consecutive_X_s (const char *s, size_t len)
111 size_t n = 0;
112 for ( ; len && s[len-1] == 'X'; len--)
113 ++n;
114 return n;
117 static int
118 mkstemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
120 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_FILE,
121 x_len);
124 static int
125 mkdtemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
127 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_DIR,
128 x_len);
131 /* True if we have already closed standard output. */
132 static bool stdout_closed;
134 /* Avoid closing stdout twice. Since we conditionally call
135 close_stream (stdout) in order to decide whether to clean up a
136 temporary file, the exit hook needs to know whether to do all of
137 close_stdout or just the stderr half. */
138 static void
139 maybe_close_stdout (void)
141 if (!stdout_closed)
142 close_stdout ();
143 else if (close_stream (stderr) != 0)
144 _exit (EXIT_FAILURE);
148 main (int argc, char **argv)
150 char const *dest_dir;
151 char const *dest_dir_arg = NULL;
152 bool suppress_stderr = false;
153 int c;
154 unsigned int n_args;
155 char *template;
156 char *suffix = NULL;
157 bool use_dest_dir = false;
158 bool deprecated_t_option = false;
159 bool create_directory = false;
160 bool dry_run = false;
161 int status = EXIT_SUCCESS;
162 size_t x_count;
163 size_t suffix_len;
164 char *dest_name;
166 initialize_main (&argc, &argv);
167 set_program_name (argv[0]);
168 setlocale (LC_ALL, "");
169 bindtextdomain (PACKAGE, LOCALEDIR);
170 textdomain (PACKAGE);
172 atexit (maybe_close_stdout);
174 while ((c = getopt_long (argc, argv, "dp:qtuV", longopts, NULL)) != -1)
176 switch (c)
178 case 'd':
179 create_directory = true;
180 break;
181 case 'p':
182 dest_dir_arg = optarg;
183 use_dest_dir = true;
184 break;
185 case 'q':
186 suppress_stderr = true;
187 break;
188 case 't':
189 use_dest_dir = true;
190 deprecated_t_option = true;
191 break;
192 case 'u':
193 dry_run = true;
194 break;
196 case TMPDIR_OPTION:
197 use_dest_dir = true;
198 dest_dir_arg = optarg;
199 break;
201 case SUFFIX_OPTION:
202 suffix = optarg;
203 break;
205 case_GETOPT_HELP_CHAR;
207 case 'V': /* Undocumented alias. FIXME: remove in 2011. */
208 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
209 default:
210 usage (EXIT_FAILURE);
214 if (suppress_stderr)
216 /* From here on, redirect stderr to /dev/null.
217 A diagnostic from getopt_long, above, would still go to stderr. */
218 if (!freopen ("/dev/null", "wb", stderr))
219 error (EXIT_FAILURE, errno,
220 _("failed to redirect stderr to /dev/null"));
223 n_args = argc - optind;
224 if (2 <= n_args)
226 error (0, 0, _("too many templates"));
227 usage (EXIT_FAILURE);
230 if (n_args == 0)
232 use_dest_dir = true;
233 template = (char *) default_template;
235 else
237 template = argv[optind];
240 if (suffix)
242 size_t len = strlen (template);
243 if (!len || template[len - 1] != 'X')
245 error (EXIT_FAILURE, 0,
246 _("with --suffix, template %s must end in X"),
247 quote (template));
249 suffix_len = strlen (suffix);
250 dest_name = xcharalloc (len + suffix_len + 1);
251 memcpy (dest_name, template, len);
252 memcpy (dest_name + len, suffix, suffix_len + 1);
253 template = dest_name;
254 suffix = dest_name + len;
256 else
258 template = xstrdup (template);
259 suffix = strrchr (template, 'X');
260 if (!suffix)
261 suffix = strchr (template, '\0');
262 else
263 suffix++;
264 suffix_len = strlen (suffix);
267 /* At this point, template is malloc'd, and suffix points into template. */
268 if (suffix_len && last_component (suffix) != suffix)
270 error (EXIT_FAILURE, 0,
271 _("invalid suffix %s, contains directory separator"),
272 quote (suffix));
274 x_count = count_consecutive_X_s (template, suffix - template);
275 if (x_count < 3)
276 error (EXIT_FAILURE, 0, _("too few X's in template %s"), quote (template));
278 if (use_dest_dir)
280 if (deprecated_t_option)
282 char *env = getenv ("TMPDIR");
283 dest_dir = (env && *env
284 ? env
285 : (dest_dir_arg ? dest_dir_arg : "/tmp"));
287 if (last_component (template) != template)
288 error (EXIT_FAILURE, 0,
289 _("invalid template, %s, contains directory separator"),
290 quote (template));
292 else
294 if (dest_dir_arg && *dest_dir_arg)
295 dest_dir = dest_dir_arg;
296 else
298 char *env = getenv ("TMPDIR");
299 dest_dir = (env && *env ? env : "/tmp");
301 if (IS_ABSOLUTE_FILE_NAME (template))
302 error (EXIT_FAILURE, 0,
303 _("invalid template, %s; with --tmpdir,"
304 " it may not be absolute"),
305 quote (template));
308 dest_name = file_name_concat (dest_dir, template, NULL);
309 free (template);
310 template = dest_name;
311 /* Note that suffix is now invalid. */
314 /* Make a copy to be used in case of diagnostic, since failing
315 mkstemp may leave the buffer in an undefined state. */
316 dest_name = xstrdup (template);
318 if (create_directory)
320 int err = mkdtemp_len (dest_name, suffix_len, x_count, dry_run);
321 if (err != 0)
323 error (0, errno, _("failed to create directory via template %s"),
324 quote (template));
325 status = EXIT_FAILURE;
328 else
330 int fd = mkstemp_len (dest_name, suffix_len, x_count, dry_run);
331 if (fd < 0 || (!dry_run && close (fd) != 0))
333 error (0, errno, _("failed to create file via template %s"),
334 quote (template));
335 status = EXIT_FAILURE;
339 if (status == EXIT_SUCCESS)
341 puts (dest_name);
342 /* If we created a file, but then failed to output the file
343 name, we should clean up the mess before failing. */
344 if (!dry_run && (stdout_closed = true) && close_stream (stdout) != 0)
346 int saved_errno = errno;
347 remove (dest_name);
348 error (EXIT_FAILURE, saved_errno, _("write error"));
352 #ifdef lint
353 free (dest_name);
354 free (template);
355 #endif
357 exit (status);