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