touch.c revision 297782
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: stable/10/usr.bin/touch/touch.c 297782 2016-04-10 15:02:29Z jilles $");
33
34#ifndef lint
35static 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
41static 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
59static void	stime_arg1(const char *, struct timespec *);
60static void	stime_arg2(const char *, int, struct timespec *);
61static void	stime_darg(const char *, struct timespec *);
62static void	stime_file(const char *, struct timespec *);
63static int	timeoffset(const char *);
64static void	usage(const char *);
65
66int
67main(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	if (clock_gettime(CLOCK_REALTIME, &ts[0]) == -1)
80		err(1, "clock_gettime(CLOCK_REALTIME)");
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 (*argv == NULL)
156		usage(myname);
157
158	if (Aflag)
159		cflag = 1;
160
161	for (rval = 0; *argv; ++argv) {
162		/* See if the file exists. */
163		if (fstatat(AT_FDCWD, *argv, &sb, atflag) != 0) {
164			if (errno != ENOENT) {
165				rval = 1;
166				warn("%s", *argv);
167				continue;
168			}
169			if (!cflag) {
170				/* Create the file. */
171				fd = open(*argv,
172				    O_WRONLY | O_CREAT, DEFFILEMODE);
173				if (fd == -1 || fstat(fd, &sb) || close(fd)) {
174					rval = 1;
175					warn("%s", *argv);
176					continue;
177				}
178
179				/* If using the current time, we're done. */
180				if (!timeset)
181					continue;
182			} else
183				continue;
184		}
185
186		if (!aflag)
187			ts[0] = sb.st_atim;
188		if (!mflag)
189			ts[1] = sb.st_mtim;
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		/* Try utimensat(2). */
207		if (!utimensat(AT_FDCWD, *argv, ts, atflag))
208			continue;
209
210		/* If the user specified a time, nothing else we can do. */
211		if (timeset || Aflag) {
212			rval = 1;
213			warn("%s", *argv);
214			continue;
215		}
216
217		/*
218		 * System V and POSIX 1003.1 require that a NULL argument
219		 * set the access/modification times to the current time.
220		 * The permission checks are different, too, in that the
221		 * ability to write the file is sufficient.  Take a shot.
222		 */
223		 if (!utimensat(AT_FDCWD, *argv, NULL, atflag))
224			continue;
225
226		rval = 1;
227		warn("%s", *argv);
228	}
229	exit(rval);
230}
231
232#define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
233
234static void
235stime_arg1(const char *arg, struct timespec *tvp)
236{
237	time_t now;
238	struct tm *t;
239	int yearset;
240	char *p;
241					/* Start with the current time. */
242	now = tvp[0].tv_sec;
243	if ((t = localtime(&now)) == NULL)
244		err(1, "localtime");
245					/* [[CC]YY]MMDDhhmm[.SS] */
246	if ((p = strchr(arg, '.')) == NULL)
247		t->tm_sec = 0;		/* Seconds defaults to 0. */
248	else {
249		if (strlen(p + 1) != 2)
250			goto terr;
251		*p++ = '\0';
252		t->tm_sec = ATOI2(p);
253	}
254
255	yearset = 0;
256	switch(strlen(arg)) {
257	case 12:			/* CCYYMMDDhhmm */
258		t->tm_year = ATOI2(arg);
259		t->tm_year *= 100;
260		yearset = 1;
261		/* FALLTHROUGH */
262	case 10:			/* YYMMDDhhmm */
263		if (yearset) {
264			yearset = ATOI2(arg);
265			t->tm_year += yearset;
266		} else {
267			yearset = ATOI2(arg);
268			if (yearset < 69)
269				t->tm_year = yearset + 2000;
270			else
271				t->tm_year = yearset + 1900;
272		}
273		t->tm_year -= 1900;	/* Convert to UNIX time. */
274		/* FALLTHROUGH */
275	case 8:				/* MMDDhhmm */
276		t->tm_mon = ATOI2(arg);
277		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
278		t->tm_mday = ATOI2(arg);
279		t->tm_hour = ATOI2(arg);
280		t->tm_min = ATOI2(arg);
281		break;
282	default:
283		goto terr;
284	}
285
286	t->tm_isdst = -1;		/* Figure out DST. */
287	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
288	if (tvp[0].tv_sec == -1)
289		goto terr;
290
291	tvp[0].tv_nsec = tvp[1].tv_nsec = 0;
292	return;
293
294terr:
295	errx(1, "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
296}
297
298static void
299stime_arg2(const char *arg, int year, struct timespec *tvp)
300{
301	time_t now;
302	struct tm *t;
303					/* Start with the current time. */
304	now = tvp[0].tv_sec;
305	if ((t = localtime(&now)) == NULL)
306		err(1, "localtime");
307
308	t->tm_mon = ATOI2(arg);		/* MMDDhhmm[yy] */
309	--t->tm_mon;			/* Convert from 01-12 to 00-11 */
310	t->tm_mday = ATOI2(arg);
311	t->tm_hour = ATOI2(arg);
312	t->tm_min = ATOI2(arg);
313	if (year) {
314		t->tm_year = ATOI2(arg);
315		if (t->tm_year < 39)	/* support 2000-2038 not 1902-1969 */
316			t->tm_year += 100;
317	}
318
319	t->tm_isdst = -1;		/* Figure out DST. */
320	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
321	if (tvp[0].tv_sec == -1)
322		errx(1,
323	"out of range or illegal time specification: MMDDhhmm[yy]");
324
325	tvp[0].tv_nsec = tvp[1].tv_nsec = 0;
326}
327
328static void
329stime_darg(const char *arg, struct timespec *tvp)
330{
331	struct tm t = { .tm_sec = 0 };
332	const char *fmt, *colon;
333	char *p;
334	int val, isutc = 0;
335
336	tvp[0].tv_nsec = 0;
337	t.tm_isdst = -1;
338	colon = strchr(arg, ':');
339	if (colon == NULL || strchr(colon + 1, ':') == NULL)
340		goto bad;
341	fmt = strchr(arg, 'T') != NULL ? "%Y-%m-%dT%H:%M:%S" :
342	    "%Y-%m-%d %H:%M:%S";
343	p = strptime(arg, fmt, &t);
344	if (p == NULL)
345		goto bad;
346	/* POSIX: must have at least one digit after dot */
347	if ((*p == '.' || *p == ',') && isdigit((unsigned char)p[1])) {
348		p++;
349		val = 100000000;
350		while (isdigit((unsigned char)*p)) {
351			tvp[0].tv_nsec += val * (*p - '0');
352			p++;
353			val /= 10;
354		}
355	}
356	if (*p == 'Z') {
357		isutc = 1;
358		p++;
359	}
360	if (*p != '\0')
361		goto bad;
362
363	tvp[0].tv_sec = isutc ? timegm(&t) : mktime(&t);
364
365	tvp[1] = tvp[0];
366	return;
367
368bad:
369	errx(1, "out of range or illegal time specification: YYYY-MM-DDThh:mm:SS[.frac][tz]");
370}
371
372/* Calculate a time offset in seconds, given an arg of the format [-]HHMMSS. */
373int
374timeoffset(const char *arg)
375{
376	int offset;
377	int isneg;
378
379	offset = 0;
380	isneg = *arg == '-';
381	if (isneg)
382		arg++;
383	switch (strlen(arg)) {
384	default:				/* invalid */
385		errx(1, "Invalid offset spec, must be [-][[HH]MM]SS");
386
387	case 6:					/* HHMMSS */
388		offset = ATOI2(arg);
389		/* FALLTHROUGH */
390	case 4:					/* MMSS */
391		offset = offset * 60 + ATOI2(arg);
392		/* FALLTHROUGH */
393	case 2:					/* SS */
394		offset = offset * 60 + ATOI2(arg);
395	}
396	if (isneg)
397		return (-offset);
398	else
399		return (offset);
400}
401
402static void
403stime_file(const char *fname, struct timespec *tsp)
404{
405	struct stat sb;
406
407	if (stat(fname, &sb))
408		err(1, "%s", fname);
409	tsp[0] = sb.st_atim;
410	tsp[1] = sb.st_mtim;
411}
412
413static void
414usage(const char *myname)
415{
416	fprintf(stderr, "usage: %s [-A [-][[hh]mm]SS] [-achm] [-r file] "
417		"[-t [[CC]YY]MMDDhhmm[.SS]]\n"
418		"       [-d YYYY-MM-DDThh:mm:SS[.frac][tz]] "
419		"file ...\n", myname);
420	exit(1);
421}
422