(touch): Extend the change of 2001-09-15 to work on
[platform/upstream/coreutils.git] / src / touch.c
1 /* touch -- change modification and access times of files
2    Copyright (C) 87, 1989-1991, 1995-2001 Free Software Foundation, Inc.
3
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 2, or (at your option)
7    any later version.
8
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.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Paul Rubin, Arnold Robbins, Jim Kingdon, David MacKenzie,
19    and Randy Smith. */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <getopt.h>
24 #include <sys/types.h>
25
26 #include "system.h"
27 #include "argmatch.h"
28 #include "error.h"
29 #include "getdate.h"
30 #include "posixtm.h"
31 #include "quote.h"
32 #include "safe-read.h"
33
34 /* The official name of this program (e.g., no `g' prefix).  */
35 #define PROGRAM_NAME "touch"
36
37 #define AUTHORS \
38   "Paul Rubin, Arnold Robbins, Jim Kingdon, David MacKenzie, and Randy Smith"
39
40 #ifndef STDC_HEADERS
41 time_t time ();
42 #endif
43
44 /* Bitmasks for `change_times'. */
45 #define CH_ATIME 1
46 #define CH_MTIME 2
47
48 #if !defined O_NDELAY
49 # define O_NDELAY 0
50 #endif
51
52 #if !defined O_NONBLOCK
53 # define O_NONBLOCK O_NDELAY
54 #endif
55
56 #if !defined O_NOCTTY
57 # define O_NOCTTY 0
58 #endif
59
60 #if !defined EISDIR
61 # define EISDIR 0
62 #endif
63
64 /* The name by which this program was run. */
65 char *program_name;
66
67 /* Which timestamps to change. */
68 static int change_times;
69
70 /* (-c) If nonzero, don't create if not already there. */
71 static int no_create;
72
73 /* (-d) If nonzero, date supplied on command line in get_date formats. */
74 static int flexible_date;
75
76 /* (-r) If nonzero, use times from a reference file. */
77 static int use_ref;
78
79 /* (-t) If nonzero, date supplied on command line in POSIX format. */
80 static int posix_date;
81
82 /* If nonzero, the only thing we have to do is change both the
83    modification and access time to the current time, so we don't
84    have to own the file, just be able to read and write it.
85    On some systems, we can do this if we own the file, even though
86    we have neither read nor write access to it.  */
87 static int amtime_now;
88
89 /* New time to use when setting time. */
90 static time_t newtime;
91
92 /* File to use for -r. */
93 static char *ref_file;
94
95 /* Info about the reference file. */
96 static struct stat ref_stats;
97
98 /* For long options that have no equivalent short option, use a
99    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
100 enum
101 {
102   TIME_OPTION = CHAR_MAX + 1
103 };
104
105 static struct option const longopts[] =
106 {
107   {"time", required_argument, 0, TIME_OPTION},
108   {"no-create", no_argument, 0, 'c'},
109   {"date", required_argument, 0, 'd'},
110   {"file", required_argument, 0, 'r'}, /* FIXME: phase out --file */
111   {"reference", required_argument, 0, 'r'},
112   {GETOPT_HELP_OPTION_DECL},
113   {GETOPT_VERSION_OPTION_DECL},
114   {0, 0, 0, 0}
115 };
116
117 /* Valid arguments to the `--time' option. */
118 static char const* const time_args[] =
119 {
120   "atime", "access", "use", "mtime", "modify", 0
121 };
122
123 /* The bits in `change_times' that those arguments set. */
124 static int const time_masks[] =
125 {
126   CH_ATIME, CH_ATIME, CH_ATIME, CH_MTIME, CH_MTIME
127 };
128
129 /* Update the time of file FILE according to the options given.
130    Return 0 if successful, 1 if an error occurs. */
131
132 static int
133 touch (const char *file)
134 {
135   int status;
136   struct stat sbuf;
137   int fd = -1;
138   int open_errno = 0;
139
140   if (! no_create)
141     {
142       /* Try to open FILE, creating it if necessary.  */
143       fd = open (file, O_WRONLY | O_CREAT | O_NONBLOCK | O_NOCTTY,
144                  S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
145
146       /* Don't save a copy of errno if it's EISDIR, since that would lead
147          touch to give a bogus diagnostic for e.g., `touch /' (assuming
148          we don't own / or have write access to it).  On Solaris 5.6,
149          and probably other systems, it is EINVAL.  On SunOS4, it's EPERM.  */
150       if (fd == -1 && errno != EISDIR && errno != EINVAL && errno != EPERM)
151         open_errno = errno;
152     }
153
154   if (! amtime_now)
155     {
156       /* We're setting only one of the time values.  stat the target to get
157          the other one.  If we have the file descriptor already, use fstat.
158          Otherwise, either we're in no-create mode (and hence didn't call open)
159          or FILE is inaccessible or a directory, so we have to use stat.  */
160       if (fd != -1 ? fstat (fd, &sbuf) : stat (file, &sbuf))
161         {
162           if (open_errno)
163             error (0, open_errno, _("creating %s"), quote (file));
164           else
165             error (0, errno, _("getting attributes of %s"), quote (file));
166           close (fd);
167           return 1;
168         }
169     }
170
171   if (fd != -1 && close (fd) < 0)
172     {
173       error (0, errno, _("creating %s"), quote (file));
174       return 1;
175     }
176
177   if (amtime_now)
178     {
179       /* Pass NULL to utime so it will not fail if we just have
180          write access to the file, but don't own it.  */
181       status = utime (file, NULL);
182     }
183   else
184     {
185       struct utimbuf utb;
186
187       /* There's currently no interface to set file timestamps with
188          better than 1-second resolution, so discard any fractional
189          part of the source timestamp.  */
190
191       if (use_ref)
192         {
193           utb.actime = ref_stats.st_atime;
194           utb.modtime = ref_stats.st_mtime;
195         }
196       else
197         utb.actime = utb.modtime = newtime;
198
199       if (!(change_times & CH_ATIME))
200         utb.actime = sbuf.st_atime;
201
202       if (!(change_times & CH_MTIME))
203         utb.modtime = sbuf.st_mtime;
204
205       status = utime (file, &utb);
206     }
207
208   if (status)
209     {
210       if (open_errno)
211         error (0, open_errno, _("creating %s"), quote (file));
212       else
213         error (0, errno, _("setting times of %s"), quote (file));
214       return 1;
215     }
216
217   return 0;
218 }
219
220 void
221 usage (int status)
222 {
223   if (status != 0)
224     fprintf (stderr, _("Try `%s --help' for more information.\n"),
225              program_name);
226   else
227     {
228       printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
229       printf (_("  or:  %s [-acm] MMDDhhmm[YY] FILE... (obsolescent)\n"),
230               program_name);
231       fputs (_("\
232 Update the access and modification times of each FILE to the current time.\n\
233 \n\
234 "), stdout);
235       fputs (_("\
236 Mandatory arguments to long options are mandatory for short options too.\n\
237 "), stdout);
238       fputs (_("\
239   -a                     change only the access time\n\
240   -c, --no-create        do not create any files\n\
241   -d, --date=STRING      parse STRING and use it instead of current time\n\
242   -f                     (ignored)\n\
243   -m                     change only the modification time\n\
244 "), stdout);
245       fputs (_("\
246   -r, --reference=FILE   use this file's times instead of current time\n\
247   -t STAMP               use [[CC]YY]MMDDhhmm[.ss] instead of current time\n\
248   --time=WORD            set time given by WORD: access atime use (same as -a)\n\
249                            modify mtime (same as -m)\n\
250 "), stdout);
251       fputs (_("\
252       --help             display this help and exit\n\
253       --version          output version information and exit\n\
254 "), stdout);
255       fputs (_("\
256 \n\
257 Note that the three time-date formats recognized for the -d and -t options\n\
258 and for the obsolescent argument are all different.\n\
259 "), stdout);
260       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
261     }
262   exit (status);
263 }
264
265 int
266 main (int argc, char **argv)
267 {
268   int c;
269   int date_set = 0;
270   int err = 0;
271
272   program_name = argv[0];
273   setlocale (LC_ALL, "");
274   bindtextdomain (PACKAGE, LOCALEDIR);
275   textdomain (PACKAGE);
276
277   atexit (close_stdout);
278
279   change_times = no_create = use_ref = posix_date = flexible_date = 0;
280   newtime = (time_t) -1;
281
282   while ((c = getopt_long (argc, argv, "acd:fmr:t:", longopts, NULL)) != -1)
283     {
284       switch (c)
285         {
286         case 0:
287           break;
288
289         case 'a':
290           change_times |= CH_ATIME;
291           break;
292
293         case 'c':
294           no_create++;
295           break;
296
297         case 'd':
298           flexible_date++;
299           newtime = get_date (optarg, NULL);
300           if (newtime == (time_t) -1)
301             error (1, 0, _("invalid date format %s"), quote (optarg));
302           date_set++;
303           break;
304
305         case 'f':
306           break;
307
308         case 'm':
309           change_times |= CH_MTIME;
310           break;
311
312         case 'r':
313           use_ref++;
314           ref_file = optarg;
315           break;
316
317         case 't':
318           posix_date++;
319           newtime = posixtime (optarg,
320                                PDS_LEADING_YEAR | PDS_CENTURY | PDS_SECONDS);
321           if (newtime == (time_t) -1)
322             error (1, 0, _("invalid date format %s"), quote (optarg));
323           date_set++;
324           break;
325
326         case TIME_OPTION:       /* --time */
327           change_times |= XARGMATCH ("--time", optarg,
328                                      time_args, time_masks);
329           break;
330
331         case_GETOPT_HELP_CHAR;
332
333         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
334
335         default:
336           usage (1);
337         }
338     }
339
340   if (change_times == 0)
341     change_times = CH_ATIME | CH_MTIME;
342
343   if ((use_ref && (posix_date || flexible_date))
344       || (posix_date && flexible_date))
345     {
346       error (0, 0, _("cannot specify times from more than one source"));
347       usage (1);
348     }
349
350   if (use_ref)
351     {
352       if (stat (ref_file, &ref_stats))
353         error (1, errno, _("getting attributes of %s"), quote (ref_file));
354       date_set++;
355     }
356
357   /* The obsolescent `MMDDhhmm[YY]' form is valid IFF there are
358      two or more non-option arguments.  */
359   if (!date_set && 2 <= argc - optind && !STREQ (argv[optind - 1], "--"))
360     {
361       newtime = posixtime (argv[optind], PDS_TRAILING_YEAR);
362       if (newtime != (time_t) -1)
363         {
364           optind++;
365           date_set++;
366         }
367     }
368   if (!date_set)
369     {
370       if ((change_times & (CH_ATIME | CH_MTIME)) == (CH_ATIME | CH_MTIME))
371         amtime_now = 1;
372       else
373         time (&newtime);
374     }
375
376   if (optind == argc)
377     {
378       error (0, 0, _("file arguments missing"));
379       usage (1);
380     }
381
382   for (; optind < argc; ++optind)
383     err += touch (argv[optind]);
384
385   exit (err != 0);
386 }