xref: /freebsd/usr.bin/touch/touch.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
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 <libgen.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <time.h>
60 #include <unistd.h>
61 
62 int	rw(char *, struct stat *, int);
63 void	stime_arg1(char *, struct timeval *);
64 void	stime_arg2(char *, int, struct timeval *);
65 void	stime_file(char *, struct timeval *);
66 int	timeoffset(char *);
67 void	usage(char *);
68 
69 int
70 main(int argc, char *argv[])
71 {
72 	struct stat sb;
73 	struct timeval tv[2];
74 	int (*stat_f)(const char *, struct stat *);
75 	int (*utimes_f)(const char *, const struct timeval *);
76 	int Aflag, aflag, cflag, fflag, mflag, ch, fd, len, rval, timeset;
77 	char *p;
78 	char *myname;
79 
80 	myname = basename(argv[0]);
81 	Aflag = aflag = cflag = fflag = mflag = timeset = 0;
82 	stat_f = stat;
83 	utimes_f = utimes;
84 	if (gettimeofday(&tv[0], NULL))
85 		err(1, "gettimeofday");
86 
87 	while ((ch = getopt(argc, argv, "A:acfhmr:t:")) != -1)
88 		switch(ch) {
89 		case 'A':
90 			Aflag = timeoffset(optarg);
91 			break;
92 		case 'a':
93 			aflag = 1;
94 			break;
95 		case 'c':
96 			cflag = 1;
97 			break;
98 		case 'f':
99 			fflag = 1;
100 			break;
101 		case 'h':
102 			cflag = 1;
103 			stat_f = lstat;
104 			utimes_f = lutimes;
105 			break;
106 		case 'm':
107 			mflag = 1;
108 			break;
109 		case 'r':
110 			timeset = 1;
111 			stime_file(optarg, tv);
112 			break;
113 		case 't':
114 			timeset = 1;
115 			stime_arg1(optarg, tv);
116 			break;
117 		case '?':
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 (!cflag) {
168 				/* Create the file. */
169 				fd = open(*argv,
170 				    O_WRONLY | O_CREAT, DEFFILEMODE);
171 				if (fd == -1 || fstat(fd, &sb) || close(fd)) {
172 					rval = 1;
173 					warn("%s", *argv);
174 					continue;
175 				}
176 
177 				/* If using the current time, we're done. */
178 				if (!timeset)
179 					continue;
180 			} else
181 				continue;
182 		}
183 
184 		if (!aflag)
185 			TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
186 		if (!mflag)
187 			TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
188 
189 		/*
190 		 * We're adjusting the times based on the file times, not a
191 		 * specified time (that gets handled above).
192 		 */
193 		if (Aflag) {
194 			if (aflag) {
195 				TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
196 				tv[0].tv_sec += Aflag;
197 			}
198 			if (mflag) {
199 				TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
200 				tv[1].tv_sec += Aflag;
201 			}
202 		}
203 
204 		/* Try utimes(2). */
205 		if (!utimes_f(*argv, tv))
206 			continue;
207 
208 		/* If the user specified a time, nothing else we can do. */
209 		if (timeset) {
210 			rval = 1;
211 			warn("%s", *argv);
212 			continue;
213 		}
214 
215 		/*
216 		 * System V and POSIX 1003.1 require that a NULL argument
217 		 * set the access/modification times to the current time.
218 		 * The permission checks are different, too, in that the
219 		 * ability to write the file is sufficient.  Take a shot.
220 		 */
221 		 if (!utimes_f(*argv, NULL))
222 			continue;
223 
224 		/* Try reading/writing. */
225 		if (!S_ISLNK(sb.st_mode) && !S_ISDIR(sb.st_mode) &&
226 		    rw(*argv, &sb, fflag))
227 			rval = 1;
228 		else
229 			warn("%s", *argv);
230 	}
231 	exit(rval);
232 }
233 
234 #define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
235 
236 void
237 stime_arg1(char *arg, struct timeval *tvp)
238 {
239 	time_t now;
240 	struct tm *t;
241 	int yearset;
242 	char *p;
243 					/* Start with the current time. */
244 	now = tvp[0].tv_sec;
245 	if ((t = localtime(&now)) == NULL)
246 		err(1, "localtime");
247 					/* [[CC]YY]MMDDhhmm[.SS] */
248 	if ((p = strchr(arg, '.')) == NULL)
249 		t->tm_sec = 0;		/* Seconds defaults to 0. */
250 	else {
251 		if (strlen(p + 1) != 2)
252 			goto terr;
253 		*p++ = '\0';
254 		t->tm_sec = ATOI2(p);
255 	}
256 
257 	yearset = 0;
258 	switch(strlen(arg)) {
259 	case 12:			/* CCYYMMDDhhmm */
260 		t->tm_year = ATOI2(arg);
261 		t->tm_year *= 100;
262 		yearset = 1;
263 		/* FALLTHROUGH */
264 	case 10:			/* YYMMDDhhmm */
265 		if (yearset) {
266 			yearset = ATOI2(arg);
267 			t->tm_year += yearset;
268 		} else {
269 			yearset = ATOI2(arg);
270 			if (yearset < 69)
271 				t->tm_year = yearset + 2000;
272 			else
273 				t->tm_year = yearset + 1900;
274 		}
275 		t->tm_year -= 1900;	/* Convert to UNIX time. */
276 		/* FALLTHROUGH */
277 	case 8:				/* MMDDhhmm */
278 		t->tm_mon = ATOI2(arg);
279 		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
280 		t->tm_mday = ATOI2(arg);
281 		t->tm_hour = ATOI2(arg);
282 		t->tm_min = ATOI2(arg);
283 		break;
284 	default:
285 		goto terr;
286 	}
287 
288 	t->tm_isdst = -1;		/* Figure out DST. */
289 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
290 	if (tvp[0].tv_sec == -1)
291 terr:		errx(1,
292 	"out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
293 
294 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
295 }
296 
297 void
298 stime_arg2(char *arg, int year, struct timeval *tvp)
299 {
300 	time_t now;
301 	struct tm *t;
302 					/* Start with the current time. */
303 	now = tvp[0].tv_sec;
304 	if ((t = localtime(&now)) == NULL)
305 		err(1, "localtime");
306 
307 	t->tm_mon = ATOI2(arg);		/* MMDDhhmm[yy] */
308 	--t->tm_mon;			/* Convert from 01-12 to 00-11 */
309 	t->tm_mday = ATOI2(arg);
310 	t->tm_hour = ATOI2(arg);
311 	t->tm_min = ATOI2(arg);
312 	if (year) {
313 		t->tm_year = ATOI2(arg);
314 		if (t->tm_year < 39)	/* support 2000-2038 not 1902-1969 */
315 			t->tm_year += 100;
316 	}
317 
318 	t->tm_isdst = -1;		/* Figure out DST. */
319 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
320 	if (tvp[0].tv_sec == -1)
321 		errx(1,
322 	"out of range or illegal time specification: MMDDhhmm[yy]");
323 
324 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
325 }
326 
327 /* Calculate a time offset in seconds, given an arg of the format [-]HHMMSS. */
328 int
329 timeoffset(char *arg)
330 {
331 	int offset;
332 	int isneg;
333 
334 	offset = 0;
335 	isneg = *arg == '-';
336 	if (isneg)
337 		arg++;
338 	switch (strlen(arg)) {
339 	default:				/* invalid */
340 		errx(1, "Invalid offset spec, must be [-][[HH]MM]SS");
341 
342 	case 6:					/* HHMMSS */
343 		offset = ATOI2(arg);
344 		/* FALLTHROUGH */
345 	case 4:					/* MMSS */
346 		offset = offset * 60 + ATOI2(arg);
347 		/* FALLTHROUGH */
348 	case 2:					/* SS */
349 		offset = offset * 60 + ATOI2(arg);
350 	}
351 	if (isneg)
352 		return (-offset);
353 	else
354 		return (offset);
355 }
356 
357 void
358 stime_file(char *fname, struct timeval *tvp)
359 {
360 	struct stat sb;
361 
362 	if (stat(fname, &sb))
363 		err(1, "%s", fname);
364 	TIMESPEC_TO_TIMEVAL(tvp, &sb.st_atimespec);
365 	TIMESPEC_TO_TIMEVAL(tvp + 1, &sb.st_mtimespec);
366 }
367 
368 int
369 rw(char *fname, struct stat *sbp, int force)
370 {
371 	int fd, needed_chmod, rval;
372 	u_char byte;
373 
374 	/* Try regular files. */
375 	if (!S_ISREG(sbp->st_mode)) {
376 		warnx("%s: %s", fname, strerror(EFTYPE));
377 		return (1);
378 	}
379 
380 	needed_chmod = rval = 0;
381 	if ((fd = open(fname, O_RDWR, 0)) == -1) {
382 		if (!force || chmod(fname, DEFFILEMODE))
383 			goto err;
384 		if ((fd = open(fname, O_RDWR, 0)) == -1)
385 			goto err;
386 		needed_chmod = 1;
387 	}
388 
389 	if (sbp->st_size != 0) {
390 		if (read(fd, &byte, sizeof(byte)) != sizeof(byte))
391 			goto err;
392 		if (lseek(fd, (off_t)0, SEEK_SET) == -1)
393 			goto err;
394 		if (write(fd, &byte, sizeof(byte)) != sizeof(byte))
395 			goto err;
396 	} else {
397 		if (write(fd, &byte, sizeof(byte)) != sizeof(byte)) {
398 err:			rval = 1;
399 			warn("%s", fname);
400 		} else if (ftruncate(fd, (off_t)0)) {
401 			rval = 1;
402 			warn("%s: file modified", fname);
403 		}
404 	}
405 
406 	if (close(fd) && rval != 1) {
407 		rval = 1;
408 		warn("%s", fname);
409 	}
410 	if (needed_chmod && chmod(fname, sbp->st_mode) && rval != 1) {
411 		rval = 1;
412 		warn("%s: permissions modified", fname);
413 	}
414 	return (rval);
415 }
416 
417 void
418 usage(char *myname)
419 {
420 	fprintf(stderr, "usage:\n" "%s [-A [-][[hh]mm]SS] [-acfhm] [-r file] "
421 		"[-t [[CC]YY]MMDDhhmm[.SS]] file ...\n", myname);
422 	exit(1);
423 }
424