]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - usr.bin/touch/touch.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31
32 __FBSDID("$FreeBSD$");
33
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1993\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif
39
40 #ifndef lint
41 static const char sccsid[] = "@(#)touch.c       8.1 (Berkeley) 6/6/93";
42 #endif
43
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/time.h>
47
48 #include <ctype.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <libgen.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <time.h>
57 #include <unistd.h>
58
59 int     rw(char *, struct stat *, int);
60 void    stime_arg1(char *, struct timeval *);
61 void    stime_arg2(char *, int, struct timeval *);
62 void    stime_darg(char *, struct timeval *);
63 void    stime_file(char *, struct timeval *);
64 int     timeoffset(char *);
65 void    usage(char *);
66
67 int
68 main(int argc, char *argv[])
69 {
70         struct stat sb;
71         struct timeval tv[2];
72         int (*stat_f)(const char *, struct stat *);
73         int (*utimes_f)(const char *, const struct timeval *);
74         int Aflag, aflag, cflag, fflag, mflag, ch, fd, len, rval, timeset;
75         char *p;
76         char *myname;
77
78         myname = basename(argv[0]);
79         Aflag = aflag = cflag = fflag = mflag = timeset = 0;
80         stat_f = stat;
81         utimes_f = utimes;
82         if (gettimeofday(&tv[0], NULL))
83                 err(1, "gettimeofday");
84
85         while ((ch = getopt(argc, argv, "A:acd:fhmr:t:")) != -1)
86                 switch(ch) {
87                 case 'A':
88                         Aflag = timeoffset(optarg);
89                         break;
90                 case 'a':
91                         aflag = 1;
92                         break;
93                 case 'c':
94                         cflag = 1;
95                         break;
96                 case 'd':
97                         timeset = 1;
98                         stime_darg(optarg, tv);
99                         break;
100                 case 'f':
101                         fflag = 1;
102                         break;
103                 case 'h':
104                         cflag = 1;
105                         stat_f = lstat;
106                         utimes_f = lutimes;
107                         break;
108                 case 'm':
109                         mflag = 1;
110                         break;
111                 case 'r':
112                         timeset = 1;
113                         stime_file(optarg, tv);
114                         break;
115                 case 't':
116                         timeset = 1;
117                         stime_arg1(optarg, tv);
118                         break;
119                 case '?':
120                 default:
121                         usage(myname);
122                 }
123         argc -= optind;
124         argv += optind;
125
126         if (aflag == 0 && mflag == 0)
127                 aflag = mflag = 1;
128
129         if (timeset) {
130                 if (Aflag) {
131                         /*
132                          * We're setting the time to an offset from a specified
133                          * time.  God knows why, but it means that we can set
134                          * that time once and for all here.
135                          */
136                         if (aflag)
137                                 tv[0].tv_sec += Aflag;
138                         if (mflag)
139                                 tv[1].tv_sec += Aflag;
140                         Aflag = 0;              /* done our job */
141                 }
142         } else {
143                 /*
144                  * If no -r or -t flag, at least two operands, the first of
145                  * which is an 8 or 10 digit number, use the obsolete time
146                  * specification, otherwise use the current time.
147                  */
148                 if (argc > 1) {
149                         strtol(argv[0], &p, 10);
150                         len = p - argv[0];
151                         if (*p == '\0' && (len == 8 || len == 10)) {
152                                 timeset = 1;
153                                 stime_arg2(*argv++, len == 10, tv);
154                         }
155                 }
156                 /* Both times default to the same. */
157                 tv[1] = tv[0];
158         }
159
160         if (*argv == NULL)
161                 usage(myname);
162
163         if (Aflag)
164                 cflag = 1;
165
166         for (rval = 0; *argv; ++argv) {
167                 /* See if the file exists. */
168                 if (stat_f(*argv, &sb) != 0) {
169                         if (errno != ENOENT) {
170                                 rval = 1;
171                                 warn("%s", *argv);
172                                 continue;
173                         }
174                         if (!cflag) {
175                                 /* Create the file. */
176                                 fd = open(*argv,
177                                     O_WRONLY | O_CREAT, DEFFILEMODE);
178                                 if (fd == -1 || fstat(fd, &sb) || close(fd)) {
179                                         rval = 1;
180                                         warn("%s", *argv);
181                                         continue;
182                                 }
183
184                                 /* If using the current time, we're done. */
185                                 if (!timeset)
186                                         continue;
187                         } else
188                                 continue;
189                 }
190
191                 if (!aflag)
192                         TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atim);
193                 if (!mflag)
194                         TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtim);
195
196                 /*
197                  * We're adjusting the times based on the file times, not a
198                  * specified time (that gets handled above).
199                  */
200                 if (Aflag) {
201                         if (aflag) {
202                                 TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atim);
203                                 tv[0].tv_sec += Aflag;
204                         }
205                         if (mflag) {
206                                 TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtim);
207                                 tv[1].tv_sec += Aflag;
208                         }
209                 }
210
211                 /* Try utimes(2). */
212                 if (!utimes_f(*argv, tv))
213                         continue;
214
215                 /* If the user specified a time, nothing else we can do. */
216                 if (timeset || Aflag) {
217                         rval = 1;
218                         warn("%s", *argv);
219                         continue;
220                 }
221
222                 /*
223                  * System V and POSIX 1003.1 require that a NULL argument
224                  * set the access/modification times to the current time.
225                  * The permission checks are different, too, in that the
226                  * ability to write the file is sufficient.  Take a shot.
227                  */
228                  if (!utimes_f(*argv, NULL))
229                         continue;
230
231                 /* Try reading/writing. */
232                 if (!S_ISLNK(sb.st_mode) && !S_ISDIR(sb.st_mode)) {
233                         if (rw(*argv, &sb, fflag))
234                                 rval = 1;
235                 } else {
236                         rval = 1;
237                         warn("%s", *argv);
238                 }
239         }
240         exit(rval);
241 }
242
243 #define ATOI2(ar)       ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
244
245 void
246 stime_arg1(char *arg, struct timeval *tvp)
247 {
248         time_t now;
249         struct tm *t;
250         int yearset;
251         char *p;
252                                         /* Start with the current time. */
253         now = tvp[0].tv_sec;
254         if ((t = localtime(&now)) == NULL)
255                 err(1, "localtime");
256                                         /* [[CC]YY]MMDDhhmm[.SS] */
257         if ((p = strchr(arg, '.')) == NULL)
258                 t->tm_sec = 0;          /* Seconds defaults to 0. */
259         else {
260                 if (strlen(p + 1) != 2)
261                         goto terr;
262                 *p++ = '\0';
263                 t->tm_sec = ATOI2(p);
264         }
265
266         yearset = 0;
267         switch(strlen(arg)) {
268         case 12:                        /* CCYYMMDDhhmm */
269                 t->tm_year = ATOI2(arg);
270                 t->tm_year *= 100;
271                 yearset = 1;
272                 /* FALLTHROUGH */
273         case 10:                        /* YYMMDDhhmm */
274                 if (yearset) {
275                         yearset = ATOI2(arg);
276                         t->tm_year += yearset;
277                 } else {
278                         yearset = ATOI2(arg);
279                         if (yearset < 69)
280                                 t->tm_year = yearset + 2000;
281                         else
282                                 t->tm_year = yearset + 1900;
283                 }
284                 t->tm_year -= 1900;     /* Convert to UNIX time. */
285                 /* FALLTHROUGH */
286         case 8:                         /* MMDDhhmm */
287                 t->tm_mon = ATOI2(arg);
288                 --t->tm_mon;            /* Convert from 01-12 to 00-11 */
289                 t->tm_mday = ATOI2(arg);
290                 t->tm_hour = ATOI2(arg);
291                 t->tm_min = ATOI2(arg);
292                 break;
293         default:
294                 goto terr;
295         }
296
297         t->tm_isdst = -1;               /* Figure out DST. */
298         tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
299         if (tvp[0].tv_sec == -1)
300 terr:           errx(1,
301         "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
302
303         tvp[0].tv_usec = tvp[1].tv_usec = 0;
304 }
305
306 void
307 stime_arg2(char *arg, int year, struct timeval *tvp)
308 {
309         time_t now;
310         struct tm *t;
311                                         /* Start with the current time. */
312         now = tvp[0].tv_sec;
313         if ((t = localtime(&now)) == NULL)
314                 err(1, "localtime");
315
316         t->tm_mon = ATOI2(arg);         /* MMDDhhmm[yy] */
317         --t->tm_mon;                    /* Convert from 01-12 to 00-11 */
318         t->tm_mday = ATOI2(arg);
319         t->tm_hour = ATOI2(arg);
320         t->tm_min = ATOI2(arg);
321         if (year) {
322                 t->tm_year = ATOI2(arg);
323                 if (t->tm_year < 39)    /* support 2000-2038 not 1902-1969 */
324                         t->tm_year += 100;
325         }
326
327         t->tm_isdst = -1;               /* Figure out DST. */
328         tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
329         if (tvp[0].tv_sec == -1)
330                 errx(1,
331         "out of range or illegal time specification: MMDDhhmm[yy]");
332
333         tvp[0].tv_usec = tvp[1].tv_usec = 0;
334 }
335
336 void
337 stime_darg(char *arg, struct timeval *tvp)
338 {
339         struct tm t = { .tm_sec = 0 };
340         const char *fmt, *colon;
341         char *p;
342         int val, isutc = 0;
343
344         tvp[0].tv_usec = 0;
345         t.tm_isdst = -1;
346         colon = strchr(arg, ':');
347         if (colon == NULL || strchr(colon + 1, ':') == NULL)
348                 goto bad;
349         fmt = strchr(arg, 'T') != NULL ? "%Y-%m-%dT%H:%M:%S" :
350             "%Y-%m-%d %H:%M:%S";
351         p = strptime(arg, fmt, &t);
352         if (p == NULL)
353                 goto bad;
354         /* POSIX: must have at least one digit after dot */
355         if ((*p == '.' || *p == ',') && isdigit((unsigned char)p[1])) {
356                 p++;
357                 val = 100000;
358                 while (isdigit((unsigned char)*p)) {
359                         tvp[0].tv_usec += val * (*p - '0');
360                         p++;
361                         val /= 10;
362                 }
363         }
364         if (*p == 'Z') {
365                 isutc = 1;
366                 p++;
367         }
368         if (*p != '\0')
369                 goto bad;
370
371         tvp[0].tv_sec = isutc ? timegm(&t) : mktime(&t);
372
373         tvp[1] = tvp[0];
374         return;
375
376 bad:
377         errx(1, "out of range or illegal time specification: YYYY-MM-DDThh:mm:SS[.frac][tz]");
378 }
379
380 /* Calculate a time offset in seconds, given an arg of the format [-]HHMMSS. */
381 int
382 timeoffset(char *arg)
383 {
384         int offset;
385         int isneg;
386
387         offset = 0;
388         isneg = *arg == '-';
389         if (isneg)
390                 arg++;
391         switch (strlen(arg)) {
392         default:                                /* invalid */
393                 errx(1, "Invalid offset spec, must be [-][[HH]MM]SS");
394
395         case 6:                                 /* HHMMSS */
396                 offset = ATOI2(arg);
397                 /* FALLTHROUGH */
398         case 4:                                 /* MMSS */
399                 offset = offset * 60 + ATOI2(arg);
400                 /* FALLTHROUGH */
401         case 2:                                 /* SS */
402                 offset = offset * 60 + ATOI2(arg);
403         }
404         if (isneg)
405                 return (-offset);
406         else
407                 return (offset);
408 }
409
410 void
411 stime_file(char *fname, struct timeval *tvp)
412 {
413         struct stat sb;
414
415         if (stat(fname, &sb))
416                 err(1, "%s", fname);
417         TIMESPEC_TO_TIMEVAL(tvp, &sb.st_atim);
418         TIMESPEC_TO_TIMEVAL(tvp + 1, &sb.st_mtim);
419 }
420
421 int
422 rw(char *fname, struct stat *sbp, int force)
423 {
424         int fd, needed_chmod, rval;
425         u_char byte;
426
427         /* Try regular files. */
428         if (!S_ISREG(sbp->st_mode)) {
429                 warnx("%s: %s", fname, strerror(EFTYPE));
430                 return (1);
431         }
432
433         needed_chmod = rval = 0;
434         if ((fd = open(fname, O_RDWR, 0)) == -1) {
435                 if (!force || chmod(fname, DEFFILEMODE))
436                         goto err;
437                 if ((fd = open(fname, O_RDWR, 0)) == -1)
438                         goto err;
439                 needed_chmod = 1;
440         }
441
442         if (sbp->st_size != 0) {
443                 if (read(fd, &byte, sizeof(byte)) != sizeof(byte))
444                         goto err;
445                 if (lseek(fd, (off_t)0, SEEK_SET) == -1)
446                         goto err;
447                 if (write(fd, &byte, sizeof(byte)) != sizeof(byte))
448                         goto err;
449         } else {
450                 if (write(fd, &byte, sizeof(byte)) != sizeof(byte)) {
451 err:                    rval = 1;
452                         warn("%s", fname);
453                 } else if (ftruncate(fd, (off_t)0)) {
454                         rval = 1;
455                         warn("%s: file modified", fname);
456                 }
457         }
458
459         if (close(fd) && rval != 1) {
460                 rval = 1;
461                 warn("%s", fname);
462         }
463         if (needed_chmod && chmod(fname, sbp->st_mode) && rval != 1) {
464                 rval = 1;
465                 warn("%s: permissions modified", fname);
466         }
467         return (rval);
468 }
469
470 void
471 usage(char *myname)
472 {
473         fprintf(stderr, "usage: %s [-A [-][[hh]mm]SS] [-acfhm] [-r file] "
474                 "[-t [[CC]YY]MMDDhhmm[.SS]]\n"
475                 "       [-d YYYY-MM-DDThh:mm:SS[.frac][tz]] "
476                 "file ...\n", myname);
477         exit(1);
478 }