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