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