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