xref: /dragonfly/bin/date/date.c (revision 9ef1e017)
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#)date.c	8.2 (Berkeley) 4/28/95
30  * $FreeBSD: src/bin/date/date.c,v 1.47 2005/01/10 08:39:21 imp Exp $
31  */
32 
33 #include <sys/param.h>
34 #include <sys/time.h>
35 
36 #include <ctype.h>
37 #include <err.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <syslog.h>
42 #include <unistd.h>
43 #include <locale.h>
44 #include <libutil.h>
45 #include <utmpx.h>
46 
47 #include "vary.h"
48 
49 #ifndef	TM_YEAR_BASE
50 #define	TM_YEAR_BASE	1900
51 #endif
52 
53 static time_t tval;
54 
55 static void badformat(void);
56 static void setthetime(const char *, const char *, int);
57 static void usage(void);
58 
59 static const struct iso8601_fmt {
60 	const char *refname;
61 	const char *format;
62 } iso8601_fmts[] = {
63 	{ "date", "%Y-%m-%d" },
64 	{ "hours", "%Y-%m-%dT%H" },
65 	{ "minutes", "%Y-%m-%dT%H:%M" },
66 	{ "seconds", "%Y-%m-%dT%H:%M:%S" },
67 };
68 static const struct iso8601_fmt *iso8601_selected;
69 
70 static const char *rfc2822_format = "%a, %d %b %Y %T %z";
71 
72 int
73 main(int argc, char **argv)
74 {
75 	int ch, rflag;
76 	int Iflag, jflag, Rflag;
77 	const char *format;
78 	char buf[1024], tzbuf[8];
79 	char *fmt;
80 	char *tmp;
81 	struct vary *v;
82 	const struct vary *badv;
83 	struct tm lt;
84 	size_t i;
85 
86 	v = NULL;
87 	fmt = NULL;
88 	setlocale(LC_TIME, "");
89 	rflag = 0;
90 	Iflag = jflag = Rflag = 0;
91 	while ((ch = getopt(argc, argv, "f:I::jnRr:uv:")) != -1)
92 		switch (ch) {
93 		case 'f':
94 			fmt = optarg;
95 			break;
96 		case 'I':		/* ISO 8601 datetime format */
97 			if (Rflag)
98 				errx(1, "multiple output formats specified");
99 			Iflag = 1;
100 			if (optarg == NULL) {
101 				iso8601_selected = iso8601_fmts;
102 				break;
103 			}
104 			for (i = 0; i < nitems(iso8601_fmts); i++) {
105 				if (strncmp(optarg, iso8601_fmts[i].refname,
106 					    strlen(optarg)) == 0)
107 					break;
108 			}
109 			if (i == nitems(iso8601_fmts))
110 				errx(1, "invalid argument '%s' for -I", optarg);
111 			iso8601_selected = &iso8601_fmts[i];
112 			break;
113 		case 'j':
114 			jflag = 1;	/* don't set time */
115 			break;
116 		case 'n':		/* don't set network */
117 			break;
118 		case 'R':		/* RFC 2822 datetime format */
119 			if (Iflag)
120 				errx(1, "multiple output formats specified");
121 			Rflag = 1;
122 			break;
123 		case 'r':		/* user specified seconds */
124 			rflag = 1;
125 			tval = strtoll(optarg, &tmp, 0);
126 			if (*tmp != 0)
127 				usage();
128 			break;
129 		case 'u':		/* do everything in UTC */
130 			if (setenv("TZ", "UTC0", 1) != 0)
131 				err(1, "setenv: cannot set TZ=UTC0");
132 			break;
133 		case 'v':
134 			v = vary_append(v, optarg);
135 			break;
136 		default:
137 			usage();
138 		}
139 	argc -= optind;
140 	argv += optind;
141 
142 	if (!rflag && time(&tval) == -1)
143 		err(1, "time");
144 
145 	format = "%+";
146 
147 	if (Rflag)
148 		format = rfc2822_format;
149 	if (Iflag)
150 		format = iso8601_selected->format;
151 
152 	/* allow the operands in any order */
153 	if (*argv && **argv == '+') {
154 		if (Iflag || Rflag)
155 			errx(1, "multiple output formats specified");
156 		format = *argv + 1;
157 		++argv;
158 	}
159 
160 	if (*argv) {
161 		setthetime(fmt, *argv, jflag);
162 		++argv;
163 	} else if (fmt != NULL)
164 		usage();
165 
166 	if (*argv && **argv == '+') {
167 		if (Iflag || Rflag)
168 			errx(1, "multiple output formats specified");
169 		format = *argv + 1;
170 	}
171 
172 	lt = *localtime(&tval);
173 	badv = vary_apply(v, &lt);
174 	if (badv) {
175 		fprintf(stderr, "%s: Cannot apply date adjustment\n",
176 			badv->arg);
177 		vary_destroy(v);
178 		usage();
179 	}
180 	vary_destroy(v);
181 
182 	if (format == rfc2822_format) {
183 		/*
184 		 * When using RFC 2822 datetime format, don't honor the
185 		 * locale.
186 		 */
187 		setlocale(LC_TIME, "C");
188 	}
189 
190 	strftime(buf, sizeof(buf), format, &lt);
191 	if (Iflag && iso8601_selected > iso8601_fmts) {
192 		strftime(tzbuf, sizeof(tzbuf), "%z", &lt);
193 		memmove(&tzbuf[4], &tzbuf[3], 3);
194 		tzbuf[3] = ':';
195 		strlcat(buf, tzbuf, sizeof(buf));
196 	}
197 	printf("%s\n", buf);
198 	if (fflush(stdout) != 0)
199 		err(1, "stdout");
200 	exit(EXIT_SUCCESS);
201 }
202 
203 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
204 
205 static void
206 setthetime(const char *fmt, const char *p, int jflag)
207 {
208 	struct tm *lt;
209 	struct timeval tv;
210 	const char *dot, *t;
211 	int century;
212 
213 	if (fmt != NULL) {
214 		lt = localtime(&tval);
215 		t = strptime(p, fmt, lt);
216 		if (t == NULL) {
217 			fprintf(stderr, "Failed conversion of ``%s''"
218 				" using format ``%s''\n", p, fmt);
219 			badformat();
220 		} else if (*t != '\0')
221 			fprintf(stderr, "Warning: Ignoring %ld extraneous"
222 				" characters in date string (%s)\n",
223 				(long) strlen(t), t);
224 	} else {
225 		for (t = p, dot = NULL; *t; ++t) {
226 			if (isdigit(*t))
227 				continue;
228 			if (*t == '.' && dot == NULL) {
229 				dot = t;
230 				continue;
231 			}
232 			badformat();
233 		}
234 
235 		lt = localtime(&tval);
236 
237 		if (dot != NULL) {			/* .ss */
238 			dot++; /* *dot++ = '\0'; */
239 			if (strlen(dot) != 2)
240 				badformat();
241 			lt->tm_sec = ATOI2(dot);
242 			if (lt->tm_sec > 61)
243 				badformat();
244 		} else
245 			lt->tm_sec = 0;
246 
247 		century = 0;
248 		/* if p has a ".ss" field then let's pretend it's not there */
249 		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
250 		case 12:				/* cc */
251 			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
252 			century = 1;
253 			/* FALLTHROUGH */
254 		case 10:				/* yy */
255 			if (century)
256 				lt->tm_year += ATOI2(p);
257 			else {				/* hack for 2000 ;-} */
258 				lt->tm_year = ATOI2(p);
259 				if (lt->tm_year < 69)
260 					lt->tm_year += 2000 - TM_YEAR_BASE;
261 				else
262 					lt->tm_year += 1900 - TM_YEAR_BASE;
263 			}
264 			/* FALLTHROUGH */
265 		case 8:					/* mm */
266 			lt->tm_mon = ATOI2(p);
267 			if (lt->tm_mon > 12)
268 				badformat();
269 			--lt->tm_mon;		/* time struct is 0 - 11 */
270 			/* FALLTHROUGH */
271 		case 6:					/* dd */
272 			lt->tm_mday = ATOI2(p);
273 			if (lt->tm_mday > 31)
274 				badformat();
275 			/* FALLTHROUGH */
276 		case 4:					/* HH */
277 			lt->tm_hour = ATOI2(p);
278 			if (lt->tm_hour > 23)
279 				badformat();
280 			/* FALLTHROUGH */
281 		case 2:					/* MM */
282 			lt->tm_min = ATOI2(p);
283 			if (lt->tm_min > 59)
284 				badformat();
285 			break;
286 		default:
287 			badformat();
288 		}
289 	}
290 
291 	/* Let mktime() decide whether summer time is in effect. */
292 	lt->tm_isdst = -1;
293 
294 	/* convert broken-down time to GMT clock time */
295 	if ((tval = mktime(lt)) == -1)
296 		errx(1, "nonexistent time");
297 
298 	if (!jflag) {
299 		logwtmpx("|", "date", "", 0, OLD_TIME);
300 		tv.tv_sec = tval;
301 		tv.tv_usec = 0;
302 		if (settimeofday(&tv, NULL))
303 			err(1, "settimeofday (timeval)");
304 		logwtmpx("{", "date", "", 0, NEW_TIME);
305 
306 		if ((p = getlogin()) == NULL)
307 			p = "???";
308 		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
309 	}
310 }
311 
312 static void
313 badformat(void)
314 {
315 	warnx("illegal time format");
316 	usage();
317 }
318 
319 static void
320 usage(void)
321 {
322 	fprintf(stderr, "%s\n%s\n",
323 	    "usage: date [-jnRu] [-r seconds] [-v[+|-]val[ymwdHMS]] ... ",
324 	    "            "
325 	    "[-I [date | hours | minutes | seconds]]"
326 	    "            "
327 	    "[-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]");
328 	exit(1);
329 }
330