date.c revision 77934
1/*
2 * Copyright (c) 1985, 1987, 1988, 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#ifndef lint
35static char const copyright[] =
36"@(#) Copyright (c) 1985, 1987, 1988, 1993\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)date.c	8.2 (Berkeley) 4/28/95";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/bin/date/date.c 77934 2001-06-09 06:14:05Z dd $";
46#endif /* not lint */
47
48#include <sys/param.h>
49#include <sys/time.h>
50
51#include <ctype.h>
52#include <err.h>
53#include <stdio.h>
54#include <stdlib.h>
55#include <string.h>
56#include <syslog.h>
57#include <unistd.h>
58#include <locale.h>
59
60#include "extern.h"
61#include "vary.h"
62
63#ifndef	TM_YEAR_BASE
64#define	TM_YEAR_BASE	1900
65#endif
66
67time_t tval;
68int retval;
69
70static void setthetime __P((const char *, const char *, int, int));
71static void badformat __P((void));
72static void usage __P((void));
73
74int logwtmp __P((char *, char *, char *));
75
76int
77main(argc, argv)
78	int argc;
79	char **argv;
80{
81	struct timezone tz;
82	int ch, rflag;
83	int jflag, nflag;
84	char *format, buf[1024];
85	char *endptr, *fmt;
86	int set_timezone;
87	struct vary *v;
88	const struct vary *badv;
89	struct tm lt;
90
91	v = NULL;
92	fmt = NULL;
93	(void) setlocale(LC_TIME, "");
94	tz.tz_dsttime = tz.tz_minuteswest = 0;
95	rflag = 0;
96	jflag = nflag = 0;
97	set_timezone = 0;
98	while ((ch = getopt(argc, argv, "d:f:jnr:t:uv:")) != -1)
99		switch((char)ch) {
100		case 'd':		/* daylight savings time */
101			tz.tz_dsttime = strtol(optarg, &endptr, 10) ? 1 : 0;
102			if (endptr == optarg || *endptr != '\0')
103				usage();
104			set_timezone = 1;
105			break;
106		case 'f':
107			fmt = optarg;
108			break;
109		case 'j':
110			jflag = 1;	/* don't set time */
111			break;
112		case 'n':		/* don't set network */
113			nflag = 1;
114			break;
115		case 'r':		/* user specified seconds */
116			rflag = 1;
117			if (sscanf(optarg,"%li",&tval) != 1)
118				usage();
119			break;
120		case 't':		/* minutes west of UTC */
121					/* error check; don't allow "PST" */
122			tz.tz_minuteswest = strtol(optarg, &endptr, 10);
123			if (endptr == optarg || *endptr != '\0')
124				usage();
125			set_timezone = 1;
126			break;
127		case 'u':		/* do everything in UTC */
128			(void)setenv("TZ", "UTC0", 1);
129			break;
130		case 'v':
131			v = vary_append(v, optarg);
132			break;
133		default:
134			usage();
135		}
136	argc -= optind;
137	argv += optind;
138
139	/*
140	 * If -d or -t, set the timezone or daylight savings time; this
141	 * doesn't belong here; the kernel should not know about either.
142	 */
143	if (set_timezone && settimeofday((struct timeval *)NULL, &tz))
144		err(1, "settimeofday (timezone)");
145
146	if (!rflag && time(&tval) == -1)
147		err(1, "time");
148
149	format = "%+";
150
151	/* allow the operands in any order */
152	if (*argv && **argv == '+') {
153		format = *argv + 1;
154		++argv;
155	}
156
157	if (*argv) {
158		setthetime(fmt, *argv, jflag, nflag);
159		++argv;
160	} else if (fmt != NULL)
161		usage();
162
163	if (*argv && **argv == '+')
164		format = *argv + 1;
165
166	lt = *localtime(&tval);
167	badv = vary_apply(v, &lt);
168	if (badv) {
169		fprintf(stderr, "%s: Cannot apply date adjustment\n",
170			badv->arg);
171		vary_destroy(v);
172		usage();
173	}
174	vary_destroy(v);
175	(void)strftime(buf, sizeof(buf), format, &lt);
176	(void)printf("%s\n", buf);
177	exit(retval);
178}
179
180#define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
181
182void
183setthetime(fmt, p, jflag, nflag)
184	const char *fmt;
185	register const char *p;
186	int jflag, nflag;
187{
188	register struct tm *lt;
189	struct timeval tv;
190	const char *dot, *t;
191	int century;
192
193	if (fmt != NULL) {
194		lt = localtime(&tval);
195		t = strptime(p, fmt, lt);
196		if (t == NULL) {
197			fprintf(stderr, "Failed conversion of ``%s''"
198				" using format ``%s''\n", p, fmt);
199			badformat();
200		} else if (*t != '\0')
201			fprintf(stderr, "Warning: Ignoring %ld extraneous"
202				" characters in date string (%s)\n",
203				(long) strlen(t), t);
204	} else {
205		for (t = p, dot = NULL; *t; ++t) {
206			if (isdigit(*t))
207				continue;
208			if (*t == '.' && dot == NULL) {
209				dot = t;
210				continue;
211			}
212			badformat();
213		}
214
215		lt = localtime(&tval);
216
217		if (dot != NULL) {			/* .ss */
218			dot++; /* *dot++ = '\0'; */
219			if (strlen(dot) != 2)
220				badformat();
221			lt->tm_sec = ATOI2(dot);
222			if (lt->tm_sec > 61)
223				badformat();
224		} else
225			lt->tm_sec = 0;
226
227		century = 0;
228		/* if p has a ".ss" field then let's pretend it's not there */
229		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
230		case 12:				/* cc */
231			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
232			century = 1;
233			/* FALLTHROUGH */
234		case 10:				/* yy */
235			if (century)
236				lt->tm_year += ATOI2(p);
237			else {				/* hack for 2000 ;-} */
238				lt->tm_year = ATOI2(p);
239				if (lt->tm_year < 69)
240					lt->tm_year += 2000 - TM_YEAR_BASE;
241				else
242					lt->tm_year += 1900 - TM_YEAR_BASE;
243			}
244			/* FALLTHROUGH */
245		case 8:					/* mm */
246			lt->tm_mon = ATOI2(p);
247			if (lt->tm_mon > 12)
248				badformat();
249			--lt->tm_mon;		/* time struct is 0 - 11 */
250			/* FALLTHROUGH */
251		case 6:					/* dd */
252			lt->tm_mday = ATOI2(p);
253			if (lt->tm_mday > 31)
254				badformat();
255			/* FALLTHROUGH */
256		case 4:					/* HH */
257			lt->tm_hour = ATOI2(p);
258			if (lt->tm_hour > 23)
259				badformat();
260			/* FALLTHROUGH */
261		case 2:					/* MM */
262			lt->tm_min = ATOI2(p);
263			if (lt->tm_min > 59)
264				badformat();
265			break;
266		default:
267			badformat();
268		}
269	}
270
271	/* Let mktime() decide whether summer time is in effect. */
272	lt->tm_isdst = -1;
273
274	/* convert broken-down time to GMT clock time */
275	if ((tval = mktime(lt)) == -1)
276		errx(1, "nonexistent time");
277
278	if (!jflag) {
279		/* set the time */
280		if (nflag || netsettime(tval)) {
281			logwtmp("|", "date", "");
282			tv.tv_sec = tval;
283			tv.tv_usec = 0;
284			if (settimeofday(&tv, (struct timezone *)NULL))
285				err(1, "settimeofday (timeval)");
286			logwtmp("{", "date", "");
287		}
288
289		if ((p = getlogin()) == NULL)
290			p = "???";
291		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
292	}
293}
294
295static void
296badformat()
297{
298	warnx("illegal time format");
299	usage();
300}
301
302static void
303usage()
304{
305	(void)fprintf(stderr, "%s\n%s\n",
306	    "usage: date [-jnu] [-d dst] [-r seconds] [-t west] "
307	    "[-v[+|-]val[ymwdHMS]] ... ",
308	    "            "
309	    "[-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]");
310	exit(1);
311}
312