1 /* Create a temporary file or directory, safely.
2 Copyright (C) 2007-2012 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. */
20 #include <sys/types.h>
25 #include "close-stream.h"
27 #include "filenamecat.h"
32 /* The official name of this program (e.g., no 'g' prefix). */
33 #define PROGRAM_NAME "mktemp"
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. */
45 SUFFIX_OPTION
= CHAR_MAX
+ 1,
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
},
64 if (status
!= EXIT_SUCCESS
)
68 printf (_("Usage: %s [OPTION]... [TEMPLATE]\n"), program_name
);
70 Create a temporary file or directory, safely, and print its name.\n\
71 TEMPLATE must contain at least 3 consecutive 'X's in last component.\n\
72 If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.\n\
75 Files are created u+rw, and directories u+rwx, minus umask restrictions.\n\
79 -d, --directory create a directory, not a file\n\
80 -u, --dry-run do not create anything; merely print a name (unsafe)\n\
81 -q, --quiet suppress diagnostics about file/dir-creation failure\n\
84 --suffix=SUFF append SUFF to TEMPLATE. SUFF must not contain slash.\n\
85 This option is implied if TEMPLATE does not end in X.\n\
88 --tmpdir[=DIR] interpret TEMPLATE relative to DIR. If DIR is not\n\
89 specified, use $TMPDIR if set, else /tmp. With\n\
90 this option, TEMPLATE must not be an absolute name.\n\
91 Unlike with -t, TEMPLATE may contain slashes, but\n\
92 mktemp creates only the final component\n\
96 -p DIR use DIR as a prefix; implies -t [deprecated]\n\
97 -t interpret TEMPLATE as a single file name component,\n\
98 relative to a directory: $TMPDIR, if set; else the\n\
99 directory specified via -p; else /tmp [deprecated]\n\
101 fputs ("\n", stdout
);
102 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
103 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
104 emit_ancillary_info ();
111 count_consecutive_X_s (const char *s
, size_t len
)
114 for ( ; len
&& s
[len
-1] == 'X'; len
--)
120 mkstemp_len (char *tmpl
, size_t suff_len
, size_t x_len
, bool dry_run
)
122 return gen_tempname_len (tmpl
, suff_len
, 0, dry_run
? GT_NOCREATE
: GT_FILE
,
127 mkdtemp_len (char *tmpl
, size_t suff_len
, size_t x_len
, bool dry_run
)
129 return gen_tempname_len (tmpl
, suff_len
, 0, dry_run
? GT_NOCREATE
: GT_DIR
,
133 /* True if we have already closed standard output. */
134 static bool stdout_closed
;
136 /* Avoid closing stdout twice. Since we conditionally call
137 close_stream (stdout) in order to decide whether to clean up a
138 temporary file, the exit hook needs to know whether to do all of
139 close_stdout or just the stderr half. */
141 maybe_close_stdout (void)
145 else if (close_stream (stderr
) != 0)
146 _exit (EXIT_FAILURE
);
150 main (int argc
, char **argv
)
152 char const *dest_dir
;
153 char const *dest_dir_arg
= NULL
;
154 bool suppress_stderr
= false;
159 bool use_dest_dir
= false;
160 bool deprecated_t_option
= false;
161 bool create_directory
= false;
162 bool dry_run
= false;
163 int status
= EXIT_SUCCESS
;
168 initialize_main (&argc
, &argv
);
169 set_program_name (argv
[0]);
170 setlocale (LC_ALL
, "");
171 bindtextdomain (PACKAGE
, LOCALEDIR
);
172 textdomain (PACKAGE
);
174 atexit (maybe_close_stdout
);
176 while ((c
= getopt_long (argc
, argv
, "dp:qtuV", longopts
, NULL
)) != -1)
181 create_directory
= true;
184 dest_dir_arg
= optarg
;
188 suppress_stderr
= true;
192 deprecated_t_option
= true;
200 dest_dir_arg
= optarg
;
207 case_GETOPT_HELP_CHAR
;
209 case 'V': /* Undocumented alias. FIXME: remove in 2011. */
210 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
212 usage (EXIT_FAILURE
);
218 /* From here on, redirect stderr to /dev/null.
219 A diagnostic from getopt_long, above, would still go to stderr. */
220 if (!freopen ("/dev/null", "wb", stderr
))
221 error (EXIT_FAILURE
, errno
,
222 _("failed to redirect stderr to /dev/null"));
225 n_args
= argc
- optind
;
228 error (0, 0, _("too many templates"));
229 usage (EXIT_FAILURE
);
235 template = (char *) default_template
;
239 template = argv
[optind
];
244 size_t len
= strlen (template);
245 if (!len
|| template[len
- 1] != 'X')
247 error (EXIT_FAILURE
, 0,
248 _("with --suffix, template %s must end in X"),
251 suffix_len
= strlen (suffix
);
252 dest_name
= xcharalloc (len
+ suffix_len
+ 1);
253 memcpy (dest_name
, template, len
);
254 memcpy (dest_name
+ len
, suffix
, suffix_len
+ 1);
255 template = dest_name
;
256 suffix
= dest_name
+ len
;
260 template = xstrdup (template);
261 suffix
= strrchr (template, 'X');
263 suffix
= strchr (template, '\0');
266 suffix_len
= strlen (suffix
);
269 /* At this point, template is malloc'd, and suffix points into template. */
270 if (suffix_len
&& last_component (suffix
) != suffix
)
272 error (EXIT_FAILURE
, 0,
273 _("invalid suffix %s, contains directory separator"),
276 x_count
= count_consecutive_X_s (template, suffix
- template);
278 error (EXIT_FAILURE
, 0, _("too few X's in template %s"), quote (template));
282 if (deprecated_t_option
)
284 char *env
= getenv ("TMPDIR");
285 dest_dir
= (env
&& *env
287 : (dest_dir_arg
? dest_dir_arg
: "/tmp"));
289 if (last_component (template) != template)
290 error (EXIT_FAILURE
, 0,
291 _("invalid template, %s, contains directory separator"),
296 if (dest_dir_arg
&& *dest_dir_arg
)
297 dest_dir
= dest_dir_arg
;
300 char *env
= getenv ("TMPDIR");
301 dest_dir
= (env
&& *env
? env
: "/tmp");
303 if (IS_ABSOLUTE_FILE_NAME (template))
304 error (EXIT_FAILURE
, 0,
305 _("invalid template, %s; with --tmpdir,"
306 " it may not be absolute"),
310 dest_name
= file_name_concat (dest_dir
, template, NULL
);
312 template = dest_name
;
313 /* Note that suffix is now invalid. */
316 /* Make a copy to be used in case of diagnostic, since failing
317 mkstemp may leave the buffer in an undefined state. */
318 dest_name
= xstrdup (template);
320 if (create_directory
)
322 int err
= mkdtemp_len (dest_name
, suffix_len
, x_count
, dry_run
);
325 error (0, errno
, _("failed to create directory via template %s"),
327 status
= EXIT_FAILURE
;
332 int fd
= mkstemp_len (dest_name
, suffix_len
, x_count
, dry_run
);
333 if (fd
< 0 || (!dry_run
&& close (fd
) != 0))
335 error (0, errno
, _("failed to create file via template %s"),
337 status
= EXIT_FAILURE
;
341 if (status
== EXIT_SUCCESS
)
344 /* If we created a file, but then failed to output the file
345 name, we should clean up the mess before failing. */
346 if (!dry_run
&& ((stdout_closed
= true), close_stream (stdout
) != 0))
348 int saved_errno
= errno
;
350 error (EXIT_FAILURE
, saved_errno
, _("write error"));