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