xref: /freebsd/bin/date/date.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
33 static char const copyright[] =
34 "@(#) Copyright (c) 1985, 1987, 1988, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)date.c	8.2 (Berkeley) 4/28/95";
41 #endif /* not lint */
42 #endif
43 
44 #include <sys/cdefs.h>
45 #include <sys/param.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 
49 #include <ctype.h>
50 #include <err.h>
51 #include <locale.h>
52 #include <stdbool.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <syslog.h>
57 #include <unistd.h>
58 #include <utmpx.h>
59 
60 #include "vary.h"
61 
62 #ifndef	TM_YEAR_BASE
63 #define	TM_YEAR_BASE	1900
64 #endif
65 
66 static time_t tval;
67 
68 static void badformat(void);
69 static void iso8601_usage(const char *) __dead2;
70 static void multipleformats(void);
71 static void printdate(const char *);
72 static void printisodate(struct tm *);
73 static void setthetime(const char *, const char *, int);
74 static void usage(void) __dead2;
75 
76 static const struct iso8601_fmt {
77 	const char *refname;
78 	const char *format_string;
79 } iso8601_fmts[] = {
80 	{ "date", "%Y-%m-%d" },
81 	{ "hours", "T%H" },
82 	{ "minutes", ":%M" },
83 	{ "seconds", ":%S" },
84 };
85 static const struct iso8601_fmt *iso8601_selected;
86 
87 static const char *rfc2822_format = "%a, %d %b %Y %T %z";
88 
89 int
90 main(int argc, char *argv[])
91 {
92 	int ch, rflag;
93 	bool Iflag, jflag, Rflag;
94 	const char *format;
95 	char buf[1024];
96 	char *fmt, *outzone = NULL;
97 	char *tmp;
98 	struct vary *v;
99 	const struct vary *badv;
100 	struct tm *lt;
101 	struct stat sb;
102 	size_t i;
103 
104 	v = NULL;
105 	fmt = NULL;
106 	(void) setlocale(LC_TIME, "");
107 	rflag = 0;
108 	Iflag = jflag = Rflag = 0;
109 	while ((ch = getopt(argc, argv, "f:I::jnRr:uv:z:")) != -1)
110 		switch((char)ch) {
111 		case 'f':
112 			fmt = optarg;
113 			break;
114 		case 'I':
115 			if (Rflag)
116 				multipleformats();
117 			Iflag = 1;
118 			if (optarg == NULL) {
119 				iso8601_selected = iso8601_fmts;
120 				break;
121 			}
122 			for (i = 0; i < nitems(iso8601_fmts); i++)
123 				if (strcmp(optarg, iso8601_fmts[i].refname) == 0)
124 					break;
125 			if (i == nitems(iso8601_fmts))
126 				iso8601_usage(optarg);
127 
128 			iso8601_selected = &iso8601_fmts[i];
129 			break;
130 		case 'j':
131 			jflag = 1;	/* don't set time */
132 			break;
133 		case 'n':
134 			break;
135 		case 'R':		/* RFC 2822 datetime format */
136 			if (Iflag)
137 				multipleformats();
138 			Rflag = 1;
139 			break;
140 		case 'r':		/* user specified seconds */
141 			rflag = 1;
142 			tval = strtoq(optarg, &tmp, 0);
143 			if (*tmp != 0) {
144 				if (stat(optarg, &sb) == 0)
145 					tval = sb.st_mtim.tv_sec;
146 				else
147 					usage();
148 			}
149 			break;
150 		case 'u':		/* do everything in UTC */
151 			(void)setenv("TZ", "UTC0", 1);
152 			break;
153 		case 'z':
154 			outzone = optarg;
155 			break;
156 		case 'v':
157 			v = vary_append(v, optarg);
158 			break;
159 		default:
160 			usage();
161 		}
162 	argc -= optind;
163 	argv += optind;
164 
165 	if (!rflag && time(&tval) == -1)
166 		err(1, "time");
167 
168 	format = "%+";
169 
170 	if (Rflag)
171 		format = rfc2822_format;
172 
173 	/* allow the operands in any order */
174 	if (*argv && **argv == '+') {
175 		if (Iflag)
176 			multipleformats();
177 		format = *argv + 1;
178 		++argv;
179 	}
180 
181 	if (*argv) {
182 		setthetime(fmt, *argv, jflag);
183 		++argv;
184 	} else if (fmt != NULL)
185 		usage();
186 
187 	if (*argv && **argv == '+') {
188 		if (Iflag)
189 			multipleformats();
190 		format = *argv + 1;
191 	}
192 
193 	if (outzone != NULL && setenv("TZ", outzone, 1) != 0)
194 		err(1, "setenv(TZ)");
195 	lt = localtime(&tval);
196 	if (lt == NULL)
197 		errx(1, "invalid time");
198 	badv = vary_apply(v, lt);
199 	if (badv) {
200 		fprintf(stderr, "%s: Cannot apply date adjustment\n",
201 			badv->arg);
202 		vary_destroy(v);
203 		usage();
204 	}
205 	vary_destroy(v);
206 
207 	if (Iflag)
208 		printisodate(lt);
209 
210 	if (format == rfc2822_format)
211 		/*
212 		 * When using RFC 2822 datetime format, don't honor the
213 		 * locale.
214 		 */
215 		setlocale(LC_TIME, "C");
216 
217 
218 	(void)strftime(buf, sizeof(buf), format, lt);
219 	printdate(buf);
220 }
221 
222 static void
223 printdate(const char *buf)
224 {
225 	(void)printf("%s\n", buf);
226 	if (fflush(stdout))
227 		err(1, "stdout");
228 	exit(EXIT_SUCCESS);
229 }
230 
231 static void
232 printisodate(struct tm *lt)
233 {
234 	const struct iso8601_fmt *it;
235 	char fmtbuf[32], buf[32], tzbuf[8];
236 
237 	fmtbuf[0] = 0;
238 	for (it = iso8601_fmts; it <= iso8601_selected; it++)
239 		strlcat(fmtbuf, it->format_string, sizeof(fmtbuf));
240 
241 	(void)strftime(buf, sizeof(buf), fmtbuf, lt);
242 
243 	if (iso8601_selected > iso8601_fmts) {
244 		(void)strftime(tzbuf, sizeof(tzbuf), "%z", lt);
245 		memmove(&tzbuf[4], &tzbuf[3], 3);
246 		tzbuf[3] = ':';
247 		strlcat(buf, tzbuf, sizeof(buf));
248 	}
249 
250 	printdate(buf);
251 }
252 
253 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
254 
255 static void
256 setthetime(const char *fmt, const char *p, int jflag)
257 {
258 	struct utmpx utx;
259 	struct tm *lt;
260 	struct timeval tv;
261 	const char *dot, *t;
262 	int century;
263 
264 	lt = localtime(&tval);
265 	if (lt == NULL)
266 		errx(1, "invalid time");
267 	lt->tm_isdst = -1;		/* divine correct DST */
268 
269 	if (fmt != NULL) {
270 		t = strptime(p, fmt, lt);
271 		if (t == NULL) {
272 			fprintf(stderr, "Failed conversion of ``%s''"
273 				" using format ``%s''\n", p, fmt);
274 			badformat();
275 		} else if (*t != '\0')
276 			fprintf(stderr, "Warning: Ignoring %ld extraneous"
277 				" characters in date string (%s)\n",
278 				(long) strlen(t), t);
279 	} else {
280 		for (t = p, dot = NULL; *t; ++t) {
281 			if (isdigit(*t))
282 				continue;
283 			if (*t == '.' && dot == NULL) {
284 				dot = t;
285 				continue;
286 			}
287 			badformat();
288 		}
289 
290 		if (dot != NULL) {			/* .ss */
291 			dot++; /* *dot++ = '\0'; */
292 			if (strlen(dot) != 2)
293 				badformat();
294 			lt->tm_sec = ATOI2(dot);
295 			if (lt->tm_sec > 61)
296 				badformat();
297 		} else
298 			lt->tm_sec = 0;
299 
300 		century = 0;
301 		/* if p has a ".ss" field then let's pretend it's not there */
302 		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
303 		case 12:				/* cc */
304 			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
305 			century = 1;
306 			/* FALLTHROUGH */
307 		case 10:				/* yy */
308 			if (century)
309 				lt->tm_year += ATOI2(p);
310 			else {
311 				lt->tm_year = ATOI2(p);
312 				if (lt->tm_year < 69)	/* hack for 2000 ;-} */
313 					lt->tm_year += 2000 - TM_YEAR_BASE;
314 				else
315 					lt->tm_year += 1900 - TM_YEAR_BASE;
316 			}
317 			/* FALLTHROUGH */
318 		case 8:					/* mm */
319 			lt->tm_mon = ATOI2(p);
320 			if (lt->tm_mon > 12)
321 				badformat();
322 			--lt->tm_mon;		/* time struct is 0 - 11 */
323 			/* FALLTHROUGH */
324 		case 6:					/* dd */
325 			lt->tm_mday = ATOI2(p);
326 			if (lt->tm_mday > 31)
327 				badformat();
328 			/* FALLTHROUGH */
329 		case 4:					/* HH */
330 			lt->tm_hour = ATOI2(p);
331 			if (lt->tm_hour > 23)
332 				badformat();
333 			/* FALLTHROUGH */
334 		case 2:					/* MM */
335 			lt->tm_min = ATOI2(p);
336 			if (lt->tm_min > 59)
337 				badformat();
338 			break;
339 		default:
340 			badformat();
341 		}
342 	}
343 
344 	/* convert broken-down time to GMT clock time */
345 	if ((tval = mktime(lt)) == -1)
346 		errx(1, "nonexistent time");
347 
348 	if (!jflag) {
349 		utx.ut_type = OLD_TIME;
350 		memset(utx.ut_id, 0, sizeof(utx.ut_id));
351 		(void)gettimeofday(&utx.ut_tv, NULL);
352 		pututxline(&utx);
353 		tv.tv_sec = tval;
354 		tv.tv_usec = 0;
355 		if (settimeofday(&tv, NULL) != 0)
356 			err(1, "settimeofday (timeval)");
357 		utx.ut_type = NEW_TIME;
358 		(void)gettimeofday(&utx.ut_tv, NULL);
359 		pututxline(&utx);
360 
361 		if ((p = getlogin()) == NULL)
362 			p = "???";
363 		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
364 	}
365 }
366 
367 static void
368 badformat(void)
369 {
370 	warnx("illegal time format");
371 	usage();
372 }
373 
374 static void
375 iso8601_usage(const char *badarg)
376 {
377 	errx(1, "invalid argument '%s' for -I", badarg);
378 }
379 
380 static void
381 multipleformats(void)
382 {
383 	errx(1, "multiple output formats specified");
384 }
385 
386 static void
387 usage(void)
388 {
389 	(void)fprintf(stderr, "%s\n%s\n%s\n",
390 	    "usage: date [-jnRu] [-I[date|hours|minutes|seconds]] [-f input_fmt]",
391 	    "            "
392 	    "[ -z output_zone ] [-r filename|seconds] [-v[+|-]val[y|m|w|d|H|M|S]]",
393 	    "            "
394 	    "[[[[[[cc]yy]mm]dd]HH]MM[.SS] | new_date] [+output_fmt]"
395 	    );
396 	exit(1);
397 }
398