maint: prefer C23-style nullptr
[coreutils.git] / src / mktemp.c
blob83900a2a1e4a48e6dbf1ed47152e68e158ee6184
1 /* Create a temporary file or directory, safely.
2 Copyright (C) 2007-2023 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 <https://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 "die.h"
27 #include "error.h"
28 #include "filenamecat.h"
29 #include "quote.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 char const *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,
48 static struct option const longopts[] =
50 {"directory", no_argument, nullptr, 'd'},
51 {"quiet", no_argument, nullptr, 'q'},
52 {"dry-run", no_argument, nullptr, 'u'},
53 {"suffix", required_argument, nullptr, SUFFIX_OPTION},
54 {"tmpdir", optional_argument, nullptr, 'p'},
55 {GETOPT_HELP_OPTION_DECL},
56 {GETOPT_VERSION_OPTION_DECL},
57 {nullptr, 0, nullptr, 0}
60 void
61 usage (int status)
63 if (status != EXIT_SUCCESS)
64 emit_try_help ();
65 else
67 printf (_("Usage: %s [OPTION]... [TEMPLATE]\n"), program_name);
68 fputs (_("\
69 Create a temporary file or directory, safely, and print its name.\n\
70 TEMPLATE must contain at least 3 consecutive 'X's in last component.\n\
71 If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.\n\
72 "), stdout);
73 fputs (_("\
74 Files are created u+rw, and directories u+rwx, minus umask restrictions.\n\
75 "), stdout);
76 fputs ("\n", stdout);
77 fputs (_("\
78 -d, --directory create a directory, not a file\n\
79 -u, --dry-run do not create anything; merely print a name (unsafe)\n\
80 -q, --quiet suppress diagnostics about file/dir-creation failure\n\
81 "), stdout);
82 fputs (_("\
83 --suffix=SUFF append SUFF to TEMPLATE; SUFF must not contain a slash.\n\
84 This option is implied if TEMPLATE does not end in X\n\
85 "), stdout);
86 fputs (_("\
87 -p DIR, --tmpdir[=DIR] interpret TEMPLATE relative to DIR; if DIR is not\n\
88 specified, use $TMPDIR if set, else /tmp. With\n\
89 this option, TEMPLATE must not be an absolute name;\n\
90 unlike with -t, TEMPLATE may contain slashes, but\n\
91 mktemp creates only the final component\n\
92 "), stdout);
93 fputs (_("\
94 -t interpret TEMPLATE as a single file name component,\n\
95 relative to a directory: $TMPDIR, if set; else the\n\
96 directory specified via -p; else /tmp [deprecated]\n\
97 "), stdout);
98 fputs (HELP_OPTION_DESCRIPTION, stdout);
99 fputs (VERSION_OPTION_DESCRIPTION, stdout);
100 emit_ancillary_info (PROGRAM_NAME);
103 exit (status);
106 static size_t
107 count_consecutive_X_s (char const *s, size_t len)
109 size_t n = 0;
110 for ( ; len && s[len - 1] == 'X'; len--)
111 ++n;
112 return n;
115 static int
116 mkstemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
118 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_FILE,
119 x_len);
122 static int
123 mkdtemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
125 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_DIR,
126 x_len);
129 /* True if we have already closed standard output. */
130 static bool stdout_closed;
132 /* Avoid closing stdout twice. Since we conditionally call
133 close_stream (stdout) in order to decide whether to clean up a
134 temporary file, the exit hook needs to know whether to do all of
135 close_stdout or just the stderr half. */
136 static void
137 maybe_close_stdout (void)
139 if (!stdout_closed)
140 close_stdout ();
141 else if (close_stream (stderr) != 0)
142 _exit (EXIT_FAILURE);
146 main (int argc, char **argv)
148 char const *dest_dir;
149 char const *dest_dir_arg = nullptr;
150 bool suppress_file_err = false;
151 int c;
152 unsigned int n_args;
153 char *template;
154 char *suffix = nullptr;
155 bool use_dest_dir = false;
156 bool deprecated_t_option = false;
157 bool create_directory = false;
158 bool dry_run = false;
159 int status = EXIT_SUCCESS;
160 size_t x_count;
161 size_t suffix_len;
162 char *dest_name;
164 initialize_main (&argc, &argv);
165 set_program_name (argv[0]);
166 setlocale (LC_ALL, "");
167 bindtextdomain (PACKAGE, LOCALEDIR);
168 textdomain (PACKAGE);
170 atexit (maybe_close_stdout);
172 while ((c = getopt_long (argc, argv, "dp:qtuV", longopts, nullptr)) != -1)
174 switch (c)
176 case 'd':
177 create_directory = true;
178 break;
179 case 'p':
180 dest_dir_arg = optarg;
181 use_dest_dir = true;
182 break;
183 case 'q':
184 suppress_file_err = true;
185 break;
186 case 't':
187 use_dest_dir = true;
188 deprecated_t_option = true;
189 break;
190 case 'u':
191 dry_run = true;
192 break;
194 case SUFFIX_OPTION:
195 suffix = optarg;
196 break;
198 case_GETOPT_HELP_CHAR;
200 case 'V': /* Undocumented alias, for compatibility with the original
201 mktemp program. */
202 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
203 default:
204 usage (EXIT_FAILURE);
208 n_args = argc - optind;
209 if (2 <= n_args)
211 error (0, 0, _("too many templates"));
212 usage (EXIT_FAILURE);
215 if (n_args == 0)
217 use_dest_dir = true;
218 template = (char *) default_template;
220 else
222 template = argv[optind];
225 if (suffix)
227 size_t len = strlen (template);
228 if (!len || template[len - 1] != 'X')
230 die (EXIT_FAILURE, 0,
231 _("with --suffix, template %s must end in X"),
232 quote (template));
234 suffix_len = strlen (suffix);
235 dest_name = xcharalloc (len + suffix_len + 1);
236 memcpy (dest_name, template, len);
237 memcpy (dest_name + len, suffix, suffix_len + 1);
238 template = dest_name;
239 suffix = dest_name + len;
241 else
243 template = xstrdup (template);
244 suffix = strrchr (template, 'X');
245 if (!suffix)
246 suffix = strchr (template, '\0');
247 else
248 suffix++;
249 suffix_len = strlen (suffix);
252 /* At this point, template is malloc'd, and suffix points into template. */
253 if (suffix_len && last_component (suffix) != suffix)
255 die (EXIT_FAILURE, 0,
256 _("invalid suffix %s, contains directory separator"),
257 quote (suffix));
259 x_count = count_consecutive_X_s (template, suffix - template);
260 if (x_count < 3)
261 die (EXIT_FAILURE, 0, _("too few X's in template %s"), quote (template));
263 if (use_dest_dir)
265 if (deprecated_t_option)
267 char *env = getenv ("TMPDIR");
268 if (env && *env)
269 dest_dir = env;
270 else if (dest_dir_arg && *dest_dir_arg)
271 dest_dir = dest_dir_arg;
272 else
273 dest_dir = "/tmp";
275 if (last_component (template) != template)
276 die (EXIT_FAILURE, 0,
277 _("invalid template, %s, contains directory separator"),
278 quote (template));
280 else
282 if (dest_dir_arg && *dest_dir_arg)
283 dest_dir = dest_dir_arg;
284 else
286 char *env = getenv ("TMPDIR");
287 dest_dir = (env && *env ? env : "/tmp");
289 if (IS_ABSOLUTE_FILE_NAME (template))
290 die (EXIT_FAILURE, 0,
291 _("invalid template, %s; with --tmpdir,"
292 " it may not be absolute"),
293 quote (template));
296 dest_name = file_name_concat (dest_dir, template, nullptr);
297 free (template);
298 template = dest_name;
299 /* Note that suffix is now invalid. */
302 /* Make a copy to be used in case of diagnostic, since failing
303 mkstemp may leave the buffer in an undefined state. */
304 dest_name = xstrdup (template);
306 if (create_directory)
308 int err = mkdtemp_len (dest_name, suffix_len, x_count, dry_run);
309 if (err != 0)
311 if (!suppress_file_err)
312 error (0, errno, _("failed to create directory via template %s"),
313 quote (template));
314 status = EXIT_FAILURE;
317 else
319 int fd = mkstemp_len (dest_name, suffix_len, x_count, dry_run);
320 if (fd < 0 || (!dry_run && close (fd) != 0))
322 if (!suppress_file_err)
323 error (0, errno, _("failed to create file via template %s"),
324 quote (template));
325 status = EXIT_FAILURE;
329 if (status == EXIT_SUCCESS)
331 puts (dest_name);
332 /* If we created a file, but then failed to output the file
333 name, we should clean up the mess before failing. */
334 if (!dry_run && ((stdout_closed = true), close_stream (stdout) != 0))
336 int saved_errno = errno;
337 remove (dest_name);
338 if (!suppress_file_err)
339 error (0, saved_errno, _("write error"));
340 status = EXIT_FAILURE;
344 main_exit (status);