xref: /minix3/bin/date/date.c (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1 /* $NetBSD: date.c,v 1.61 2014/09/01 21:42:21 dholland Exp $ */
2 
3 /*
4  * Copyright (c) 1985, 1987, 1988, 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(
35 "@(#) Copyright (c) 1985, 1987, 1988, 1993\
36  The Regents of the University of California.  All rights reserved.");
37 #endif /* not lint */
38 
39 #ifndef lint
40 #if 0
41 static char sccsid[] = "@(#)date.c	8.2 (Berkeley) 4/28/95";
42 #else
43 __RCSID("$NetBSD: date.c,v 1.61 2014/09/01 21:42:21 dholland Exp $");
44 #endif
45 #endif /* not lint */
46 
47 #include <sys/param.h>
48 #include <sys/time.h>
49 
50 #include <ctype.h>
51 #include <err.h>
52 #include <fcntl.h>
53 #include <errno.h>
54 #include <locale.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <syslog.h>
59 #include <time.h>
60 #include <tzfile.h>
61 #include <unistd.h>
62 #include <util.h>
63 
64 #include "extern.h"
65 
66 static time_t tval;
67 static int aflag, jflag, rflag, nflag;
68 
69 __dead static void badcanotime(const char *, const char *, size_t);
70 static void setthetime(const char *);
71 __dead static void usage(void);
72 
73 int
main(int argc,char * argv[])74 main(int argc, char *argv[])
75 {
76 	char *buf;
77 	size_t bufsiz;
78 	const char *format;
79 	int ch;
80 	long long val;
81 	struct tm *tm;
82 
83 	setprogname(argv[0]);
84 	(void)setlocale(LC_ALL, "");
85 
86 	while ((ch = getopt(argc, argv, "ad:jnr:u")) != -1) {
87 		switch (ch) {
88 		case 'a':		/* adjust time slowly */
89 			aflag = 1;
90 			nflag = 1;
91 			break;
92 		case 'd':
93 #if !defined(__minix)
94 			rflag = 1;
95 			tval = parsedate(optarg, NULL, NULL);
96 			if (tval == -1) {
97 				errx(EXIT_FAILURE,
98 				    "%s: Unrecognized date format", optarg);
99 			}
100 #else
101 				errx(EXIT_FAILURE,
102 				    "%s: Unrecognized date format", optarg);
103 #endif /* !defined(__minix) */
104 			break;
105 		case 'j':		/* don't set time */
106 			jflag = 1;
107 			break;
108 		case 'n':		/* don't set network */
109 			nflag = 1;
110 			break;
111 		case 'r':		/* user specified seconds */
112 			if (optarg[0] == '\0') {
113 				errx(EXIT_FAILURE, "<empty>: Invalid number");
114 			}
115 			errno = 0;
116 			val = strtoll(optarg, &buf, 0);
117 			if (errno) {
118 				err(EXIT_FAILURE, "%s", optarg);
119 			}
120 			if (optarg[0] == '\0' || *buf != '\0') {
121 				errx(EXIT_FAILURE,
122 				    "%s: Invalid number", optarg);
123 			}
124 			rflag = 1;
125 			tval = (time_t)val;
126 			break;
127 		case 'u':		/* do everything in UTC */
128 			(void)setenv("TZ", "UTC0", 1);
129 			break;
130 		default:
131 			usage();
132 		}
133 	}
134 	argc -= optind;
135 	argv += optind;
136 
137 	if (!rflag && time(&tval) == -1)
138 		err(EXIT_FAILURE, "time");
139 
140 
141 	/* allow the operands in any order */
142 	if (*argv && **argv == '+') {
143 		format = *argv;
144 		++argv;
145 	} else
146 		format = "+%a %b %e %H:%M:%S %Z %Y";
147 
148 	if (*argv) {
149 		setthetime(*argv);
150 		++argv;
151 	}
152 
153 	if (*argv && **argv == '+')
154 		format = *argv;
155 
156 	if ((buf = malloc(bufsiz = 1024)) == NULL)
157 		goto bad;
158 
159 	if ((tm = localtime(&tval)) == NULL)
160 		err(EXIT_FAILURE, "%lld: localtime", (long long)tval);
161 
162 	while (strftime(buf, bufsiz, format, tm) == 0)
163 		if ((buf = realloc(buf, bufsiz <<= 1)) == NULL)
164 			goto bad;
165 
166 	(void)printf("%s\n", buf + 1);
167 	free(buf);
168 	return 0;
169 bad:
170 	err(EXIT_FAILURE, "Cannot allocate format buffer");
171 }
172 
173 static void
badcanotime(const char * msg,const char * val,size_t where)174 badcanotime(const char *msg, const char *val, size_t where)
175 {
176 	warnx("%s in canonical time", msg);
177 	warnx("%s", val);
178 	warnx("%*s", (int)where + 1, "^");
179 	usage();
180 }
181 
182 #define ATOI2(s) ((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
183 
184 static void
setthetime(const char * p)185 setthetime(const char *p)
186 {
187 	struct timeval tv;
188 	time_t new_time;
189 	struct tm *lt;
190 	const char *dot, *t, *op;
191 	size_t len;
192 	int yearset;
193 
194 	for (t = p, dot = NULL; *t; ++t) {
195 		if (*t == '.') {
196 			if (dot == NULL) {
197 				dot = t;
198 			} else {
199 				badcanotime("Unexpected dot", p, t - p);
200 			}
201 		} else if (!isdigit((unsigned char)*t)) {
202 			badcanotime("Expected digit", p, t - p);
203 		}
204 	}
205 
206 	if ((lt = localtime(&tval)) == NULL)
207 		err(EXIT_FAILURE, "%lld: localtime", (long long)tval);
208 
209 	lt->tm_isdst = -1;			/* Divine correct DST */
210 
211 	if (dot != NULL) {			/* .ss */
212 		len = strlen(dot);
213 		if (len > 3) {
214 			badcanotime("Unexpected digit after seconds field",
215 				    p, strlen(p) - 1);
216 		} else if (len < 3) {
217 			badcanotime("Expected digit in seconds field",
218 				    p, strlen(p));
219 		}
220 		++dot;
221 		lt->tm_sec = ATOI2(dot);
222 		if (lt->tm_sec > 61)
223 			badcanotime("Seconds out of range", p, strlen(p) - 1);
224 	} else {
225 		len = 0;
226 		lt->tm_sec = 0;
227 	}
228 
229 	op = p;
230 	yearset = 0;
231 	switch (strlen(p) - len) {
232 	case 12:				/* cc */
233 		lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
234 		if (lt->tm_year < 0)
235 			badcanotime("Year before 1900", op, p - op + 1);
236 		yearset = 1;
237 		/* FALLTHROUGH */
238 	case 10:				/* yy */
239 		if (yearset) {
240 			lt->tm_year += ATOI2(p);
241 		} else {
242 			yearset = ATOI2(p);
243 			if (yearset < 69)
244 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
245 			else
246 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
247 		}
248 		/* FALLTHROUGH */
249 	case 8:					/* mm */
250 		lt->tm_mon = ATOI2(p);
251 		if (lt->tm_mon > 12 || lt->tm_mon == 0)
252 			badcanotime("Month out of range", op, p - op - 1);
253 		--lt->tm_mon;			/* time struct is 0 - 11 */
254 		/* FALLTHROUGH */
255 	case 6:					/* dd */
256 		lt->tm_mday = ATOI2(p);
257 		switch (lt->tm_mon) {
258 		case 0:
259 		case 2:
260 		case 4:
261 		case 6:
262 		case 7:
263 		case 9:
264 		case 11:
265 			if (lt->tm_mday > 31 || lt->tm_mday == 0)
266 				badcanotime("Day out of range (max 31)",
267 					    op, p - op - 1);
268 			break;
269 		case 3:
270 		case 5:
271 		case 8:
272 		case 10:
273 			if (lt->tm_mday > 30 || lt->tm_mday == 0)
274 				badcanotime("Day out of range (max 30)",
275 					    op, p - op - 1);
276 			break;
277 		case 1:
278 			if (isleap(lt->tm_year + TM_YEAR_BASE)) {
279 				if (lt->tm_mday > 29 || lt->tm_mday == 0) {
280 					badcanotime("Day out of range "
281 						    "(max 29)",
282 						    op, p - op - 1);
283 				}
284 			} else {
285 				if (lt->tm_mday > 28 || lt->tm_mday == 0) {
286 					badcanotime("Day out of range "
287 						    "(max 28)",
288 						    op, p - op - 1);
289 				}
290 			}
291 			break;
292 		default:
293 			/*
294 			 * If the month was given, it's already been
295 			 * checked.  If a bad value came back from
296 			 * localtime, something's badly broken.
297 			 * (make this an assertion?)
298 			 */
299 			errx(EXIT_FAILURE, "localtime gave invalid month %d",
300 			    lt->tm_mon);
301 		}
302 		/* FALLTHROUGH */
303 	case 4:					/* hh */
304 		lt->tm_hour = ATOI2(p);
305 		if (lt->tm_hour > 23)
306 			badcanotime("Hour out of range", op, p - op - 1);
307 		/* FALLTHROUGH */
308 	case 2:					/* mm */
309 		lt->tm_min = ATOI2(p);
310 		if (lt->tm_min > 59)
311 			badcanotime("Minute out of range", op, p - op - 1);
312 		break;
313 	case 0:					/* was just .sss */
314 		if (len != 0)
315 			break;
316 		/* FALLTHROUGH */
317 	default:
318 	    if (strlen(p) - len > 12) {
319 		    badcanotime("Too many digits", p, 12);
320 	    } else {
321 		    badcanotime("Not enough digits", p, strlen(p) - len);
322 	    }
323 	}
324 
325 	/* convert broken-down time to UTC clock time */
326 	if ((new_time = mktime(lt)) == -1) {
327 		/* Can this actually happen? */
328 		err(EXIT_FAILURE, "%s: mktime", op);
329 	}
330 
331 	/* if jflag is set, don't actually change the time, just return */
332 	if (jflag) {
333 		tval = new_time;
334 		return;
335 	}
336 
337 	/* set the time */
338 	if (nflag || netsettime(new_time)) {
339 		logwtmp("|", "date", "");
340 		if (aflag) {
341 			tv.tv_sec = new_time - tval;
342 			tv.tv_usec = 0;
343 			if (adjtime(&tv, NULL))
344 				err(EXIT_FAILURE, "adjtime");
345 		} else {
346 			tval = new_time;
347 			tv.tv_sec = tval;
348 			tv.tv_usec = 0;
349 			if (settimeofday(&tv, NULL))
350 				err(EXIT_FAILURE, "settimeofday");
351 		}
352 		logwtmp("{", "date", "");
353 	}
354 
355 	if ((p = getlogin()) == NULL)
356 		p = "???";
357 	syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
358 }
359 
360 static void
usage(void)361 usage(void)
362 {
363 	(void)fprintf(stderr,
364 	    "Usage: %s [-ajnu] [-d date] [-r seconds] [+format]",
365 	    getprogname());
366 	(void)fprintf(stderr, " [[[[[[CC]yy]mm]dd]HH]MM[.SS]]\n");
367 	exit(EXIT_FAILURE);
368 	/* NOTREACHED */
369 }
370