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