summaryrefslogtreecommitdiff
path: root/src/mktemp.c
blob: 6f12d994784ee2170c1592220380b2dd575570e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/* Create a temporary file or directory, safely.
   Copyright (C) 2007-2008 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

/* Jim Meyering */

#include <config.h>
#include <stdio.h>
#include <sys/types.h>
#include <getopt.h>

#include "system.h"

#include "error.h"
#include "filenamecat.h"
#include "quote.h"
#include "tempname.h"

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "mktemp"

#define AUTHORS "Jim Meyering"

static const char *default_template = "tmp.XXXXXXXXXX";

/* The name this program was run with. */
char *program_name;

/* For long options that have no equivalent short option, use a
   non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
enum
{
  TMPDIR_OPTION = CHAR_MAX + 1
};

static struct option const longopts[] =
{
  {"directory", no_argument, NULL, 'd'},
  {"quiet", no_argument, NULL, 'q'},
  {"dry-run", no_argument, NULL, 'u'},
  {"tmpdir", optional_argument, NULL, TMPDIR_OPTION},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {NULL, 0, NULL, 0}
};

void
usage (int status)
{
  if (status != EXIT_SUCCESS)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
             program_name);
  else
    {
      printf (_("Usage: %s [OPTION]... [TEMPLATE]\n"), program_name);
      fputs (_("\
Create a temporary file or directory, safely, and print its name.\n\
If TEMPLATE is not specified, use tmp.XXXXXXXXXX.\n\
"), stdout);
      fputs ("\n", stdout);
      fputs (_("\
  -d, --directory  create a directory, not a file\n\
"), stdout);
      fputs (_("\
  -q, --quiet      suppress diagnostics about file/dir-creation failure\n\
"), stdout);
      fputs (_("\
  -u, --dry-run    do not create anything; merely print a name (unsafe)\n\
"), stdout);
      fputs (_("\
  --tmpdir[=DIR]   interpret TEMPLATE relative to DIR.  If DIR is\n\
                     not specified, use $TMPDIR if set, else /tmp.\n\
                     With this option, TEMPLATE must not be an absolute name.\n\
                     Unlike with -t, TEMPLATE may contain slashes, but even\n\
                     here, mktemp still creates only the final component.\n\
"), stdout);
      fputs ("\n", stdout);
      fputs (_("\
  -p DIR           use DIR as a prefix; implies -t [deprecated]\n\
"), stdout);
      fputs (_("\
  -t               interpret TEMPLATE as a single file name component,\n\
                     relative to a directory: $TMPDIR, if set; else the\n\
                     directory specified via -p; else /tmp [deprecated]\n\
"), stdout);
      fputs ("\n", stdout);
      fputs (HELP_OPTION_DESCRIPTION, stdout);
      fputs (VERSION_OPTION_DESCRIPTION, stdout);
      emit_bug_reporting_address ();
    }

  exit (status);
}

static size_t
count_trailing_X_s (const char *s)
{
  size_t len = strlen (s);
  size_t n = 0;
  for ( ; len && s[len-1] == 'X'; len--)
    ++n;
  return n;
}

static int
mkstemp_len (char *tmpl, size_t suff_len, bool dry_run)
{
  return gen_tempname_len (tmpl, dry_run ? GT_NOCREATE : GT_FILE, suff_len);
}

static int
mkdtemp_len (char *tmpl, size_t suff_len, bool dry_run)
{
  return gen_tempname_len (tmpl, dry_run ? GT_NOCREATE : GT_DIR, suff_len);
}

int
main (int argc, char **argv)
{
  char *dest_dir;
  char *dest_dir_arg = NULL;
  bool suppress_stderr = false;
  int c;
  unsigned int n_args;
  char *template;
  bool use_dest_dir = false;
  bool deprecated_t_option = false;
  bool create_directory = false;
  bool dry_run = false;
  int status = EXIT_SUCCESS;
  size_t x_count;
  char *dest_name;

  initialize_main (&argc, &argv);
  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  atexit (close_stdout);

  while ((c = getopt_long (argc, argv, "dp:qtuV", longopts, NULL)) != -1)
    {
      switch (c)
        {
        case 'd':
          create_directory = true;
          break;
        case 'p':
          dest_dir_arg = optarg;
          use_dest_dir = true;
          break;
        case 'q':
          suppress_stderr = true;
          break;
        case 't':
          use_dest_dir = true;
          deprecated_t_option = true;
          break;
        case 'u':
          dry_run = true;
          break;

        case TMPDIR_OPTION:
          use_dest_dir = true;
          dest_dir_arg = optarg;
          break;

        case_GETOPT_HELP_CHAR;

        case 'V':
        case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
        default:
          usage (EXIT_FAILURE);
        }
    }

  if (suppress_stderr)
    {
      /* From here on, redirect stderr to /dev/null.
         A diagnostic from getopt_long, above, would still go to stderr.  */
      freopen ("/dev/null", "wb", stderr);
    }

  n_args = argc - optind;
  if (2 <= n_args)
    {
      error (0, 0, _("too many templates"));
      usage (EXIT_FAILURE);
    }

  if (n_args == 0)
    {
      use_dest_dir = true;
      template = (char *) default_template;
    }
  else
    {
      template = argv[optind];
    }

  x_count = count_trailing_X_s (template);
  if (x_count < 3)
    error (EXIT_FAILURE, 0, _("too few X's in template %s"), quote (template));

  if (use_dest_dir)
    {
      if (deprecated_t_option)
        {
          char *env = getenv ("TMPDIR");
          dest_dir = (env && *env
                      ? env
                      : (dest_dir_arg ? dest_dir_arg : "/tmp"));

          if (last_component (template) != template)
            error (EXIT_FAILURE, 0,
                   _("invalid template, %s, contains directory separator"),
                   quote (template));
        }
      else
        {
          if (dest_dir_arg && *dest_dir_arg)
            dest_dir = dest_dir_arg;
          else
            {
              char *env = getenv ("TMPDIR");
              dest_dir = (env && *env ? env : "/tmp");
            }
          if (IS_ABSOLUTE_FILE_NAME (template))
            error (EXIT_FAILURE, 0,
                   _("invalid template, %s; with --tmpdir,"
                     " it may not be absolute"),
                   quote (template));
        }

      dest_name = file_name_concat (dest_dir, template, NULL);
    }
  else
    {
      dest_name = xstrdup (template);
    }

  if (create_directory)
    {
      int err = mkdtemp_len (dest_name, x_count, dry_run);
      if (err != 0)
        {
          error (0, errno, _("failed to create directory via template %s"),
                 quote (dest_name));
          status = EXIT_FAILURE;
        }
    }
  else
    {
      int fd = mkstemp_len (dest_name, x_count, dry_run);
      if (fd < 0 || (!dry_run && close (fd) != 0))
        {
          error (0, errno, _("failed to create file via template %s"),
                 quote (dest_name));
          status = EXIT_FAILURE;
        }
    }

  if (status == EXIT_SUCCESS)
    puts (dest_name);

#ifdef lint
  free (dest_name);
#endif

  exit (status);
}

/*
 * Local variables:
 *  indent-tabs-mode: nil
 * End:
 */