xref: /freebsd/usr.bin/touch/touch.c (revision f5147e312f43a9050468de539aeafa072caa1a60)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 
34 __FBSDID("$FreeBSD$");
35 
36 #ifndef lint
37 static const char copyright[] =
38 "@(#) Copyright (c) 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif
41 
42 #ifndef lint
43 static const char sccsid[] = "@(#)touch.c	8.1 (Berkeley) 6/6/93";
44 #endif
45 
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <sys/time.h>
49 
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <libgen.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60 
61 static void	stime_arg1(const char *, struct timespec *);
62 static void	stime_arg2(const char *, int, struct timespec *);
63 static void	stime_darg(const char *, struct timespec *);
64 static void	stime_file(const char *, struct timespec *);
65 static int	timeoffset(const char *);
66 static void	usage(const char *);
67 
68 int
69 main(int argc, char *argv[])
70 {
71 	struct stat sb;
72 	struct timespec ts[2];
73 	int atflag;
74 	int Aflag, aflag, cflag, mflag, ch, fd, len, rval, timeset;
75 	char *p;
76 	char *myname;
77 
78 	myname = basename(argv[0]);
79 	Aflag = aflag = cflag = mflag = timeset = 0;
80 	atflag = 0;
81 	ts[0].tv_sec = ts[1].tv_sec = 0;
82 	ts[0].tv_nsec = ts[1].tv_nsec = UTIME_NOW;
83 
84 	while ((ch = getopt(argc, argv, "A:acd:fhmr:t:")) != -1)
85 		switch(ch) {
86 		case 'A':
87 			Aflag = timeoffset(optarg);
88 			break;
89 		case 'a':
90 			aflag = 1;
91 			break;
92 		case 'c':
93 			cflag = 1;
94 			break;
95 		case 'd':
96 			timeset = 1;
97 			stime_darg(optarg, ts);
98 			break;
99 		case 'f':
100 			/* No-op for compatibility. */
101 			break;
102 		case 'h':
103 			cflag = 1;
104 			atflag = AT_SYMLINK_NOFOLLOW;
105 			break;
106 		case 'm':
107 			mflag = 1;
108 			break;
109 		case 'r':
110 			timeset = 1;
111 			stime_file(optarg, ts);
112 			break;
113 		case 't':
114 			timeset = 1;
115 			stime_arg1(optarg, ts);
116 			break;
117 		default:
118 			usage(myname);
119 		}
120 	argc -= optind;
121 	argv += optind;
122 
123 	if (aflag == 0 && mflag == 0)
124 		aflag = mflag = 1;
125 
126 	if (timeset) {
127 		if (Aflag) {
128 			/*
129 			 * We're setting the time to an offset from a specified
130 			 * time.  God knows why, but it means that we can set
131 			 * that time once and for all here.
132 			 */
133 			if (aflag)
134 				ts[0].tv_sec += Aflag;
135 			if (mflag)
136 				ts[1].tv_sec += Aflag;
137 			Aflag = 0;		/* done our job */
138 		}
139 	} else {
140 		/*
141 		 * If no -r or -t flag, at least two operands, the first of
142 		 * which is an 8 or 10 digit number, use the obsolete time
143 		 * specification, otherwise use the current time.
144 		 */
145 		if (argc > 1) {
146 			strtol(argv[0], &p, 10);
147 			len = p - argv[0];
148 			if (*p == '\0' && (len == 8 || len == 10)) {
149 				timeset = 1;
150 				stime_arg2(*argv++, len == 10, ts);
151 			}
152 		}
153 		/* Both times default to the same. */
154 		ts[1] = ts[0];
155 	}
156 
157 	if (!aflag)
158 		ts[0].tv_nsec = UTIME_OMIT;
159 	if (!mflag)
160 		ts[1].tv_nsec = UTIME_OMIT;
161 
162 	if (*argv == NULL)
163 		usage(myname);
164 
165 	if (Aflag)
166 		cflag = 1;
167 
168 	for (rval = 0; *argv; ++argv) {
169 		/* See if the file exists. */
170 		if (fstatat(AT_FDCWD, *argv, &sb, atflag) != 0) {
171 			if (errno != ENOENT) {
172 				rval = 1;
173 				warn("%s", *argv);
174 				continue;
175 			}
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 = 1;
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 
193 		/*
194 		 * We're adjusting the times based on the file times, not a
195 		 * specified time (that gets handled above).
196 		 */
197 		if (Aflag) {
198 			if (aflag) {
199 				ts[0] = sb.st_atim;
200 				ts[0].tv_sec += Aflag;
201 			}
202 			if (mflag) {
203 				ts[1] = sb.st_mtim;
204 				ts[1].tv_sec += Aflag;
205 			}
206 		}
207 
208 		if (!utimensat(AT_FDCWD, *argv, ts, atflag))
209 			continue;
210 
211 		rval = 1;
212 		warn("%s", *argv);
213 	}
214 	exit(rval);
215 }
216 
217 #define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
218 
219 static void
220 stime_arg1(const char *arg, struct timespec *tvp)
221 {
222 	time_t now;
223 	struct tm *t;
224 	int yearset;
225 	char *p;
226 
227 	now = time(NULL);
228 	if ((t = localtime(&now)) == NULL)
229 		err(1, "localtime");
230 					/* [[CC]YY]MMDDhhmm[.SS] */
231 	if ((p = strchr(arg, '.')) == NULL)
232 		t->tm_sec = 0;		/* Seconds defaults to 0. */
233 	else {
234 		if (strlen(p + 1) != 2)
235 			goto terr;
236 		*p++ = '\0';
237 		t->tm_sec = ATOI2(p);
238 	}
239 
240 	yearset = 0;
241 	switch(strlen(arg)) {
242 	case 12:			/* CCYYMMDDhhmm */
243 		t->tm_year = ATOI2(arg);
244 		t->tm_year *= 100;
245 		yearset = 1;
246 		/* FALLTHROUGH */
247 	case 10:			/* YYMMDDhhmm */
248 		if (yearset) {
249 			yearset = ATOI2(arg);
250 			t->tm_year += yearset;
251 		} else {
252 			yearset = ATOI2(arg);
253 			if (yearset < 69)
254 				t->tm_year = yearset + 2000;
255 			else
256 				t->tm_year = yearset + 1900;
257 		}
258 		t->tm_year -= 1900;	/* Convert to UNIX time. */
259 		/* FALLTHROUGH */
260 	case 8:				/* MMDDhhmm */
261 		t->tm_mon = ATOI2(arg);
262 		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
263 		t->tm_mday = ATOI2(arg);
264 		t->tm_hour = ATOI2(arg);
265 		t->tm_min = ATOI2(arg);
266 		break;
267 	default:
268 		goto terr;
269 	}
270 
271 	t->tm_isdst = -1;		/* Figure out DST. */
272 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
273 	if (tvp[0].tv_sec == -1)
274 		goto terr;
275 
276 	tvp[0].tv_nsec = tvp[1].tv_nsec = 0;
277 	return;
278 
279 terr:
280 	errx(1, "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
281 }
282 
283 static void
284 stime_arg2(const char *arg, int year, struct timespec *tvp)
285 {
286 	time_t now;
287 	struct tm *t;
288 
289 	now = time(NULL);
290 	if ((t = localtime(&now)) == NULL)
291 		err(1, "localtime");
292 
293 	t->tm_mon = ATOI2(arg);		/* MMDDhhmm[yy] */
294 	--t->tm_mon;			/* Convert from 01-12 to 00-11 */
295 	t->tm_mday = ATOI2(arg);
296 	t->tm_hour = ATOI2(arg);
297 	t->tm_min = ATOI2(arg);
298 	if (year) {
299 		t->tm_year = ATOI2(arg);
300 		if (t->tm_year < 39)	/* support 2000-2038 not 1902-1969 */
301 			t->tm_year += 100;
302 	}
303 
304 	t->tm_isdst = -1;		/* Figure out DST. */
305 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
306 	if (tvp[0].tv_sec == -1)
307 		errx(1,
308 	"out of range or illegal time specification: MMDDhhmm[yy]");
309 
310 	tvp[0].tv_nsec = tvp[1].tv_nsec = 0;
311 }
312 
313 static void
314 stime_darg(const char *arg, struct timespec *tvp)
315 {
316 	struct tm t = { .tm_sec = 0 };
317 	const char *fmt, *colon;
318 	char *p;
319 	int val, isutc = 0;
320 
321 	tvp[0].tv_nsec = 0;
322 	t.tm_isdst = -1;
323 	colon = strchr(arg, ':');
324 	if (colon == NULL || strchr(colon + 1, ':') == NULL)
325 		goto bad;
326 	fmt = strchr(arg, 'T') != NULL ? "%Y-%m-%dT%H:%M:%S" :
327 	    "%Y-%m-%d %H:%M:%S";
328 	p = strptime(arg, fmt, &t);
329 	if (p == NULL)
330 		goto bad;
331 	/* POSIX: must have at least one digit after dot */
332 	if ((*p == '.' || *p == ',') && isdigit((unsigned char)p[1])) {
333 		p++;
334 		val = 100000000;
335 		while (isdigit((unsigned char)*p)) {
336 			tvp[0].tv_nsec += val * (*p - '0');
337 			p++;
338 			val /= 10;
339 		}
340 	}
341 	if (*p == 'Z') {
342 		isutc = 1;
343 		p++;
344 	}
345 	if (*p != '\0')
346 		goto bad;
347 
348 	tvp[0].tv_sec = isutc ? timegm(&t) : mktime(&t);
349 
350 	tvp[1] = tvp[0];
351 	return;
352 
353 bad:
354 	errx(1, "out of range or illegal time specification: YYYY-MM-DDThh:mm:SS[.frac][tz]");
355 }
356 
357 /* Calculate a time offset in seconds, given an arg of the format [-]HHMMSS. */
358 int
359 timeoffset(const char *arg)
360 {
361 	int offset;
362 	int isneg;
363 
364 	offset = 0;
365 	isneg = *arg == '-';
366 	if (isneg)
367 		arg++;
368 	switch (strlen(arg)) {
369 	default:				/* invalid */
370 		errx(1, "Invalid offset spec, must be [-][[HH]MM]SS");
371 
372 	case 6:					/* HHMMSS */
373 		offset = ATOI2(arg);
374 		/* FALLTHROUGH */
375 	case 4:					/* MMSS */
376 		offset = offset * 60 + ATOI2(arg);
377 		/* FALLTHROUGH */
378 	case 2:					/* SS */
379 		offset = offset * 60 + ATOI2(arg);
380 	}
381 	if (isneg)
382 		return (-offset);
383 	else
384 		return (offset);
385 }
386 
387 static void
388 stime_file(const char *fname, struct timespec *tsp)
389 {
390 	struct stat sb;
391 
392 	if (stat(fname, &sb))
393 		err(1, "%s", fname);
394 	tsp[0] = sb.st_atim;
395 	tsp[1] = sb.st_mtim;
396 }
397 
398 static void
399 usage(const char *myname)
400 {
401 	fprintf(stderr, "usage: %s [-A [-][[hh]mm]SS] [-achm] [-r file] "
402 		"[-t [[CC]YY]MMDDhhmm[.SS]]\n"
403 		"       [-d YYYY-MM-DDThh:mm:SS[.frac][tz]] "
404 		"file ...\n", myname);
405 	exit(1);
406 }
407