id: fix infinite loop on some systems
[coreutils/ericb.git] / src / touch.c
blob3d6d9fac26becae106eb63a0b2dfba821bcacf26
1 /* touch -- change modification and access times of files
2 Copyright (C) 87, 1989-1991, 1995-2005, 2007-2009
3 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* Written by Paul Rubin, Arnold Robbins, Jim Kingdon, David MacKenzie,
19 and Randy Smith. */
21 #include <config.h>
22 #include <stdio.h>
23 #include <getopt.h>
24 #include <sys/types.h>
26 #include "system.h"
27 #include "argmatch.h"
28 #include "error.h"
29 #include "fd-reopen.h"
30 #include "getdate.h"
31 #include "posixtm.h"
32 #include "posixver.h"
33 #include "quote.h"
34 #include "stat-time.h"
35 #include "utimens.h"
37 /* The official name of this program (e.g., no `g' prefix). */
38 #define PROGRAM_NAME "touch"
40 #define AUTHORS \
41 proper_name ("Paul Rubin"), \
42 proper_name ("Arnold Robbins"), \
43 proper_name ("Jim Kingdon"), \
44 proper_name ("David MacKenzie"), \
45 proper_name ("Randy Smith")
47 /* Bitmasks for `change_times'. */
48 #define CH_ATIME 1
49 #define CH_MTIME 2
51 /* Which timestamps to change. */
52 static int change_times;
54 /* (-c) If true, don't create if not already there. */
55 static bool no_create;
57 /* (-r) If true, use times from a reference file. */
58 static bool use_ref;
60 /* If true, the only thing we have to do is change both the
61 modification and access time to the current time, so we don't
62 have to own the file, just be able to read and write it.
63 On some systems, we can do this if we own the file, even though
64 we have neither read nor write access to it. */
65 static bool amtime_now;
67 /* New access and modification times to use when setting time. */
68 static struct timespec newtime[2];
70 /* File to use for -r. */
71 static char *ref_file;
73 /* For long options that have no equivalent short option, use a
74 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
75 enum
77 TIME_OPTION = CHAR_MAX + 1
80 static struct option const longopts[] =
82 {"time", required_argument, NULL, TIME_OPTION},
83 {"no-create", no_argument, NULL, 'c'},
84 {"date", required_argument, NULL, 'd'},
85 {"file", required_argument, NULL, 'r'}, /* FIXME: remove --file in 2010 */
86 {"reference", required_argument, NULL, 'r'},
87 {GETOPT_HELP_OPTION_DECL},
88 {GETOPT_VERSION_OPTION_DECL},
89 {NULL, 0, NULL, 0}
92 /* Valid arguments to the `--time' option. */
93 static char const* const time_args[] =
95 "atime", "access", "use", "mtime", "modify", NULL
98 /* The bits in `change_times' that those arguments set. */
99 static int const time_masks[] =
101 CH_ATIME, CH_ATIME, CH_ATIME, CH_MTIME, CH_MTIME
104 /* Store into *RESULT the result of interpreting FLEX_DATE as a date,
105 relative to NOW. If NOW is null, use the current time. */
107 static void
108 get_reldate (struct timespec *result,
109 char const *flex_date, struct timespec const *now)
111 if (! get_date (result, flex_date, now))
112 error (EXIT_FAILURE, 0, _("invalid date format %s"), quote (flex_date));
115 /* Update the time of file FILE according to the options given.
116 Return true if successful. */
118 static bool
119 touch (const char *file)
121 bool ok;
122 struct stat sbuf;
123 int fd = -1;
124 int open_errno = 0;
125 struct timespec timespec[2];
126 struct timespec const *t;
128 if (STREQ (file, "-"))
129 fd = STDOUT_FILENO;
130 else if (! no_create)
132 /* Try to open FILE, creating it if necessary. */
133 fd = fd_reopen (STDIN_FILENO, file,
134 O_WRONLY | O_CREAT | O_NONBLOCK | O_NOCTTY,
135 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
137 /* Don't save a copy of errno if it's EISDIR, since that would lead
138 touch to give a bogus diagnostic for e.g., `touch /' (assuming
139 we don't own / or have write access to it). On Solaris 5.6,
140 and probably other systems, it is EINVAL. On SunOS4, it's EPERM. */
141 if (fd == -1 && errno != EISDIR && errno != EINVAL && errno != EPERM)
142 open_errno = errno;
145 if (change_times != (CH_ATIME | CH_MTIME))
147 /* We're setting only one of the time values. stat the target to get
148 the other one. If we have the file descriptor already, use fstat.
149 Otherwise, either we're in no-create mode (and hence didn't call open)
150 or FILE is inaccessible or a directory, so we have to use stat. */
151 if (fd != -1 ? fstat (fd, &sbuf) : stat (file, &sbuf))
153 if (open_errno)
154 error (0, open_errno, _("creating %s"), quote (file));
155 else
157 if (no_create && (errno == ENOENT || errno == EBADF))
158 return true;
159 error (0, errno, _("failed to get attributes of %s"),
160 quote (file));
162 if (fd == STDIN_FILENO)
163 close (fd);
164 return false;
168 if (amtime_now)
170 /* Pass NULL to futimens so it will not fail if we have
171 write access to the file, but don't own it. */
172 t = NULL;
174 else
176 timespec[0] = (change_times & CH_ATIME
177 ? newtime[0]
178 : get_stat_atime (&sbuf));
179 timespec[1] = (change_times & CH_MTIME
180 ? newtime[1]
181 : get_stat_mtime (&sbuf));
182 t = timespec;
185 ok = (gl_futimens (fd, (fd == STDOUT_FILENO ? NULL : file), t) == 0);
187 if (fd == STDIN_FILENO)
189 if (close (STDIN_FILENO) != 0)
191 error (0, errno, _("closing %s"), quote (file));
192 return false;
195 else if (fd == STDOUT_FILENO)
197 /* Do not diagnose "touch -c - >&-". */
198 if (!ok && errno == EBADF && no_create
199 && change_times == (CH_ATIME | CH_MTIME))
200 return true;
203 if (!ok)
205 if (open_errno)
207 /* The wording of this diagnostic should cover at least two cases:
208 - the file does not exist, but the parent directory is unwritable
209 - the file exists, but it isn't writable
210 I think it's not worth trying to distinguish them. */
211 error (0, open_errno, _("cannot touch %s"), quote (file));
213 else
215 if (no_create && errno == ENOENT)
216 return true;
217 error (0, errno, _("setting times of %s"), quote (file));
219 return false;
222 return true;
225 void
226 usage (int status)
228 if (status != EXIT_SUCCESS)
229 fprintf (stderr, _("Try `%s --help' for more information.\n"),
230 program_name);
231 else
233 printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
234 fputs (_("\
235 Update the access and modification times of each FILE to the current time.\n\
237 A FILE argument that does not exist is created empty.\n\
239 A FILE argument string of - is handled specially and causes touch to\n\
240 change the times of the file associated with standard output.\n\
242 "), stdout);
243 fputs (_("\
244 Mandatory arguments to long options are mandatory for short options too.\n\
245 "), stdout);
246 fputs (_("\
247 -a change only the access time\n\
248 -c, --no-create do not create any files\n\
249 -d, --date=STRING parse STRING and use it instead of current time\n\
250 -f (ignored)\n\
251 -m change only the modification time\n\
252 "), stdout);
253 fputs (_("\
254 -r, --reference=FILE use this file's times instead of current time\n\
255 -t STAMP use [[CC]YY]MMDDhhmm[.ss] instead of current time\n\
256 --time=WORD change the specified time:\n\
257 WORD is access, atime, or use: equivalent to -a\n\
258 WORD is modify or mtime: equivalent to -m\n\
259 "), stdout);
260 fputs (HELP_OPTION_DESCRIPTION, stdout);
261 fputs (VERSION_OPTION_DESCRIPTION, stdout);
262 fputs (_("\
264 Note that the -d and -t options accept different time-date formats.\n\
265 "), stdout);
266 emit_bug_reporting_address ();
268 exit (status);
272 main (int argc, char **argv)
274 int c;
275 bool date_set = false;
276 bool ok = true;
277 char const *flex_date = NULL;
278 int long_idx; /* FIXME: remove in 2010, when --file is removed */
280 initialize_main (&argc, &argv);
281 set_program_name (argv[0]);
282 setlocale (LC_ALL, "");
283 bindtextdomain (PACKAGE, LOCALEDIR);
284 textdomain (PACKAGE);
286 atexit (close_stdout);
288 change_times = 0;
289 no_create = use_ref = false;
291 while ((c = getopt_long (argc, argv, "acd:fmr:t:", longopts, &long_idx)) != -1)
293 switch (c)
295 case 'a':
296 change_times |= CH_ATIME;
297 break;
299 case 'c':
300 no_create = true;
301 break;
303 case 'd':
304 flex_date = optarg;
305 break;
307 case 'f':
308 break;
310 case 'm':
311 change_times |= CH_MTIME;
312 break;
314 case 'r':
315 if (long_idx == 3)
316 error (0, 0,
317 _("warning: the --%s option is obsolete; use --reference"),
318 longopts[long_idx].name);
319 use_ref = true;
320 ref_file = optarg;
321 break;
323 case 't':
324 if (! posixtime (&newtime[0].tv_sec, optarg,
325 PDS_LEADING_YEAR | PDS_CENTURY | PDS_SECONDS))
326 error (EXIT_FAILURE, 0, _("invalid date format %s"),
327 quote (optarg));
328 newtime[0].tv_nsec = 0;
329 newtime[1] = newtime[0];
330 date_set = true;
331 break;
333 case TIME_OPTION: /* --time */
334 change_times |= XARGMATCH ("--time", optarg,
335 time_args, time_masks);
336 break;
338 case_GETOPT_HELP_CHAR;
340 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
342 default:
343 usage (EXIT_FAILURE);
347 if (change_times == 0)
348 change_times = CH_ATIME | CH_MTIME;
350 if (date_set && (use_ref || flex_date))
352 error (0, 0, _("cannot specify times from more than one source"));
353 usage (EXIT_FAILURE);
356 if (use_ref)
358 struct stat ref_stats;
359 if (stat (ref_file, &ref_stats))
360 error (EXIT_FAILURE, errno,
361 _("failed to get attributes of %s"), quote (ref_file));
362 newtime[0] = get_stat_atime (&ref_stats);
363 newtime[1] = get_stat_mtime (&ref_stats);
364 date_set = true;
365 if (flex_date)
367 if (change_times & CH_ATIME)
368 get_reldate (&newtime[0], flex_date, &newtime[0]);
369 if (change_times & CH_MTIME)
370 get_reldate (&newtime[1], flex_date, &newtime[1]);
373 else
375 if (flex_date)
377 struct timespec now;
378 gettime (&now);
379 get_reldate (&newtime[0], flex_date, &now);
380 newtime[1] = newtime[0];
381 date_set = true;
383 /* If neither -a nor -m is specified, treat "-d now" as if
384 it were absent; this lets "touch" succeed more often in
385 the presence of restrictive permissions. */
386 if (change_times == (CH_ATIME | CH_MTIME)
387 && newtime[0].tv_sec == now.tv_sec
388 && newtime[0].tv_nsec == now.tv_nsec)
390 /* Check that it really was "-d now", and not a time
391 stamp that just happens to be the current time. */
392 struct timespec notnow, notnow1;
393 notnow.tv_sec = now.tv_sec ^ 1;
394 notnow.tv_nsec = now.tv_nsec;
395 get_reldate (&notnow1, flex_date, &notnow);
396 if (notnow1.tv_sec == notnow.tv_sec
397 && notnow1.tv_nsec == notnow.tv_nsec)
398 date_set = false;
403 /* The obsolete `MMDDhhmm[YY]' form is valid IFF there are
404 two or more non-option arguments. */
405 if (!date_set && 2 <= argc - optind && posix2_version () < 200112
406 && posixtime (&newtime[0].tv_sec, argv[optind],
407 PDS_TRAILING_YEAR | PDS_PRE_2000))
409 newtime[0].tv_nsec = 0;
410 newtime[1] = newtime[0];
411 date_set = true;
413 if (! getenv ("POSIXLY_CORRECT"))
415 struct tm const *tm = localtime (&newtime[0].tv_sec);
416 error (0, 0,
417 _("warning: `touch %s' is obsolete; use "
418 "`touch -t %04ld%02d%02d%02d%02d.%02d'"),
419 argv[optind],
420 tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday,
421 tm->tm_hour, tm->tm_min, tm->tm_sec);
424 optind++;
427 if (!date_set)
429 if (change_times == (CH_ATIME | CH_MTIME))
430 amtime_now = true;
431 else
433 gettime (&newtime[0]);
434 newtime[1] = newtime[0];
438 if (optind == argc)
440 error (0, 0, _("missing file operand"));
441 usage (EXIT_FAILURE);
444 for (; optind < argc; ++optind)
445 ok &= touch (argv[optind]);
447 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);