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