Home | History | Annotate | Line # | Download | only in touch
touch.c revision 1.37
      1 /*	$NetBSD: touch.c,v 1.37 2024/02/08 02:53:53 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.37 2024/02/08 02:53:53 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 <ctype.h>
     50 #include <err.h>
     51 #include <errno.h>
     52 #include <fcntl.h>
     53 #include <limits.h>
     54 #include <math.h>
     55 #include <stdio.h>
     56 #include <stdlib.h>
     57 #include <string.h>
     58 #include <locale.h>
     59 #include <time.h>
     60 #include <tzfile.h>
     61 #include <unistd.h>
     62 #include <util.h>
     63 #include <getopt.h>
     64 
     65 static void	stime_arg0(const char *, struct timespec *);
     66 static void	stime_arg1(char *, struct timespec *);
     67 static void	stime_arg2(const char *, int, struct timespec *);
     68 static void	stime_file(const char *, struct timespec *);
     69 static int	stime_posix(const char *, struct timespec *);
     70 __dead static void	usage(void);
     71 
     72 struct option touch_longopts[] = {
     73 	{ "date",		required_argument,	0,
     74 						'd' },
     75 	{ "reference",		required_argument,	0,
     76 						'r' },
     77 	{ NULL,			0,			0,
     78 						0 },
     79 };
     80 
     81 #define	YEAR_BOUNDARY		69
     82 #define	LOW_YEAR_CENTURY	2000	/* for 2 digit years < YEAR_BOUNDARY */
     83 #define	HIGH_YEAR_CENTURY	1900	/* for 2 digit years >=  "  */
     84 
     85 #define	NO_TIME		((time_t)-1)	/* time_t might be unsigned */
     86 
     87 int
     88 main(int argc, char *argv[])
     89 {
     90 	struct stat sb;
     91 	struct timespec ts[2];
     92 	int aflag, cflag, hflag, mflag, ch, fd, len, rval, timeset;
     93 	char *p;
     94 	int (*change_file_times)(const char *, const struct timespec *);
     95 	int (*get_file_status)(const char *, struct stat *);
     96 
     97 	setlocale(LC_ALL, "");
     98 
     99 	aflag = cflag = hflag = mflag = timeset = 0;
    100 	if (clock_gettime(CLOCK_REALTIME, &ts[0]))
    101 		err(1, "clock_gettime");
    102 
    103 	while ((ch = getopt_long(argc, argv, "acd:fhmr:t:", touch_longopts,
    104 	    NULL)) != -1)
    105 		switch (ch) {
    106 		case 'a':
    107 			aflag = 1;
    108 			break;
    109 		case 'c':
    110 			cflag = 1;
    111 			break;
    112 		case 'd':
    113 			timeset = 1;
    114 			if (!stime_posix(optarg, ts))
    115 				stime_arg0(optarg, ts);
    116 			break;
    117 		case 'f':
    118 			break;
    119 		case 'h':
    120 			hflag = 1;
    121 			break;
    122 		case 'm':
    123 			mflag = 1;
    124 			break;
    125 		case 'r':
    126 			timeset = 1;
    127 			stime_file(optarg, ts);
    128 			break;
    129 		case 't':
    130 			timeset = 1;
    131 			stime_arg1(optarg, ts);
    132 			break;
    133 		case '?':
    134 		default:
    135 			usage();
    136 		}
    137 	argc -= optind;
    138 	argv += optind;
    139 
    140 	/* Default is both -a and -m. */
    141 	if (aflag == 0 && mflag == 0)
    142 		aflag = mflag = 1;
    143 
    144 	if (hflag) {
    145 		cflag = 1;		/* Don't create new file */
    146 		change_file_times = lutimens;
    147 		get_file_status = lstat;
    148 	} else {
    149 		change_file_times = utimens;
    150 		get_file_status = stat;
    151 	}
    152 
    153 	/*
    154 	 * If no -r or -t flag, at least two operands, the first of which
    155 	 * is an 8 or 10 digit number, use the obsolete time specification.
    156 	 */
    157 	if (!timeset && argc > 1) {
    158 		(void)strtol(argv[0], &p, 10);
    159 		len = p - argv[0];
    160 		if (*p == '\0' && (len == 8 || len == 10)) {
    161 			timeset = 1;
    162 			stime_arg2(*argv++, len == 10, ts);
    163 		}
    164 	}
    165 
    166 	/* Otherwise use the current time of day. */
    167 	if (!timeset)
    168 		ts[1] = ts[0];
    169 
    170 	if (*argv == NULL)
    171 		usage();
    172 
    173 	for (rval = EXIT_SUCCESS; *argv; ++argv) {
    174 		/* See if the file exists. */
    175 		if ((*get_file_status)(*argv, &sb)) {
    176 			if (!cflag) {
    177 				/* Create the file. */
    178 				fd = open(*argv,
    179 				    O_WRONLY | O_CREAT, DEFFILEMODE);
    180 				if (fd == -1 || fstat(fd, &sb) || close(fd)) {
    181 					rval = EXIT_FAILURE;
    182 					warn("%s", *argv);
    183 					continue;
    184 				}
    185 
    186 				/* If using the current time, we're done. */
    187 				if (!timeset)
    188 					continue;
    189 			} else
    190 				continue;
    191 		}
    192 		if (!aflag)
    193 			ts[0] = sb.st_atimespec;
    194 		if (!mflag)
    195 			ts[1] = sb.st_mtimespec;
    196 
    197 		/* Try utimes(2). */
    198 		if (!(*change_file_times)(*argv, ts))
    199 			continue;
    200 
    201 		/* If the user specified a time, nothing else we can do. */
    202 		if (timeset) {
    203 			rval = EXIT_FAILURE;
    204 			warn("%s", *argv);
    205 		}
    206 
    207 		/*
    208 		 * System V and POSIX 1003.1 require that a NULL argument
    209 		 * set the access/modification times to the current time.
    210 		 * The permission checks are different, too, in that the
    211 		 * ability to write the file is sufficient.  Take a shot.
    212 		 */
    213 		 if (!(*change_file_times)(*argv, NULL))
    214 			continue;
    215 
    216 		rval = EXIT_FAILURE;
    217 		warn("%s", *argv);
    218 	}
    219 	exit(rval);
    220 }
    221 
    222 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
    223 
    224 static void
    225 stime_arg0(const char *arg, struct timespec *tsp)
    226 {
    227 	tsp[1].tv_sec = tsp[0].tv_sec = parsedate(arg, NULL, NULL);
    228 	if (tsp[0].tv_sec == NO_TIME)
    229 		errx(EXIT_FAILURE, "Could not parse `%s'", arg);
    230 	tsp[0].tv_nsec = tsp[1].tv_nsec = 0;
    231 }
    232 
    233 static void
    234 stime_arg1(char *arg, struct timespec *tsp)
    235 {
    236 	struct tm *t;
    237 	time_t tmptime;
    238 	int yearset;
    239 	char *p;
    240 	char *initarg = arg;
    241 
    242 					/* Start with the current time. */
    243 	tmptime = tsp[0].tv_sec;
    244 	if ((t = localtime(&tmptime)) == NULL)
    245 		err(EXIT_FAILURE, "localtime");
    246 					/* [[CC]YY]MMDDhhmm[.ss] */
    247 	if ((p = strchr(arg, '.')) == NULL)
    248 		t->tm_sec = 0;		/* Seconds defaults to 0. */
    249 	else {
    250 		if (strlen(p + 1) != 2)
    251 			goto terr;
    252 		*p++ = '\0';
    253 		t->tm_sec = ATOI2(p);
    254 	}
    255 
    256 	yearset = 0;
    257 	switch (strlen(arg)) {
    258 	case 12:			/* CCYYMMDDhhmm */
    259 		t->tm_year = ATOI2(arg) * 100 - TM_YEAR_BASE;
    260 		yearset = 1;
    261 		/* FALLTHROUGH */
    262 	case 10:			/* YYMMDDhhmm */
    263 		if (yearset) {
    264 			t->tm_year += ATOI2(arg);
    265 		} else {
    266 			yearset = ATOI2(arg);
    267 			if (yearset < YEAR_BOUNDARY)
    268 				t->tm_year = yearset +
    269 				    LOW_YEAR_CENTURY - TM_YEAR_BASE;
    270 			else
    271 				t->tm_year = yearset +
    272 				    HIGH_YEAR_CENTURY - TM_YEAR_BASE;
    273 		}
    274 		/* FALLTHROUGH */
    275 	case 8:				/* MMDDhhmm */
    276 		t->tm_mon = ATOI2(arg);
    277 		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
    278 		/* FALLTHROUGH */
    279 	case 6:
    280 		t->tm_mday = ATOI2(arg);
    281 		/* FALLTHROUGH */
    282 	case 4:
    283 		t->tm_hour = ATOI2(arg);
    284 		/* FALLTHROUGH */
    285 	case 2:
    286 		t->tm_min = ATOI2(arg);
    287 		break;
    288 	default:
    289 		goto terr;
    290 	}
    291 
    292 	t->tm_isdst = -1;		/* Figure out DST. */
    293 	tsp[0].tv_sec = tsp[1].tv_sec = mktime(t);
    294 	if (tsp[0].tv_sec == NO_TIME)
    295  terr:		errx(EXIT_FAILURE, "out of range or bad time specification:\n"
    296 		    "\t'%s' should be [[CC]YY]MMDDhhmm[.ss]", initarg);
    297 
    298 	tsp[0].tv_nsec = tsp[1].tv_nsec = 0;
    299 }
    300 
    301 static void
    302 stime_arg2(const char *arg, int year, struct timespec *tsp)
    303 {
    304 	struct tm *t;
    305 	time_t tmptime;
    306 					/* Start with the current time. */
    307 	tmptime = tsp[0].tv_sec;
    308 	if ((t = localtime(&tmptime)) == NULL)
    309 		err(EXIT_FAILURE, "localtime");
    310 
    311 	t->tm_mon = ATOI2(arg);		/* MMDDhhmm[yy] */
    312 	--t->tm_mon;			/* Convert from 01-12 to 00-11 */
    313 	t->tm_mday = ATOI2(arg);
    314 	t->tm_hour = ATOI2(arg);
    315 	t->tm_min = ATOI2(arg);
    316 	if (year) {
    317 		year = ATOI2(arg);
    318 		if (year < YEAR_BOUNDARY)
    319 			t->tm_year = year + LOW_YEAR_CENTURY - TM_YEAR_BASE;
    320 		else
    321 			t->tm_year = year + HIGH_YEAR_CENTURY - TM_YEAR_BASE;
    322 	}
    323 	t->tm_sec = 0;
    324 
    325 	t->tm_isdst = -1;		/* Figure out DST. */
    326 	tsp[0].tv_sec = tsp[1].tv_sec = mktime(t);
    327 	if (tsp[0].tv_sec == NO_TIME)
    328 		errx(EXIT_FAILURE,
    329 		    "out of range or bad time specification: MMDDhhmm[YY]");
    330 
    331 	tsp[0].tv_nsec = tsp[1].tv_nsec = 0;
    332 }
    333 
    334 static void
    335 stime_file(const char *fname, struct timespec *tsp)
    336 {
    337 	struct stat sb;
    338 
    339 	if (stat(fname, &sb))
    340 		err(1, "%s", fname);
    341 	tsp[0] = sb.st_atimespec;
    342 	tsp[1] = sb.st_mtimespec;
    343 }
    344 
    345 static int
    346 stime_posix(const char *arg, struct timespec *tsp)
    347 {
    348 	struct tm tm;
    349 	const char *p;
    350 	char *ep;
    351 	int utc = 0;
    352 	long val;
    353 
    354 #define	isdigch(c)	(isdigit((int)((unsigned char)(c))))
    355 
    356 	if ((p = strchr(arg, '-')) == NULL)
    357 		return 0;
    358 	if (p - arg < 4)	/* at least 4 year digits required */
    359 		return 0;
    360 
    361 	if (!isdigch(arg[0]))	/* and the first must be a digit! */
    362 		return 0;
    363 
    364 	errno = 0;
    365 	val = strtol(arg, &ep, 10);		/* YYYY */
    366 	if (val < 0 || val > INT_MAX)
    367 		return 0;
    368 	if (*ep != '-')
    369 		return 0;
    370 	tm.tm_year = (int)val - 1900;
    371 
    372 	p = ep + 1;
    373 
    374 	if (!isdigch(*p))
    375 		return 0;
    376 	val = strtol(p, &ep, 10);		/* MM */
    377 	if (val < 1 || val > 12)
    378 		return 0;
    379 	if (*ep != '-' || ep != p + 2)
    380 		return 0;
    381 	tm.tm_mon = (int)val - 1;
    382 
    383 	p = ep + 1;
    384 
    385 	if (!isdigch(*p))
    386 		return 0;
    387 	val = strtol(p, &ep, 10);		/* DD */
    388 	if (val < 1 || val > 31)
    389 		return 0;
    390 	if ((*ep != 'T' && *ep != ' ') || ep != p + 2)
    391 		return 0;
    392 	tm.tm_mday = (int)val;
    393 
    394 	p = ep + 1;
    395 
    396 	if (!isdigch(*p))
    397 		return 0;
    398 	val = strtol(p, &ep, 10);		/* hh */
    399 	if (val < 0 || val > 23)
    400 		return 0;
    401 	if (*ep != ':' || ep != p + 2)
    402 		return 0;
    403 	tm.tm_hour = (int)val;
    404 
    405 	p = ep + 1;
    406 
    407 	if (!isdigch(*p))
    408 		return 0;
    409 	val = strtol(p, &ep, 10);		/* mm */
    410 	if (val < 0 || val > 59)
    411 		return 0;
    412 	if (*ep != ':' || ep != p + 2)
    413 		return 0;
    414 	tm.tm_min = (int)val;
    415 
    416 	p = ep + 1;
    417 
    418 	if (!isdigch(*p))
    419 		return 0;
    420 	val = strtol(p, &ep, 10);		/* ss (or in POSIX, SS) */
    421 	if (val < 0 || val > 60)
    422 		return 0;
    423 	if ((*ep != '.' && *ep != ',' && *ep != 'Z' && *ep != '\0') ||
    424 	      ep != p + 2)
    425 		return 0;
    426 	tm.tm_sec = (int)val;
    427 
    428 	if (*ep == ',' || *ep == '.') {
    429 		double frac;
    430 		ptrdiff_t fdigs;
    431 
    432 		p = ep + 1;
    433 		if (!isdigch(*p))
    434 			return 0;
    435 		val = strtol(p, &ep, 10);
    436 		if (val < 0)
    437 			return 0;
    438 		if (ep == p)	/* at least 1 digit required */
    439 			return 0;
    440 		if (*ep != 'Z' && *ep != '\0')
    441 			return 0;
    442 
    443 		if (errno != 0)
    444 			return 0;
    445 
    446 		fdigs = ep - p;
    447 		if (fdigs > 15) {
    448 			/* avoid being absurd */
    449 			/* don't want to risk 10^fdigs being INF */
    450 			if (val == 0)
    451 				fdigs = 1;
    452 			else while (fdigs > 15) {
    453 				val = (val + 5) / 10;
    454 				fdigs--;
    455 			}
    456 		}
    457 
    458 		frac = pow(10.0, (double)fdigs);
    459 
    460 		tsp[0].tv_nsec = tsp[1].tv_nsec =
    461 			(long)round(((double)val / frac) * 1000000000.0);
    462 	} else
    463 		tsp[0].tv_nsec = tsp[1].tv_nsec = 0;
    464 
    465 	if (*ep == 'Z') {
    466 		if (ep[1] != '\0')
    467 			return 0;
    468 		utc = 1;
    469 	}
    470 
    471 	if (errno != 0)
    472 		return 0;
    473 
    474 	tm.tm_isdst = -1;
    475 	if (utc)
    476 		tsp[0].tv_sec = tsp[1].tv_sec = timegm(&tm);
    477 	else
    478 		tsp[0].tv_sec = tsp[1].tv_sec = mktime(&tm);
    479 
    480 	if (errno != 0 && tsp[1].tv_sec == NO_TIME)
    481 		return 0;
    482 
    483 	return 1;
    484 }
    485 
    486 static void
    487 usage(void)
    488 {
    489 	(void)fprintf(stderr,
    490 	    "Usage: %s [-acfhm] [-d|--date datetime] [-r|--reference file]"
    491 	    " [-t time] file ...\n", getprogname());
    492 	exit(EXIT_FAILURE);
    493 }
    494