xref: /freebsd/bin/date/date.c (revision 380a989b3223d455375b4fae70fd0b9bdd43bafb)
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
35 static 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
42 static char sccsid[] = "@(#)date.c	8.2 (Berkeley) 4/28/95";
43 #endif
44 static const char rcsid[] =
45 	"$Id: date.c,v 1.25 1998/05/13 07:31:39 charnier Exp $";
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 time_t tval;
64 int retval, nflag;
65 
66 static void setthetime __P((const char *, const char *));
67 static void badformat __P((void));
68 static void usage __P((void));
69 
70 int logwtmp __P((char *, char *, char *));
71 
72 int
73 main(argc, argv)
74 	int argc;
75 	char **argv;
76 {
77 	extern int optind;
78 	extern char *optarg;
79 	struct timezone tz;
80 	int ch, rflag;
81 	char *format, buf[1024];
82 	char *endptr, *fmt;
83 	int set_timezone;
84 	struct vary *v;
85 	const struct vary *badv;
86 	struct tm lt;
87 
88 	v = NULL;
89 	fmt = NULL;
90 	(void) setlocale(LC_TIME, "");
91 	tz.tz_dsttime = tz.tz_minuteswest = 0;
92 	rflag = 0;
93 	set_timezone = 0;
94 	while ((ch = getopt(argc, argv, "d:f:nr:t:uv:")) != -1)
95 		switch((char)ch) {
96 		case 'd':		/* daylight savings time */
97 			tz.tz_dsttime = strtol(optarg, &endptr, 10) ? 1 : 0;
98 			if (endptr == optarg || *endptr != '\0')
99 				usage();
100 			set_timezone = 1;
101 			break;
102 		case 'f':
103 			fmt = optarg;
104 			break;
105 		case 'n':		/* don't set network */
106 			nflag = 1;
107 			break;
108 		case 'r':		/* user specified seconds */
109 			rflag = 1;
110 			tval = atol(optarg);
111 			break;
112 		case 't':		/* minutes west of GMT */
113 					/* error check; don't allow "PST" */
114 			tz.tz_minuteswest = strtol(optarg, &endptr, 10);
115 			if (endptr == optarg || *endptr != '\0')
116 				usage();
117 			set_timezone = 1;
118 			break;
119 		case 'u':		/* do everything in GMT */
120 			(void)setenv("TZ", "GMT0", 1);
121 			break;
122 		case 'v':
123 			v = vary_append(v, optarg);
124 			break;
125 		default:
126 			usage();
127 		}
128 	argc -= optind;
129 	argv += optind;
130 
131 	/*
132 	 * If -d or -t, set the timezone or daylight savings time; this
133 	 * doesn't belong here; the kernel should not know about either.
134 	 */
135 	if (set_timezone && settimeofday((struct timeval *)NULL, &tz))
136 		err(1, "settimeofday (timezone)");
137 
138 	if (!rflag && time(&tval) == -1)
139 		err(1, "time");
140 
141 	format = "%+";
142 
143 	/* allow the operands in any order */
144 	if (*argv && **argv == '+') {
145 		format = *argv + 1;
146 		++argv;
147 	}
148 
149 	if (*argv) {
150 		setthetime(fmt, *argv);
151 		++argv;
152 	} else if (fmt != NULL)
153 		usage();
154 
155 	if (*argv && **argv == '+')
156 		format = *argv + 1;
157 
158 	lt = *localtime(&tval);
159 	badv = vary_apply(v, &lt);
160 	if (badv) {
161 		fprintf(stderr, "%s: Cannot apply date adjustment\n",
162 			badv->arg);
163 		vary_destroy(v);
164 		usage();
165 	}
166 	vary_destroy(v);
167 	(void)strftime(buf, sizeof(buf), format, &lt);
168 	(void)printf("%s\n", buf);
169 	exit(retval);
170 }
171 
172 #define	ATOI2(ar)	((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
173 void
174 setthetime(fmt, p)
175 	const char *fmt;
176 	register const char *p;
177 {
178 	register struct tm *lt;
179 	struct timeval tv;
180 	const char *dot, *t;
181 
182 	if (fmt != NULL) {
183 		lt = localtime(&tval);
184 		t = strptime(p, fmt, lt);
185 		if (t == NULL) {
186 			fprintf(stderr, "Failed conversion of ``%s''"
187 				" using format ``%s''\n", p, fmt);
188 			lt = localtime(&tval);
189 			return;
190 		} else if (*t != '\0')
191 			fprintf(stderr, "Warning: Ignoring %ld extraneous"
192 				" characters in date string (%s)\n",
193 				(long) strlen(t), t);
194 	} else {
195 		for (t = p, dot = NULL; *t; ++t) {
196 			if (isdigit(*t))
197 				continue;
198 			if (*t == '.' && dot == NULL) {
199 				dot = t;
200 				continue;
201 			}
202 			badformat();
203 		}
204 
205 		lt = localtime(&tval);
206 
207 		if (dot != NULL) {			/* .ss */
208 			dot++; /* *dot++ = '\0'; */
209 			if (strlen(dot) != 2)
210 				badformat();
211 			lt->tm_sec = ATOI2(dot);
212 			if (lt->tm_sec > 61)
213 				badformat();
214 		} else
215 			lt->tm_sec = 0;
216 
217 		/* if p has a ".ss" field then let's pretend it's not there */
218 		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
219 		case 10:				/* yy */
220 			lt->tm_year = ATOI2(p);
221 			if (lt->tm_year < 69)		/* hack for 2000 ;-} */
222 				lt->tm_year += 100;
223 			/* FALLTHROUGH */
224 		case 8:					/* mm */
225 			lt->tm_mon = ATOI2(p);
226 			if (lt->tm_mon > 12)
227 				badformat();
228 			--lt->tm_mon;		/* time struct is 0 - 11 */
229 			/* FALLTHROUGH */
230 		case 6:					/* dd */
231 			lt->tm_mday = ATOI2(p);
232 			if (lt->tm_mday > 31)
233 				badformat();
234 			/* FALLTHROUGH */
235 		case 4:					/* HH */
236 			lt->tm_hour = ATOI2(p);
237 			if (lt->tm_hour > 23)
238 				badformat();
239 			/* FALLTHROUGH */
240 		case 2:					/* MM */
241 			lt->tm_min = ATOI2(p);
242 			if (lt->tm_min > 59)
243 				badformat();
244 			break;
245 		default:
246 			badformat();
247 		}
248 	}
249 
250 	/* convert broken-down time to GMT clock time */
251 	if ((tval = mktime(lt)) == -1)
252 		errx(1, "nonexistent time");
253 
254 	/* set the time */
255 	if (nflag || netsettime(tval)) {
256 		logwtmp("|", "date", "");
257 		tv.tv_sec = tval;
258 		tv.tv_usec = 0;
259 		if (settimeofday(&tv, (struct timezone *)NULL))
260 			err(1, "settimeofday (timeval)");
261 		logwtmp("{", "date", "");
262 	}
263 
264 	if ((p = getlogin()) == NULL)
265 		p = "???";
266 	syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
267 }
268 
269 static void
270 badformat()
271 {
272 	warnx("illegal time format");
273 	usage();
274 }
275 
276 static void
277 usage()
278 {
279 	(void)fprintf(stderr, "%s\n%s\n",
280 	    "usage: date [-nu] [-d dst] [-r seconds] [-t west] "
281 	    "[-v[+|-]val[ymwdHM]] ... ",
282 	    "            [-f fmt date | [[[[yy]mm]dd]HH]MM[.ss]] [+format]");
283 	exit(1);
284 }
285