xref: /freebsd/usr.bin/touch/touch.c (revision d640d2e29d6b79c7b50146bfd39b4b91417c2fbc)
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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 
36 __FBSDID("$FreeBSD$");
37 
38 #ifndef lint
39 static const char copyright[] =
40 "@(#) Copyright (c) 1993\n\
41 	The Regents of the University of California.  All rights reserved.\n";
42 #endif
43 
44 #ifndef lint
45 static const char sccsid[] = "@(#)touch.c	8.1 (Berkeley) 6/6/93";
46 #endif
47 
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60 
61 int	rw(char *, struct stat *, int);
62 void	stime_arg1(char *, struct timeval *);
63 void	stime_arg2(char *, int, struct timeval *);
64 void	stime_file(char *, struct timeval *);
65 int	timeoffset(char *);
66 void	usage(char *);
67 
68 int
69 main(int argc, char *argv[])
70 {
71 	struct stat sb;
72 	struct timeval tv[2];
73 	int (*stat_f)(const char *, struct stat *);
74 	int (*utimes_f)(const char *, const struct timeval *);
75 	int Aflag, aflag, cflag, fflag, mflag, ch, fd, len, rval, timeset;
76 	char *p;
77 	char *myname;
78 
79 	myname = argv[0];
80 	Aflag = aflag = cflag = fflag = mflag = timeset = 0;
81 	stat_f = stat;
82 	utimes_f = utimes;
83 	if (gettimeofday(&tv[0], NULL))
84 		err(1, "gettimeofday");
85 
86 	while ((ch = getopt(argc, argv, "A:acfhmr:t:")) != -1)
87 		switch(ch) {
88 		case 'A':
89 			Aflag = timeoffset(optarg);
90 			break;
91 		case 'a':
92 			aflag = 1;
93 			break;
94 		case 'c':
95 			cflag = 1;
96 			break;
97 		case 'f':
98 			fflag = 1;
99 			break;
100 		case 'h':
101 			cflag = 1;
102 			stat_f = lstat;
103 			utimes_f = lutimes;
104 			break;
105 		case 'm':
106 			mflag = 1;
107 			break;
108 		case 'r':
109 			timeset = 1;
110 			stime_file(optarg, tv);
111 			break;
112 		case 't':
113 			timeset = 1;
114 			stime_arg1(optarg, tv);
115 			break;
116 		case '?':
117 		default:
118 			usage(myname);
119 		}
120 	argc -= optind;
121 	argv += optind;
122 
123 	/* -a and -m are default unless one of them or -A is set. */
124 	if (aflag == 0 && mflag == 0 && Aflag == 0)
125 		aflag = mflag = 1;
126 
127 	/*
128 	 * If no -r or -t flag, at least two operands, the first of which
129 	 * is an 8 or 10 digit number, use the obsolete time specification.
130 	 */
131 	if (!timeset && argc > 1) {
132 		(void)strtol(argv[0], &p, 10);
133 		len = p - argv[0];
134 		if (*p == '\0' && (len == 8 || len == 10)) {
135 			timeset = 1;
136 			stime_arg2(*argv++, len == 10, tv);
137 		}
138 	}
139 
140 	/* Otherwise use the current time of day. */
141 	if (!timeset)
142 		tv[1] = tv[0];
143 
144 	if (*argv == NULL)
145 		usage(myname);
146 
147 	for (rval = 0; *argv; ++argv) {
148 		/* See if the file exists. */
149 		if (stat_f(*argv, &sb) != 0) {
150 			if (!cflag) {
151 				/* Create the file. */
152 				fd = open(*argv,
153 				    O_WRONLY | O_CREAT, DEFFILEMODE);
154 				if (fd == -1 || fstat(fd, &sb) || close(fd)) {
155 					rval = 1;
156 					warn("%s", *argv);
157 					continue;
158 				}
159 
160 				/* If using the current time, we're done. */
161 				if (!timeset)
162 					continue;
163 			} else
164 				continue;
165 		}
166 
167 		/* If -a or -m are not set, base time on current file time. */
168 		if (!aflag)
169 			TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
170 		if (!mflag)
171 			TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
172 		if (Aflag) {
173 			tv[0].tv_sec += Aflag;
174 			tv[1].tv_sec += Aflag;
175 		}
176 
177 		/* Try utimes(2). */
178 		if (!utimes_f(*argv, tv))
179 			continue;
180 
181 		/* If the user specified a time, nothing else we can do. */
182 		if (timeset) {
183 			rval = 1;
184 			warn("%s", *argv);
185 			continue;
186 		}
187 
188 		/*
189 		 * System V and POSIX 1003.1 require that a NULL argument
190 		 * set the access/modification times to the current time.
191 		 * The permission checks are different, too, in that the
192 		 * ability to write the file is sufficient.  Take a shot.
193 		 */
194 		 if (!utimes_f(*argv, NULL))
195 			continue;
196 
197 		/* Try reading/writing. */
198 		if (!S_ISLNK(sb.st_mode) && !S_ISDIR(sb.st_mode) &&
199 		    rw(*argv, &sb, fflag))
200 			rval = 1;
201 		else
202 			warn("%s", *argv);
203 	}
204 	exit(rval);
205 }
206 
207 #define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
208 
209 void
210 stime_arg1(char *arg, struct timeval *tvp)
211 {
212 	time_t now;
213 	struct tm *t;
214 	int yearset;
215 	char *p;
216 					/* Start with the current time. */
217 	now = tvp[0].tv_sec;
218 	if ((t = localtime(&now)) == NULL)
219 		err(1, "localtime");
220 					/* [[CC]YY]MMDDhhmm[.SS] */
221 	if ((p = strchr(arg, '.')) == NULL)
222 		t->tm_sec = 0;		/* Seconds defaults to 0. */
223 	else {
224 		if (strlen(p + 1) != 2)
225 			goto terr;
226 		*p++ = '\0';
227 		t->tm_sec = ATOI2(p);
228 	}
229 
230 	yearset = 0;
231 	switch(strlen(arg)) {
232 	case 12:			/* CCYYMMDDhhmm */
233 		t->tm_year = ATOI2(arg);
234 		t->tm_year *= 100;
235 		yearset = 1;
236 		/* FALLTHROUGH */
237 	case 10:			/* YYMMDDhhmm */
238 		if (yearset) {
239 			yearset = ATOI2(arg);
240 			t->tm_year += yearset;
241 		} else {
242 			yearset = ATOI2(arg);
243 			if (yearset < 69)
244 				t->tm_year = yearset + 2000;
245 			else
246 				t->tm_year = yearset + 1900;
247 		}
248 		t->tm_year -= 1900;	/* Convert to UNIX time. */
249 		/* FALLTHROUGH */
250 	case 8:				/* MMDDhhmm */
251 		t->tm_mon = ATOI2(arg);
252 		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
253 		t->tm_mday = ATOI2(arg);
254 		t->tm_hour = ATOI2(arg);
255 		t->tm_min = ATOI2(arg);
256 		break;
257 	default:
258 		goto terr;
259 	}
260 
261 	t->tm_isdst = -1;		/* Figure out DST. */
262 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
263 	if (tvp[0].tv_sec == -1)
264 terr:		errx(1,
265 	"out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
266 
267 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
268 }
269 
270 void
271 stime_arg2(char *arg, int year, struct timeval *tvp)
272 {
273 	time_t now;
274 	struct tm *t;
275 					/* Start with the current time. */
276 	now = tvp[0].tv_sec;
277 	if ((t = localtime(&now)) == NULL)
278 		err(1, "localtime");
279 
280 	t->tm_mon = ATOI2(arg);		/* MMDDhhmm[yy] */
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 	if (year) {
286 		t->tm_year = ATOI2(arg);
287 		if (t->tm_year < 39)	/* support 2000-2038 not 1902-1969 */
288 			t->tm_year += 100;
289 	}
290 
291 	t->tm_isdst = -1;		/* Figure out DST. */
292 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
293 	if (tvp[0].tv_sec == -1)
294 		errx(1,
295 	"out of range or illegal time specification: MMDDhhmm[yy]");
296 
297 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
298 }
299 
300 /* Calculate a time offset in seconds, given an arg of the format [-]HHMMSS. */
301 int
302 timeoffset(char *arg)
303 {
304 	int offset;
305 	int isneg;
306 
307 	offset = 0;
308 	isneg = *arg == '-';
309 	if (isneg)
310 		arg++;
311 	switch (strlen(arg)) {
312 	default:				/* invalid */
313 		errx(1, "Invalid offset spec, must be [-][[HH]MM]SS");
314 
315 	case 6:					/* HHMMSS */
316 		offset = ATOI2(arg);
317 		/* FALLTHROUGH */
318 	case 4:					/* MMSS */
319 		offset = offset * 60 + ATOI2(arg);
320 		/* FALLTHROUGH */
321 	case 2:					/* SS */
322 		offset = offset * 60 + ATOI2(arg);
323 	}
324 	if (isneg)
325 		return (-offset);
326 	else
327 		return (offset);
328 }
329 
330 void
331 stime_file(char *fname, struct timeval *tvp)
332 {
333 	struct stat sb;
334 
335 	if (stat(fname, &sb))
336 		err(1, "%s", fname);
337 	TIMESPEC_TO_TIMEVAL(tvp, &sb.st_atimespec);
338 	TIMESPEC_TO_TIMEVAL(tvp + 1, &sb.st_mtimespec);
339 }
340 
341 int
342 rw(char *fname, struct stat *sbp, int force)
343 {
344 	int fd, needed_chmod, rval;
345 	u_char byte;
346 
347 	/* Try regular files. */
348 	if (!S_ISREG(sbp->st_mode)) {
349 		warnx("%s: %s", fname, strerror(EFTYPE));
350 		return (1);
351 	}
352 
353 	needed_chmod = rval = 0;
354 	if ((fd = open(fname, O_RDWR, 0)) == -1) {
355 		if (!force || chmod(fname, DEFFILEMODE))
356 			goto err;
357 		if ((fd = open(fname, O_RDWR, 0)) == -1)
358 			goto err;
359 		needed_chmod = 1;
360 	}
361 
362 	if (sbp->st_size != 0) {
363 		if (read(fd, &byte, sizeof(byte)) != sizeof(byte))
364 			goto err;
365 		if (lseek(fd, (off_t)0, SEEK_SET) == -1)
366 			goto err;
367 		if (write(fd, &byte, sizeof(byte)) != sizeof(byte))
368 			goto err;
369 	} else {
370 		if (write(fd, &byte, sizeof(byte)) != sizeof(byte)) {
371 err:			rval = 1;
372 			warn("%s", fname);
373 		} else if (ftruncate(fd, (off_t)0)) {
374 			rval = 1;
375 			warn("%s: file modified", fname);
376 		}
377 	}
378 
379 	if (close(fd) && rval != 1) {
380 		rval = 1;
381 		warn("%s", fname);
382 	}
383 	if (needed_chmod && chmod(fname, sbp->st_mode) && rval != 1) {
384 		rval = 1;
385 		warn("%s: permissions modified", fname);
386 	}
387 	return (rval);
388 }
389 
390 void
391 usage(char *myname)
392 {
393 	fprintf(stderr, "usage:\n" "%s [-A [-][[hh]mm]SS] [-acfhm] [-r file] "
394 		"[-t [[CC]YY]MMDDhhmm[.SS]] file ...\n", myname);
395 	exit(1);
396 }
397