xref: /freebsd/usr.bin/touch/touch.c (revision 4f29da19bd44f0e99f021510460a81bf754c21d2)
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 void	usage(void);
66 
67 int
68 main(int argc, char *argv[])
69 {
70 	struct stat sb;
71 	struct timeval tv[2];
72 	int (*stat_f)(const char *, struct stat *);
73 	int (*utimes_f)(const char *, const struct timeval *);
74 	int aflag, cflag, fflag, mflag, ch, fd, len, rval, timeset;
75 	char *p;
76 
77 	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, "acfhmr:t:")) != -1)
84 		switch(ch) {
85 		case 'a':
86 			aflag = 1;
87 			break;
88 		case 'c':
89 			cflag = 1;
90 			break;
91 		case 'f':
92 			fflag = 1;
93 			break;
94 		case 'h':
95 			cflag = 1;
96 			stat_f = lstat;
97 			utimes_f = lutimes;
98 			break;
99 		case 'm':
100 			mflag = 1;
101 			break;
102 		case 'r':
103 			timeset = 1;
104 			stime_file(optarg, tv);
105 			break;
106 		case 't':
107 			timeset = 1;
108 			stime_arg1(optarg, tv);
109 			break;
110 		case '?':
111 		default:
112 			usage();
113 		}
114 	argc -= optind;
115 	argv += optind;
116 
117 	/* Default is both -a and -m. */
118 	if (aflag == 0 && mflag == 0)
119 		aflag = mflag = 1;
120 
121 	/*
122 	 * If no -r or -t flag, at least two operands, the first of which
123 	 * is an 8 or 10 digit number, use the obsolete time specification.
124 	 */
125 	if (!timeset && argc > 1) {
126 		(void)strtol(argv[0], &p, 10);
127 		len = p - argv[0];
128 		if (*p == '\0' && (len == 8 || len == 10)) {
129 			timeset = 1;
130 			stime_arg2(*argv++, len == 10, tv);
131 		}
132 	}
133 
134 	/* Otherwise use the current time of day. */
135 	if (!timeset)
136 		tv[1] = tv[0];
137 
138 	if (*argv == NULL)
139 		usage();
140 
141 	for (rval = 0; *argv; ++argv) {
142 		/* See if the file exists. */
143 		if (stat_f(*argv, &sb) != 0) {
144 			if (!cflag) {
145 				/* Create the file. */
146 				fd = open(*argv,
147 				    O_WRONLY | O_CREAT, DEFFILEMODE);
148 				if (fd == -1 || fstat(fd, &sb) || close(fd)) {
149 					rval = 1;
150 					warn("%s", *argv);
151 					continue;
152 				}
153 
154 				/* If using the current time, we're done. */
155 				if (!timeset)
156 					continue;
157 			} else
158 				continue;
159 		}
160 
161 		if (!aflag)
162 			TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
163 		if (!mflag)
164 			TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
165 
166 		/* Try utimes(2). */
167 		if (!utimes_f(*argv, tv))
168 			continue;
169 
170 		/* If the user specified a time, nothing else we can do. */
171 		if (timeset) {
172 			rval = 1;
173 			warn("%s", *argv);
174 			continue;
175 		}
176 
177 		/*
178 		 * System V and POSIX 1003.1 require that a NULL argument
179 		 * set the access/modification times to the current time.
180 		 * The permission checks are different, too, in that the
181 		 * ability to write the file is sufficient.  Take a shot.
182 		 */
183 		 if (!utimes_f(*argv, NULL))
184 			continue;
185 
186 		/* Try reading/writing. */
187 		if (!S_ISLNK(sb.st_mode) && !S_ISDIR(sb.st_mode) &&
188 		    rw(*argv, &sb, fflag))
189 			rval = 1;
190 		else
191 			warn("%s", *argv);
192 	}
193 	exit(rval);
194 }
195 
196 #define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
197 
198 void
199 stime_arg1(char *arg, struct timeval *tvp)
200 {
201 	time_t now;
202 	struct tm *t;
203 	int yearset;
204 	char *p;
205 					/* Start with the current time. */
206 	now = tvp[0].tv_sec;
207 	if ((t = localtime(&now)) == NULL)
208 		err(1, "localtime");
209 					/* [[CC]YY]MMDDhhmm[.SS] */
210 	if ((p = strchr(arg, '.')) == NULL)
211 		t->tm_sec = 0;		/* Seconds defaults to 0. */
212 	else {
213 		if (strlen(p + 1) != 2)
214 			goto terr;
215 		*p++ = '\0';
216 		t->tm_sec = ATOI2(p);
217 	}
218 
219 	yearset = 0;
220 	switch(strlen(arg)) {
221 	case 12:			/* CCYYMMDDhhmm */
222 		t->tm_year = ATOI2(arg);
223 		t->tm_year *= 100;
224 		yearset = 1;
225 		/* FALLTHROUGH */
226 	case 10:			/* YYMMDDhhmm */
227 		if (yearset) {
228 			yearset = ATOI2(arg);
229 			t->tm_year += yearset;
230 		} else {
231 			yearset = ATOI2(arg);
232 			if (yearset < 69)
233 				t->tm_year = yearset + 2000;
234 			else
235 				t->tm_year = yearset + 1900;
236 		}
237 		t->tm_year -= 1900;	/* Convert to UNIX time. */
238 		/* FALLTHROUGH */
239 	case 8:				/* MMDDhhmm */
240 		t->tm_mon = ATOI2(arg);
241 		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
242 		t->tm_mday = ATOI2(arg);
243 		t->tm_hour = ATOI2(arg);
244 		t->tm_min = ATOI2(arg);
245 		break;
246 	default:
247 		goto terr;
248 	}
249 
250 	t->tm_isdst = -1;		/* Figure out DST. */
251 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
252 	if (tvp[0].tv_sec == -1)
253 terr:		errx(1,
254 	"out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
255 
256 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
257 }
258 
259 void
260 stime_arg2(char *arg, int year, struct timeval *tvp)
261 {
262 	time_t now;
263 	struct tm *t;
264 					/* Start with the current time. */
265 	now = tvp[0].tv_sec;
266 	if ((t = localtime(&now)) == NULL)
267 		err(1, "localtime");
268 
269 	t->tm_mon = ATOI2(arg);		/* MMDDhhmm[yy] */
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 	if (year) {
275 		t->tm_year = ATOI2(arg);
276 		if (t->tm_year < 39)	/* support 2000-2038 not 1902-1969 */
277 			t->tm_year += 100;
278 	}
279 
280 	t->tm_isdst = -1;		/* Figure out DST. */
281 	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
282 	if (tvp[0].tv_sec == -1)
283 		errx(1,
284 	"out of range or illegal time specification: MMDDhhmm[yy]");
285 
286 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
287 }
288 
289 void
290 stime_file(char *fname, struct timeval *tvp)
291 {
292 	struct stat sb;
293 
294 	if (stat(fname, &sb))
295 		err(1, "%s", fname);
296 	TIMESPEC_TO_TIMEVAL(tvp, &sb.st_atimespec);
297 	TIMESPEC_TO_TIMEVAL(tvp + 1, &sb.st_mtimespec);
298 }
299 
300 int
301 rw(char *fname, struct stat *sbp, int force)
302 {
303 	int fd, needed_chmod, rval;
304 	u_char byte;
305 
306 	/* Try regular files. */
307 	if (!S_ISREG(sbp->st_mode)) {
308 		warnx("%s: %s", fname, strerror(EFTYPE));
309 		return (1);
310 	}
311 
312 	needed_chmod = rval = 0;
313 	if ((fd = open(fname, O_RDWR, 0)) == -1) {
314 		if (!force || chmod(fname, DEFFILEMODE))
315 			goto err;
316 		if ((fd = open(fname, O_RDWR, 0)) == -1)
317 			goto err;
318 		needed_chmod = 1;
319 	}
320 
321 	if (sbp->st_size != 0) {
322 		if (read(fd, &byte, sizeof(byte)) != sizeof(byte))
323 			goto err;
324 		if (lseek(fd, (off_t)0, SEEK_SET) == -1)
325 			goto err;
326 		if (write(fd, &byte, sizeof(byte)) != sizeof(byte))
327 			goto err;
328 	} else {
329 		if (write(fd, &byte, sizeof(byte)) != sizeof(byte)) {
330 err:			rval = 1;
331 			warn("%s", fname);
332 		} else if (ftruncate(fd, (off_t)0)) {
333 			rval = 1;
334 			warn("%s: file modified", fname);
335 		}
336 	}
337 
338 	if (close(fd) && rval != 1) {
339 		rval = 1;
340 		warn("%s", fname);
341 	}
342 	if (needed_chmod && chmod(fname, sbp->st_mode) && rval != 1) {
343 		rval = 1;
344 		warn("%s: permissions modified", fname);
345 	}
346 	return (rval);
347 }
348 
349 void
350 usage(void)
351 {
352 	(void)fprintf(stderr, "usage: touch [-acfhm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...\n");
353 	exit(1);
354 }
355