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