tests: adjust memory limits in head-c.sh
[coreutils.git] / src / mktemp.c
blobd2e126d68682f0c71c262aae99cee5564b37ee8d
1 /* Create a temporary file or directory, safely.
2 Copyright (C) 2007-2016 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 "tempname.h"
31 /* The official name of this program (e.g., no 'g' prefix). */
32 #define PROGRAM_NAME "mktemp"
34 #define AUTHORS \
35 proper_name ("Jim Meyering"), \
36 proper_name ("Eric Blake")
38 static const char *default_template = "tmp.XXXXXXXXXX";
40 /* For long options that have no equivalent short option, use a
41 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
42 enum
44 SUFFIX_OPTION = CHAR_MAX + 1,
47 static struct option const longopts[] =
49 {"directory", no_argument, NULL, 'd'},
50 {"quiet", no_argument, NULL, 'q'},
51 {"dry-run", no_argument, NULL, 'u'},
52 {"suffix", required_argument, NULL, SUFFIX_OPTION},
53 {"tmpdir", optional_argument, NULL, 'p'},
54 {GETOPT_HELP_OPTION_DECL},
55 {GETOPT_VERSION_OPTION_DECL},
56 {NULL, 0, NULL, 0}
59 void
60 usage (int status)
62 if (status != EXIT_SUCCESS)
63 emit_try_help ();
64 else
66 printf (_("Usage: %s [OPTION]... [TEMPLATE]\n"), program_name);
67 fputs (_("\
68 Create a temporary file or directory, safely, and print its name.\n\
69 TEMPLATE must contain at least 3 consecutive 'X's in last component.\n\
70 If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.\n\
71 "), stdout);
72 fputs (_("\
73 Files are created u+rw, and directories u+rwx, minus umask restrictions.\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 a slash.\n\
83 This option is implied if TEMPLATE does not end in X\n\
84 "), stdout);
85 fputs (_("\
86 -p DIR, --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 (_("\
93 -t interpret TEMPLATE as a single file name component,\n\
94 relative to a directory: $TMPDIR, if set; else the\n\
95 directory specified via -p; else /tmp [deprecated]\n\
96 "), stdout);
97 fputs (HELP_OPTION_DESCRIPTION, stdout);
98 fputs (VERSION_OPTION_DESCRIPTION, stdout);
99 emit_ancillary_info (PROGRAM_NAME);
102 exit (status);
105 static size_t
106 count_consecutive_X_s (const char *s, size_t len)
108 size_t n = 0;
109 for ( ; len && s[len-1] == 'X'; len--)
110 ++n;
111 return n;
114 static int
115 mkstemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
117 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_FILE,
118 x_len);
121 static int
122 mkdtemp_len (char *tmpl, size_t suff_len, size_t x_len, bool dry_run)
124 return gen_tempname_len (tmpl, suff_len, 0, dry_run ? GT_NOCREATE : GT_DIR,
125 x_len);
128 /* True if we have already closed standard output. */
129 static bool stdout_closed;
131 /* Avoid closing stdout twice. Since we conditionally call
132 close_stream (stdout) in order to decide whether to clean up a
133 temporary file, the exit hook needs to know whether to do all of
134 close_stdout or just the stderr half. */
135 static void
136 maybe_close_stdout (void)
138 if (!stdout_closed)
139 close_stdout ();
140 else if (close_stream (stderr) != 0)
141 _exit (EXIT_FAILURE);
145 main (int argc, char **argv)
147 char const *dest_dir;
148 char const *dest_dir_arg = NULL;
149 bool suppress_file_err = false;
150 int c;
151 unsigned int n_args;
152 char *template;
153 char *suffix = NULL;
154 bool use_dest_dir = false;
155 bool deprecated_t_option = false;
156 bool create_directory = false;
157 bool dry_run = false;
158 int status = EXIT_SUCCESS;
159 size_t x_count;
160 size_t suffix_len;
161 char *dest_name;
163 initialize_main (&argc, &argv);
164 set_program_name (argv[0]);
165 setlocale (LC_ALL, "");
166 bindtextdomain (PACKAGE, LOCALEDIR);
167 textdomain (PACKAGE);
169 atexit (maybe_close_stdout);
171 while ((c = getopt_long (argc, argv, "dp:qtuV", longopts, NULL)) != -1)
173 switch (c)
175 case 'd':
176 create_directory = true;
177 break;
178 case 'p':
179 dest_dir_arg = optarg;
180 use_dest_dir = true;
181 break;
182 case 'q':
183 suppress_file_err = true;
184 break;
185 case 't':
186 use_dest_dir = true;
187 deprecated_t_option = true;
188 break;
189 case 'u':
190 dry_run = true;
191 break;
193 case SUFFIX_OPTION:
194 suffix = optarg;
195 break;
197 case_GETOPT_HELP_CHAR;
199 case 'V': /* Undocumented alias, for compatibility with the original
200 mktemp program. */
201 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
202 default:
203 usage (EXIT_FAILURE);
207 n_args = argc - optind;
208 if (2 <= n_args)
210 error (0, 0, _("too many templates"));
211 usage (EXIT_FAILURE);
214 if (n_args == 0)
216 use_dest_dir = true;
217 template = (char *) default_template;
219 else
221 template = argv[optind];
224 if (suffix)
226 size_t len = strlen (template);
227 if (!len || template[len - 1] != 'X')
229 error (EXIT_FAILURE, 0,
230 _("with --suffix, template %s must end in X"),
231 quote (template));
233 suffix_len = strlen (suffix);
234 dest_name = xcharalloc (len + suffix_len + 1);
235 memcpy (dest_name, template, len);
236 memcpy (dest_name + len, suffix, suffix_len + 1);
237 template = dest_name;
238 suffix = dest_name + len;
240 else
242 template = xstrdup (template);
243 suffix = strrchr (template, 'X');
244 if (!suffix)
245 suffix = strchr (template, '\0');
246 else
247 suffix++;
248 suffix_len = strlen (suffix);
251 /* At this point, template is malloc'd, and suffix points into template. */
252 if (suffix_len && last_component (suffix) != suffix)
254 error (EXIT_FAILURE, 0,
255 _("invalid suffix %s, contains directory separator"),
256 quote (suffix));
258 x_count = count_consecutive_X_s (template, suffix - template);
259 if (x_count < 3)
260 error (EXIT_FAILURE, 0, _("too few X's in template %s"), quote (template));
262 if (use_dest_dir)
264 if (deprecated_t_option)
266 char *env = getenv ("TMPDIR");
267 if (env && *env)
268 dest_dir = env;
269 else if (dest_dir_arg && *dest_dir_arg)
270 dest_dir = dest_dir_arg;
271 else
272 dest_dir = "/tmp";
274 if (last_component (template) != template)
275 error (EXIT_FAILURE, 0,
276 _("invalid template, %s, contains directory separator"),
277 quote (template));
279 else
281 if (dest_dir_arg && *dest_dir_arg)
282 dest_dir = dest_dir_arg;
283 else
285 char *env = getenv ("TMPDIR");
286 dest_dir = (env && *env ? env : "/tmp");
288 if (IS_ABSOLUTE_FILE_NAME (template))
289 error (EXIT_FAILURE, 0,
290 _("invalid template, %s; with --tmpdir,"
291 " it may not be absolute"),
292 quote (template));
295 dest_name = file_name_concat (dest_dir, template, NULL);
296 free (template);
297 template = dest_name;
298 /* Note that suffix is now invalid. */
301 /* Make a copy to be used in case of diagnostic, since failing
302 mkstemp may leave the buffer in an undefined state. */
303 dest_name = xstrdup (template);
305 if (create_directory)
307 int err = mkdtemp_len (dest_name, suffix_len, x_count, dry_run);
308 if (err != 0)
310 if (!suppress_file_err)
311 error (0, errno, _("failed to create directory via template %s"),
312 quote (template));
313 status = EXIT_FAILURE;
316 else
318 int fd = mkstemp_len (dest_name, suffix_len, x_count, dry_run);
319 if (fd < 0 || (!dry_run && close (fd) != 0))
321 if (!suppress_file_err)
322 error (0, errno, _("failed to create file via template %s"),
323 quote (template));
324 status = EXIT_FAILURE;
328 if (status == EXIT_SUCCESS)
330 puts (dest_name);
331 /* If we created a file, but then failed to output the file
332 name, we should clean up the mess before failing. */
333 if (!dry_run && ((stdout_closed = true), close_stream (stdout) != 0))
335 int saved_errno = errno;
336 remove (dest_name);
337 if (!suppress_file_err)
338 error (0, saved_errno, _("write error"));
339 status = EXIT_FAILURE;
343 #ifdef lint
344 free (dest_name);
345 free (template);
346 #endif
348 return status;