xref: /freebsd/usr.bin/touch/touch.c (revision 3b8f08459569bf0faa21473e5cec2491e95c9349)
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 timeval *);
60 static void	stime_arg2(const char *, int, struct timeval *);
61 static void	stime_darg(const char *, struct timeval *);
62 static void	stime_file(const char *, struct timeval *);
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 timeval tv[2];
71 	int (*stat_f)(const char *, struct stat *);
72 	int (*utimes_f)(const char *, const struct timeval *);
73 	int Aflag, aflag, cflag, mflag, ch, fd, len, rval, timeset;
74 	char *p;
75 	char *myname;
76 
77 	myname = basename(argv[0]);
78 	Aflag = aflag = cflag = mflag = timeset = 0;
79 	stat_f = stat;
80 	utimes_f = utimes;
81 	if (gettimeofday(&tv[0], NULL) == -1)
82 		err(1, "gettimeofday");
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, tv);
98 			break;
99 		case 'f':
100 			/* No-op for compatibility. */
101 			break;
102 		case 'h':
103 			cflag = 1;
104 			stat_f = lstat;
105 			utimes_f = lutimes;
106 			break;
107 		case 'm':
108 			mflag = 1;
109 			break;
110 		case 'r':
111 			timeset = 1;
112 			stime_file(optarg, tv);
113 			break;
114 		case 't':
115 			timeset = 1;
116 			stime_arg1(optarg, tv);
117 			break;
118 		default:
119 			usage(myname);
120 		}
121 	argc -= optind;
122 	argv += optind;
123 
124 	if (aflag == 0 && mflag == 0)
125 		aflag = mflag = 1;
126 
127 	if (timeset) {
128 		if (Aflag) {
129 			/*
130 			 * We're setting the time to an offset from a specified
131 			 * time.  God knows why, but it means that we can set
132 			 * that time once and for all here.
133 			 */
134 			if (aflag)
135 				tv[0].tv_sec += Aflag;
136 			if (mflag)
137 				tv[1].tv_sec += Aflag;
138 			Aflag = 0;		/* done our job */
139 		}
140 	} else {
141 		/*
142 		 * If no -r or -t flag, at least two operands, the first of
143 		 * which is an 8 or 10 digit number, use the obsolete time
144 		 * specification, otherwise use the current time.
145 		 */
146 		if (argc > 1) {
147 			strtol(argv[0], &p, 10);
148 			len = p - argv[0];
149 			if (*p == '\0' && (len == 8 || len == 10)) {
150 				timeset = 1;
151 				stime_arg2(*argv++, len == 10, tv);
152 			}
153 		}
154 		/* Both times default to the same. */
155 		tv[1] = tv[0];
156 	}
157 
158 	if (*argv == NULL)
159 		usage(myname);
160 
161 	if (Aflag)
162 		cflag = 1;
163 
164 	for (rval = 0; *argv; ++argv) {
165 		/* See if the file exists. */
166 		if (stat_f(*argv, &sb) != 0) {
167 			if (errno != ENOENT) {
168 				rval = 1;
169 				warn("%s", *argv);
170 				continue;
171 			}
172 			if (!cflag) {
173 				/* Create the file. */
174 				fd = open(*argv,
175 				    O_WRONLY | O_CREAT, DEFFILEMODE);
176 				if (fd == -1 || fstat(fd, &sb) || close(fd)) {
177 					rval = 1;
178 					warn("%s", *argv);
179 					continue;
180 				}
181 
182 				/* If using the current time, we're done. */
183 				if (!timeset)
184 					continue;
185 			} else
186 				continue;
187 		}
188 
189 		if (!aflag)
190 			TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atim);
191 		if (!mflag)
192 			TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtim);
193 
194 		/*
195 		 * We're adjusting the times based on the file times, not a
196 		 * specified time (that gets handled above).
197 		 */
198 		if (Aflag) {
199 			if (aflag) {
200 				TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atim);
201 				tv[0].tv_sec += Aflag;
202 			}
203 			if (mflag) {
204 				TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtim);
205 				tv[1].tv_sec += Aflag;
206 			}
207 		}
208 
209 		/* Try utimes(2). */
210 		if (!utimes_f(*argv, tv))
211 			continue;
212 
213 		/* If the user specified a time, nothing else we can do. */
214 		if (timeset || Aflag) {
215 			rval = 1;
216 			warn("%s", *argv);
217 			continue;
218 		}
219 
220 		/*
221 		 * System V and POSIX 1003.1 require that a NULL argument
222 		 * set the access/modification times to the current time.
223 		 * The permission checks are different, too, in that the
224 		 * ability to write the file is sufficient.  Take a shot.
225 		 */
226 		 if (!utimes_f(*argv, NULL))
227 			continue;
228 
229 		rval = 1;
230 		warn("%s", *argv);
231 	}
232 	exit(rval);
233 }
234 
235 #define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
236 
237 static void
238 stime_arg1(const char *arg, struct timeval *tvp)
239 {
240 	time_t now;
241 	struct tm *t;
242 	int yearset;
243 	char *p;
244 					/* Start with the current time. */
245 	now = tvp[0].tv_sec;
246 	if ((t = localtime(&now)) == NULL)
247 		err(1, "localtime");
248 					/* [[CC]YY]MMDDhhmm[.SS] */
249 	if ((p = strchr(arg, '.')) == NULL)
250 		t->tm_sec = 0;		/* Seconds defaults to 0. */
251 	else {
252 		if (strlen(p + 1) != 2)
253 			goto terr;
254 		*p++ = '\0';
255 		t->tm_sec = ATOI2(p);
256 	}
257 
258 	yearset = 0;
259 	switch(strlen(arg)) {
260 	case 12:			/* CCYYMMDDhhmm */
261 		t->tm_year = ATOI2(arg);
262 		t->tm_year *= 100;
263 		yearset = 1;
264 		/* FALLTHROUGH */
265 	case 10:			/* YYMMDDhhmm */
266 		if (yearset) {
267 			yearset = ATOI2(arg);
268 			t->tm_year += yearset;
269 		} else {
270 			yearset = ATOI2(arg);
271 			if (yearset < 69)
272 				t->tm_year = yearset + 2000;
273 			else
274 				t->tm_year = yearset + 1900;
275 		}
276 		t->tm_year -= 1900;	/* Convert to UNIX time. */
277 		/* FALLTHROUGH */
278 	case 8:				/* MMDDhhmm */
279 		t->tm_mon = ATOI2(arg);
280 		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
281 		t->tm_mday = ATOI2(arg);
282 		t->tm_hour = ATOI2(arg);
283 		t->tm_min = ATOI2(arg);
284 		break;
285 	default:
286 		goto terr;
287 	}
288 
289 	t->tm_isdst = -1;		/* Figure out DST. */
290 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
291 	if (tvp[0].tv_sec == -1)
292 		goto terr;
293 
294 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
295 	return;
296 
297 terr:
298 	errx(1, "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
299 }
300 
301 static void
302 stime_arg2(const char *arg, int year, struct timeval *tvp)
303 {
304 	time_t now;
305 	struct tm *t;
306 					/* Start with the current time. */
307 	now = tvp[0].tv_sec;
308 	if ((t = localtime(&now)) == NULL)
309 		err(1, "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 		t->tm_year = ATOI2(arg);
318 		if (t->tm_year < 39)	/* support 2000-2038 not 1902-1969 */
319 			t->tm_year += 100;
320 	}
321 
322 	t->tm_isdst = -1;		/* Figure out DST. */
323 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
324 	if (tvp[0].tv_sec == -1)
325 		errx(1,
326 	"out of range or illegal time specification: MMDDhhmm[yy]");
327 
328 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
329 }
330 
331 static void
332 stime_darg(const char *arg, struct timeval *tvp)
333 {
334 	struct tm t = { .tm_sec = 0 };
335 	const char *fmt, *colon;
336 	char *p;
337 	int val, isutc = 0;
338 
339 	tvp[0].tv_usec = 0;
340 	t.tm_isdst = -1;
341 	colon = strchr(arg, ':');
342 	if (colon == NULL || strchr(colon + 1, ':') == NULL)
343 		goto bad;
344 	fmt = strchr(arg, 'T') != NULL ? "%Y-%m-%dT%H:%M:%S" :
345 	    "%Y-%m-%d %H:%M:%S";
346 	p = strptime(arg, fmt, &t);
347 	if (p == NULL)
348 		goto bad;
349 	/* POSIX: must have at least one digit after dot */
350 	if ((*p == '.' || *p == ',') && isdigit((unsigned char)p[1])) {
351 		p++;
352 		val = 100000;
353 		while (isdigit((unsigned char)*p)) {
354 			tvp[0].tv_usec += val * (*p - '0');
355 			p++;
356 			val /= 10;
357 		}
358 	}
359 	if (*p == 'Z') {
360 		isutc = 1;
361 		p++;
362 	}
363 	if (*p != '\0')
364 		goto bad;
365 
366 	tvp[0].tv_sec = isutc ? timegm(&t) : mktime(&t);
367 
368 	tvp[1] = tvp[0];
369 	return;
370 
371 bad:
372 	errx(1, "out of range or illegal time specification: YYYY-MM-DDThh:mm:SS[.frac][tz]");
373 }
374 
375 /* Calculate a time offset in seconds, given an arg of the format [-]HHMMSS. */
376 int
377 timeoffset(const char *arg)
378 {
379 	int offset;
380 	int isneg;
381 
382 	offset = 0;
383 	isneg = *arg == '-';
384 	if (isneg)
385 		arg++;
386 	switch (strlen(arg)) {
387 	default:				/* invalid */
388 		errx(1, "Invalid offset spec, must be [-][[HH]MM]SS");
389 
390 	case 6:					/* HHMMSS */
391 		offset = ATOI2(arg);
392 		/* FALLTHROUGH */
393 	case 4:					/* MMSS */
394 		offset = offset * 60 + ATOI2(arg);
395 		/* FALLTHROUGH */
396 	case 2:					/* SS */
397 		offset = offset * 60 + ATOI2(arg);
398 	}
399 	if (isneg)
400 		return (-offset);
401 	else
402 		return (offset);
403 }
404 
405 static void
406 stime_file(const char *fname, struct timeval *tvp)
407 {
408 	struct stat sb;
409 
410 	if (stat(fname, &sb))
411 		err(1, "%s", fname);
412 	TIMESPEC_TO_TIMEVAL(tvp, &sb.st_atim);
413 	TIMESPEC_TO_TIMEVAL(tvp + 1, &sb.st_mtim);
414 }
415 
416 static void
417 usage(const char *myname)
418 {
419 	fprintf(stderr, "usage: %s [-A [-][[hh]mm]SS] [-achm] [-r file] "
420 		"[-t [[CC]YY]MMDDhhmm[.SS]]\n"
421 		"       [-d YYYY-MM-DDThh:mm:SS[.frac][tz]] "
422 		"file ...\n", myname);
423 	exit(1);
424 }
425