join: prefer signed types
[coreutils.git] / src / mktemp.c
blob3ce3cf3a83fae40b9e361c2b9a21f32b99dec242
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 "filenamecat.h"
27 #include "quote.h"
28 #include "tempname.h"
30 /* The official name of this program (e.g., no 'g' prefix). */
31 #define PROGRAM_NAME "mktemp"
33 #define AUTHORS \
34 proper_name ("Jim Meyering"), \
35 proper_name ("Eric Blake")
37 static char const *default_template = "tmp.XXXXXXXXXX";
39 /* For long options that have no equivalent short option, use a
40 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
41 enum
43 SUFFIX_OPTION = CHAR_MAX + 1,
46 static struct option const longopts[] =
48 {"directory", no_argument, nullptr, 'd'},
49 {"quiet", no_argument, nullptr, 'q'},
50 {"dry-run", no_argument, nullptr, 'u'},
51 {"suffix", required_argument, nullptr, SUFFIX_OPTION},
52 {"tmpdir", optional_argument, nullptr, 'p'},
53 {GETOPT_HELP_OPTION_DECL},
54 {GETOPT_VERSION_OPTION_DECL},
55 {nullptr, 0, nullptr, 0}
58 void
59 usage (int status)
61 if (status != EXIT_SUCCESS)
62 emit_try_help ();
63 else
65 printf (_("Usage: %s [OPTION]... [TEMPLATE]\n"), program_name);
66 fputs (_("\
67 Create a temporary file or directory, safely, and print its name.\n\
68 TEMPLATE must contain at least 3 consecutive 'X's in last component.\n\
69 If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.\n\
70 "), stdout);
71 fputs (_("\
72 Files are created u+rw, and directories u+rwx, minus umask restrictions.\n\
73 "), stdout);
74 fputs ("\n", stdout);
75 fputs (_("\
76 -d, --directory create a directory, not a file\n\
77 -u, --dry-run do not create anything; merely print a name (unsafe)\n\
78 -q, --quiet suppress diagnostics about file/dir-creation failure\n\
79 "), stdout);
80 fputs (_("\
81 --suffix=SUFF append SUFF to TEMPLATE; SUFF must not contain a slash.\n\
82 This option is implied if TEMPLATE does not end in X\n\
83 "), stdout);
84 fputs (_("\
85 -p DIR, --tmpdir[=DIR] interpret TEMPLATE relative to DIR; if DIR is not\n\
86 specified, use $TMPDIR if set, else /tmp. With\n\
87 this option, TEMPLATE must not be an absolute name;\n\
88 unlike with -t, TEMPLATE may contain slashes, but\n\
89 mktemp creates only the final component\n\
90 "), stdout);
91 fputs (_("\
92 -t interpret TEMPLATE as a single file name component,\n\
93 relative to a directory: $TMPDIR, if set; else the\n\
94 directory specified via -p; else /tmp [deprecated]\n\
95 "), stdout);
96 fputs (HELP_OPTION_DESCRIPTION, stdout);
97 fputs (VERSION_OPTION_DESCRIPTION, stdout);
98 emit_ancillary_info (PROGRAM_NAME);
101 exit (status);
104 static size_t
105 count_consecutive_X_s (char const *s, size_t len)
107 size_t n = 0;
108 for ( ; len && s[len - 1] == 'X'; len--)
109 ++n;
110 return n;
113 static int
114 mkstemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
116 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_FILE,
117 x_len);
120 static int
121 mkdtemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
123 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_DIR,
124 x_len);
127 /* True if we have already closed standard output. */
128 static bool stdout_closed;
130 /* Avoid closing stdout twice. Since we conditionally call
131 close_stream (stdout) in order to decide whether to clean up a
132 temporary file, the exit hook needs to know whether to do all of
133 close_stdout or just the stderr half. */
134 static void
135 maybe_close_stdout (void)
137 if (!stdout_closed)
138 close_stdout ();
139 else if (close_stream (stderr) != 0)
140 _exit (EXIT_FAILURE);
144 main (int argc, char **argv)
146 char const *dest_dir;
147 char const *dest_dir_arg = nullptr;
148 bool suppress_file_err = false;
149 int c;
150 unsigned int n_args;
151 char *template;
152 char *suffix = nullptr;
153 bool use_dest_dir = false;
154 bool deprecated_t_option = false;
155 bool create_directory = false;
156 bool dry_run = false;
157 int status = EXIT_SUCCESS;
158 size_t x_count;
159 size_t suffix_len;
160 char *dest_name;
162 initialize_main (&argc, &argv);
163 set_program_name (argv[0]);
164 setlocale (LC_ALL, "");
165 bindtextdomain (PACKAGE, LOCALEDIR);
166 textdomain (PACKAGE);
168 atexit (maybe_close_stdout);
170 while ((c = getopt_long (argc, argv, "dp:qtuV", longopts, nullptr)) != -1)
172 switch (c)
174 case 'd':
175 create_directory = true;
176 break;
177 case 'p':
178 dest_dir_arg = optarg;
179 use_dest_dir = true;
180 break;
181 case 'q':
182 suppress_file_err = true;
183 break;
184 case 't':
185 use_dest_dir = true;
186 deprecated_t_option = true;
187 break;
188 case 'u':
189 dry_run = true;
190 break;
192 case SUFFIX_OPTION:
193 suffix = optarg;
194 break;
196 case_GETOPT_HELP_CHAR;
198 case 'V': /* Undocumented alias, for compatibility with the original
199 mktemp program. */
200 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
201 default:
202 usage (EXIT_FAILURE);
206 n_args = argc - optind;
207 if (2 <= n_args)
209 error (0, 0, _("too many templates"));
210 usage (EXIT_FAILURE);
213 if (n_args == 0)
215 use_dest_dir = true;
216 template = (char *) default_template;
218 else
220 template = argv[optind];
223 if (suffix)
225 size_t len = strlen (template);
226 if (!len || template[len - 1] != 'X')
228 error (EXIT_FAILURE, 0,
229 _("with --suffix, template %s must end in X"),
230 quote (template));
232 suffix_len = strlen (suffix);
233 dest_name = xcharalloc (len + suffix_len + 1);
234 memcpy (dest_name, template, len);
235 memcpy (dest_name + len, suffix, suffix_len + 1);
236 template = dest_name;
237 suffix = dest_name + len;
239 else
241 template = xstrdup (template);
242 suffix = strrchr (template, 'X');
243 if (!suffix)
244 suffix = strchr (template, '\0');
245 else
246 suffix++;
247 suffix_len = strlen (suffix);
250 /* At this point, template is malloc'd, and suffix points into template. */
251 if (suffix_len && last_component (suffix) != suffix)
253 error (EXIT_FAILURE, 0,
254 _("invalid suffix %s, contains directory separator"),
255 quote (suffix));
257 x_count = count_consecutive_X_s (template, suffix - template);
258 if (x_count < 3)
259 error (EXIT_FAILURE, 0, _("too few X's in template %s"), quote (template));
261 if (use_dest_dir)
263 if (deprecated_t_option)
265 char *env = getenv ("TMPDIR");
266 if (env && *env)
267 dest_dir = env;
268 else if (dest_dir_arg && *dest_dir_arg)
269 dest_dir = dest_dir_arg;
270 else
271 dest_dir = "/tmp";
273 if (last_component (template) != template)
274 error (EXIT_FAILURE, 0,
275 _("invalid template, %s, contains directory separator"),
276 quote (template));
278 else
280 if (dest_dir_arg && *dest_dir_arg)
281 dest_dir = dest_dir_arg;
282 else
284 char *env = getenv ("TMPDIR");
285 dest_dir = (env && *env ? env : "/tmp");
287 if (IS_ABSOLUTE_FILE_NAME (template))
288 error (EXIT_FAILURE, 0,
289 _("invalid template, %s; with --tmpdir,"
290 " it may not be absolute"),
291 quote (template));
294 dest_name = file_name_concat (dest_dir, template, nullptr);
295 free (template);
296 template = dest_name;
297 /* Note that suffix is now invalid. */
300 /* Make a copy to be used in case of diagnostic, since failing
301 mkstemp may leave the buffer in an undefined state. */
302 dest_name = xstrdup (template);
304 if (create_directory)
306 int err = mkdtemp_len (dest_name, suffix_len, x_count, dry_run);
307 if (err != 0)
309 if (!suppress_file_err)
310 error (0, errno, _("failed to create directory via template %s"),
311 quote (template));
312 status = EXIT_FAILURE;
315 else
317 int fd = mkstemp_len (dest_name, suffix_len, x_count, dry_run);
318 if (fd < 0 || (!dry_run && close (fd) != 0))
320 if (!suppress_file_err)
321 error (0, errno, _("failed to create file via template %s"),
322 quote (template));
323 status = EXIT_FAILURE;
327 if (status == EXIT_SUCCESS)
329 puts (dest_name);
330 /* If we created a file, but then failed to output the file
331 name, we should clean up the mess before failing. */
332 if (!dry_run && ((stdout_closed = true), close_stream (stdout) != 0))
334 int saved_errno = errno;
335 remove (dest_name);
336 if (!suppress_file_err)
337 error (0, saved_errno, _("write error"));
338 status = EXIT_FAILURE;
342 main_exit (status);