737f123229a3d7d981fcce018d8653b663be6f94
[dragonfly.git] / usr.bin / touch / touch.c
1 /*
2  * Copyright (c) 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)touch.c  8.1 (Berkeley) 6/6/93
35  * $FreeBSD: src/usr.bin/touch/touch.c,v 1.11.2.2 2002/07/28 06:52:15 eric Exp $
36  * $DragonFly: src/usr.bin/touch/touch.c,v 1.7 2004/09/05 00:05:10 dillon Exp $
37  */
38
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42
43 #include <err.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <time.h>
50 #include <unistd.h>
51
52 static int      rw(const char *, const struct stat *, int);
53 static void     stime_arg1(const char *, struct timeval *);
54 static void     stime_arg2(const char *, int, struct timeval *);
55 static void     stime_file(const char *, struct timeval *);
56 static void     usage(void);
57
58 int
59 main(int argc, char **argv)
60 {
61         struct stat sb;
62         struct timeval tv[2];
63         int aflag, cflag, fflag, mflag, ch, fd, len, rval, timeset;
64         char *p;
65
66         aflag = cflag = fflag = mflag = timeset = 0;
67         if (gettimeofday(&tv[0], NULL) == -1)
68                 err(1, "gettimeofday");
69
70         while ((ch = getopt(argc, argv, "acfmr:t:")) != -1)
71                 switch(ch) {
72                 case 'a':
73                         aflag = 1;
74                         break;
75                 case 'c':
76                         cflag = 1;
77                         break;
78                 case 'f':
79                         fflag = 1;
80                         break;
81                 case 'm':
82                         mflag = 1;
83                         break;
84                 case 'r':
85                         timeset = 1;
86                         stime_file(optarg, tv);
87                         break;
88                 case 't':
89                         timeset = 1;
90                         stime_arg1(optarg, tv);
91                         break;
92                 default:
93                         usage();
94                 }
95         argc -= optind;
96         argv += optind;
97
98         /* Default is both -a and -m. */
99         if (aflag == 0 && mflag == 0)
100                 aflag = mflag = 1;
101
102         /*
103          * If no -r or -t flag, at least two operands, the first of which
104          * is an 8 or 10 digit number, use the obsolete time specification.
105          */
106         if (!timeset && argc > 1) {
107                 strtol(argv[0], &p, 10);
108                 len = p - argv[0];
109                 if (*p == '\0' && (len == 8 || len == 10)) {
110                         timeset = 1;
111                         stime_arg2(*argv++, len == 10, tv);
112                 }
113         }
114
115         /* Otherwise use the current time of day. */
116         if (!timeset)
117                 tv[1] = tv[0];
118
119         if (*argv == NULL)
120                 usage();
121
122         for (rval = 0; *argv; ++argv) {
123                 /* See if the file exists. */
124                 if (stat(*argv, &sb)) {
125                         if (!cflag) {
126                                 /* Create the file. */
127                                 fd = open(*argv,
128                                     O_WRONLY | O_CREAT, DEFFILEMODE);
129                                 if (fd == -1 || fstat(fd, &sb) || close(fd)) {
130                                         rval = 1;
131                                         warn("%s", *argv);
132                                         continue;
133                                 }
134
135                                 /* If using the current time, we're done. */
136                                 if (!timeset)
137                                         continue;
138                         } else
139                                 continue;
140                 }
141
142                 if (!aflag)
143                         TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
144                 if (!mflag)
145                         TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
146
147                 /* Try utimes(2). */
148                 if (!utimes(*argv, tv))
149                         continue;
150
151                 /* If the user specified a time, nothing else we can do. */
152                 if (timeset) {
153                         rval = 1;
154                         warn("%s", *argv);
155                 }
156
157                 /*
158                  * System V and POSIX 1003.1 require that a NULL argument
159                  * set the access/modification times to the current time.
160                  * The permission checks are different, too, in that the
161                  * ability to write the file is sufficient.  Take a shot.
162                  */
163                  if (!utimes(*argv, NULL))
164                         continue;
165
166                 /* Try reading/writing. */
167                 if (!S_ISLNK(sb.st_mode) && !S_ISDIR(sb.st_mode) &&
168                     rw(*argv, &sb, fflag))
169                         rval = 1;
170                 else
171                         warn("%s", *argv);
172         }
173         exit(rval);
174 }
175
176 #define ATOI2(ar)       ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
177
178 static void
179 stime_arg1(const char *arg, struct timeval *tvp)
180 {
181         time_t now;
182         struct tm *t;
183         int yearset;
184         char *p;
185                                         /* Start with the current time. */
186         now = tvp[0].tv_sec;
187         if ((t = localtime(&now)) == NULL)
188                 err(1, "localtime");
189                                         /* [[CC]YY]MMDDhhmm[.SS] */
190         if ((p = strchr(arg, '.')) == NULL) {
191                 t->tm_sec = 0;          /* Seconds defaults to 0. */
192         } else {
193                 if (strlen(p + 1) != 2)
194                         goto failed;
195                 *p++ = '\0';
196                 t->tm_sec = ATOI2(p);
197         }
198
199         yearset = 0;
200         switch(strlen(arg)) {
201         case 12:                        /* CCYYMMDDhhmm */
202                 t->tm_year = ATOI2(arg);
203                 t->tm_year *= 100;
204                 yearset = 1;
205                 /* FALLTHOUGH */
206         case 10:                        /* YYMMDDhhmm */
207                 if (yearset) {
208                         yearset = ATOI2(arg);
209                         t->tm_year += yearset;
210                 } else {
211                         yearset = ATOI2(arg);
212                         if (yearset < 69)
213                                 t->tm_year = yearset + 2000;
214                         else
215                                 t->tm_year = yearset + 1900;
216                 }
217                 t->tm_year -= 1900;     /* Convert to UNIX time. */
218                 /* FALLTHROUGH */
219         case 8:                         /* MMDDhhmm */
220                 t->tm_mon = ATOI2(arg);
221                 --t->tm_mon;            /* Convert from 01-12 to 00-11 */
222                 t->tm_mday = ATOI2(arg);
223                 t->tm_hour = ATOI2(arg);
224                 t->tm_min = ATOI2(arg);
225                 break;
226         default:
227                 goto failed;
228         }
229
230         t->tm_isdst = -1;               /* Figure out DST. */
231         tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
232         if (tvp[0].tv_sec == -1)
233                 goto failed;
234
235         tvp[0].tv_usec = tvp[1].tv_usec = 0;
236         return;
237
238 failed:
239         errx(1, "out of range or illegal time "
240                 "specification: [[CC]YY]MMDDhhmm[.SS]");
241 }
242
243 static void
244 stime_arg2(const char *arg, int year, struct timeval *tvp)
245 {
246         time_t now;
247         struct tm *t;
248                                         /* Start with the current time. */
249         now = tvp[0].tv_sec;
250         if ((t = localtime(&now)) == NULL)
251                 err(1, "localtime");
252
253         t->tm_mon = ATOI2(arg);         /* MMDDhhmm[yy] */
254         --t->tm_mon;                    /* Convert from 01-12 to 00-11 */
255         t->tm_mday = ATOI2(arg);
256         t->tm_hour = ATOI2(arg);
257         t->tm_min = ATOI2(arg);
258         if (year) {
259                 t->tm_year = ATOI2(arg);
260                 if (t->tm_year < 39)    /* support 2000-2038 not 1902-1969 */
261                         t->tm_year += 100;
262         }
263
264         t->tm_isdst = -1;               /* Figure out DST. */
265         tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
266         if (tvp[0].tv_sec == -1)
267                 errx(1, "out of range or illegal time "
268                         "specification: MMDDhhmm[yy]");
269
270         tvp[0].tv_usec = tvp[1].tv_usec = 0;
271 }
272
273 static void
274 stime_file(const char *fname, struct timeval *tvp)
275 {
276         struct stat sb;
277
278         if (stat(fname, &sb))
279                 err(1, "%s", fname);
280         TIMESPEC_TO_TIMEVAL(tvp, &sb.st_atimespec);
281         TIMESPEC_TO_TIMEVAL(tvp + 1, &sb.st_mtimespec);
282 }
283
284 static int
285 rw(const char *fname, const struct stat *sbp, int force)
286 {
287         int fd, needed_chmod;
288         const char *warn_msg = NULL;
289         u_char byte;
290
291         /* Try regular files. */
292         if (!S_ISREG(sbp->st_mode)) {
293                 warnx("%s: %s", fname, strerror(EFTYPE));
294                 return (1);
295         }
296
297         needed_chmod = 0;
298         if ((fd = open(fname, O_RDWR, 0)) == -1) {
299                 if (!force || chmod(fname, DEFFILEMODE))
300                         goto failed;
301                 if ((fd = open(fname, O_RDWR, 0)) == -1)
302                         goto failed;
303                 needed_chmod = 1;
304         }
305
306         if (sbp->st_size != 0) {
307                 if (read(fd, &byte, sizeof(byte)) != sizeof(byte))
308                         goto failed;
309                 if (lseek(fd, (off_t)0, SEEK_SET) == -1)
310                         goto failed;
311                 if (write(fd, &byte, sizeof(byte)) != sizeof(byte))
312                         goto failed;
313         } else {
314                 if (write(fd, &byte, sizeof(byte)) != sizeof(byte))
315                         goto failed;
316                 if (ftruncate(fd, (off_t)0)) {
317                         warn_msg = "%s: file modified";
318                         goto failed;
319                 }
320         }
321
322         if (close(fd))
323                 goto failed;
324         if (needed_chmod && chmod(fname, sbp->st_mode)) {
325                 warn_msg = "%s: permissions modified";
326                 goto failed;
327         }
328         return(0);
329
330 failed:
331         if (warn_msg != NULL)
332                 warnx(warn_msg, fname);
333         else
334                 warn("%s", fname);
335         return(1);
336 }
337
338 static void
339 usage(void)
340 {
341         fprintf(stderr, "usage: touch [-acfm] [-r file] "
342                         "[-t [[CC]YY]MMDDhhmm[.SS]] file ...\n");
343         exit(1);
344 }