xref: /freebsd-14.2/bin/date/date.c (revision d2c02cfa)
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 <errno.h>
52 #include <locale.h>
53 #include <stdbool.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <syslog.h>
58 #include <unistd.h>
59 #include <utmpx.h>
60 
61 #include "vary.h"
62 
63 #ifndef	TM_YEAR_BASE
64 #define	TM_YEAR_BASE	1900
65 #endif
66 
67 static void badformat(void);
68 static void iso8601_usage(const char *) __dead2;
69 static void multipleformats(void);
70 static void printdate(const char *);
71 static void printisodate(struct tm *, long);
72 static void setthetime(const char *, const char *, int, struct timespec *);
73 static size_t strftime_ns(char * __restrict, size_t, const char * __restrict,
74     const struct tm * __restrict, long);
75 static void usage(void) __dead2;
76 
77 static const struct iso8601_fmt {
78 	const char *refname;
79 	const char *format_string;
80 } iso8601_fmts[] = {
81 	{ "date", "%Y-%m-%d" },
82 	{ "hours", "T%H" },
83 	{ "minutes", ":%M" },
84 	{ "seconds", ":%S" },
85 	{ "ns", ",%N" },
86 };
87 static const struct iso8601_fmt *iso8601_selected;
88 
89 static const char *rfc2822_format = "%a, %d %b %Y %T %z";
90 
91 int
main(int argc,char * argv[])92 main(int argc, char *argv[])
93 {
94 	struct timespec ts;
95 	int ch, rflag;
96 	bool Iflag, jflag, Rflag;
97 	const char *format;
98 	char buf[1024];
99 	char *fmt, *outzone = NULL;
100 	char *tmp;
101 	struct vary *v;
102 	const struct vary *badv;
103 	struct tm *lt;
104 	struct stat sb;
105 	size_t i;
106 
107 	v = NULL;
108 	fmt = NULL;
109 	(void) setlocale(LC_TIME, "");
110 	rflag = 0;
111 	Iflag = jflag = Rflag = 0;
112 	ts.tv_sec = 0;
113 	ts.tv_nsec = 0;
114 	while ((ch = getopt(argc, argv, "f:I::jnRr:uv:z:")) != -1)
115 		switch((char)ch) {
116 		case 'f':
117 			fmt = optarg;
118 			break;
119 		case 'I':
120 			if (Rflag)
121 				multipleformats();
122 			Iflag = 1;
123 			if (optarg == NULL) {
124 				iso8601_selected = iso8601_fmts;
125 				break;
126 			}
127 			for (i = 0; i < nitems(iso8601_fmts); i++)
128 				if (strcmp(optarg, iso8601_fmts[i].refname) == 0)
129 					break;
130 			if (i == nitems(iso8601_fmts))
131 				iso8601_usage(optarg);
132 
133 			iso8601_selected = &iso8601_fmts[i];
134 			break;
135 		case 'j':
136 			jflag = 1;	/* don't set time */
137 			break;
138 		case 'n':
139 			break;
140 		case 'R':		/* RFC 2822 datetime format */
141 			if (Iflag)
142 				multipleformats();
143 			Rflag = 1;
144 			break;
145 		case 'r':		/* user specified seconds */
146 			rflag = 1;
147 			ts.tv_sec = strtoq(optarg, &tmp, 0);
148 			if (*tmp != 0) {
149 				if (stat(optarg, &sb) == 0) {
150 					ts.tv_sec = sb.st_mtim.tv_sec;
151 					ts.tv_nsec = sb.st_mtim.tv_nsec;
152 				} else
153 					usage();
154 			}
155 			break;
156 		case 'u':		/* do everything in UTC */
157 			(void)setenv("TZ", "UTC0", 1);
158 			break;
159 		case 'z':
160 			outzone = optarg;
161 			break;
162 		case 'v':
163 			v = vary_append(v, optarg);
164 			break;
165 		default:
166 			usage();
167 		}
168 	argc -= optind;
169 	argv += optind;
170 
171 	if (!rflag && clock_gettime(CLOCK_REALTIME, &ts) == -1)
172 		err(1, "clock_gettime");
173 
174 	format = "%+";
175 
176 	if (Rflag)
177 		format = rfc2822_format;
178 
179 	/* allow the operands in any order */
180 	if (*argv && **argv == '+') {
181 		if (Iflag)
182 			multipleformats();
183 		format = *argv + 1;
184 		++argv;
185 	}
186 
187 	if (*argv) {
188 		setthetime(fmt, *argv, jflag, &ts);
189 		++argv;
190 	} else if (fmt != NULL)
191 		usage();
192 
193 	if (*argv && **argv == '+') {
194 		if (Iflag)
195 			multipleformats();
196 		format = *argv + 1;
197 	}
198 
199 	if (outzone != NULL && setenv("TZ", outzone, 1) != 0)
200 		err(1, "setenv(TZ)");
201 	lt = localtime(&ts.tv_sec);
202 	if (lt == NULL)
203 		errx(1, "invalid time");
204 	badv = vary_apply(v, lt);
205 	if (badv) {
206 		fprintf(stderr, "%s: Cannot apply date adjustment\n",
207 			badv->arg);
208 		vary_destroy(v);
209 		usage();
210 	}
211 	vary_destroy(v);
212 
213 	if (Iflag)
214 		printisodate(lt, ts.tv_nsec);
215 
216 	if (format == rfc2822_format)
217 		/*
218 		 * When using RFC 2822 datetime format, don't honor the
219 		 * locale.
220 		 */
221 		setlocale(LC_TIME, "C");
222 
223 
224 	(void)strftime_ns(buf, sizeof(buf), format, lt, ts.tv_nsec);
225 	printdate(buf);
226 }
227 
228 static void
printdate(const char * buf)229 printdate(const char *buf)
230 {
231 	(void)printf("%s\n", buf);
232 	if (fflush(stdout))
233 		err(1, "stdout");
234 	exit(EXIT_SUCCESS);
235 }
236 
237 static void
printisodate(struct tm * lt,long nsec)238 printisodate(struct tm *lt, long nsec)
239 {
240 	const struct iso8601_fmt *it;
241 	char fmtbuf[64], buf[64], tzbuf[8];
242 
243 	fmtbuf[0] = 0;
244 	for (it = iso8601_fmts; it <= iso8601_selected; it++)
245 		strlcat(fmtbuf, it->format_string, sizeof(fmtbuf));
246 
247 	(void)strftime_ns(buf, sizeof(buf), fmtbuf, lt, nsec);
248 
249 	if (iso8601_selected > iso8601_fmts) {
250 		(void)strftime_ns(tzbuf, sizeof(tzbuf), "%z", lt, nsec);
251 		memmove(&tzbuf[4], &tzbuf[3], 3);
252 		tzbuf[3] = ':';
253 		strlcat(buf, tzbuf, sizeof(buf));
254 	}
255 
256 	printdate(buf);
257 }
258 
259 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
260 
261 static void
setthetime(const char * fmt,const char * p,int jflag,struct timespec * ts)262 setthetime(const char *fmt, const char *p, int jflag, struct timespec *ts)
263 {
264 	struct utmpx utx;
265 	struct tm *lt;
266 	const char *dot, *t;
267 	int century;
268 
269 	lt = localtime(&ts->tv_sec);
270 	if (lt == NULL)
271 		errx(1, "invalid time");
272 	lt->tm_isdst = -1;		/* divine correct DST */
273 
274 	if (fmt != NULL) {
275 		t = strptime(p, fmt, lt);
276 		if (t == NULL) {
277 			fprintf(stderr, "Failed conversion of ``%s''"
278 				" using format ``%s''\n", p, fmt);
279 			badformat();
280 		} else if (*t != '\0')
281 			fprintf(stderr, "Warning: Ignoring %ld extraneous"
282 				" characters in date string (%s)\n",
283 				(long) strlen(t), t);
284 	} else {
285 		for (t = p, dot = NULL; *t; ++t) {
286 			if (isdigit(*t))
287 				continue;
288 			if (*t == '.' && dot == NULL) {
289 				dot = t;
290 				continue;
291 			}
292 			badformat();
293 		}
294 
295 		if (dot != NULL) {			/* .ss */
296 			dot++; /* *dot++ = '\0'; */
297 			if (strlen(dot) != 2)
298 				badformat();
299 			lt->tm_sec = ATOI2(dot);
300 			if (lt->tm_sec > 61)
301 				badformat();
302 		} else
303 			lt->tm_sec = 0;
304 
305 		century = 0;
306 		/* if p has a ".ss" field then let's pretend it's not there */
307 		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
308 		case 12:				/* cc */
309 			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
310 			century = 1;
311 			/* FALLTHROUGH */
312 		case 10:				/* yy */
313 			if (century)
314 				lt->tm_year += ATOI2(p);
315 			else {
316 				lt->tm_year = ATOI2(p);
317 				if (lt->tm_year < 69)	/* hack for 2000 ;-} */
318 					lt->tm_year += 2000 - TM_YEAR_BASE;
319 				else
320 					lt->tm_year += 1900 - TM_YEAR_BASE;
321 			}
322 			/* FALLTHROUGH */
323 		case 8:					/* mm */
324 			lt->tm_mon = ATOI2(p);
325 			if (lt->tm_mon > 12)
326 				badformat();
327 			--lt->tm_mon;		/* time struct is 0 - 11 */
328 			/* FALLTHROUGH */
329 		case 6:					/* dd */
330 			lt->tm_mday = ATOI2(p);
331 			if (lt->tm_mday > 31)
332 				badformat();
333 			/* FALLTHROUGH */
334 		case 4:					/* HH */
335 			lt->tm_hour = ATOI2(p);
336 			if (lt->tm_hour > 23)
337 				badformat();
338 			/* FALLTHROUGH */
339 		case 2:					/* MM */
340 			lt->tm_min = ATOI2(p);
341 			if (lt->tm_min > 59)
342 				badformat();
343 			break;
344 		default:
345 			badformat();
346 		}
347 	}
348 
349 	/* convert broken-down time to GMT clock time */
350 	lt->tm_yday = -1;
351 	ts->tv_sec = mktime(lt);
352 	if (lt->tm_yday == -1)
353 		errx(1, "nonexistent time");
354 	ts->tv_nsec = 0;
355 
356 	if (!jflag) {
357 		utx.ut_type = OLD_TIME;
358 		memset(utx.ut_id, 0, sizeof(utx.ut_id));
359 		(void)gettimeofday(&utx.ut_tv, NULL);
360 		pututxline(&utx);
361 		if (clock_settime(CLOCK_REALTIME, ts) != 0)
362 			err(1, "clock_settime");
363 		utx.ut_type = NEW_TIME;
364 		(void)gettimeofday(&utx.ut_tv, NULL);
365 		pututxline(&utx);
366 
367 		if ((p = getlogin()) == NULL)
368 			p = "???";
369 		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
370 	}
371 }
372 
373 /*
374  * The strftime_ns function is a wrapper around strftime(3), which adds support
375  * for features absent from strftime(3). Currently, the only extra feature is
376  * support for %N, the nanosecond conversion specification.
377  *
378  * The functions scans the format string for the non-standard conversion
379  * specifications and replaces them with the date and time values before
380  * passing the format string to strftime(3). The handling of the non-standard
381  * conversion specifications happens before the call to strftime(3) to handle
382  * cases like "%%N" correctly ("%%N" should yield "%N" instead of nanoseconds).
383  */
384 static size_t
strftime_ns(char * __restrict s,size_t maxsize,const char * __restrict format,const struct tm * __restrict t,long nsec)385 strftime_ns(char * __restrict s, size_t maxsize, const char * __restrict format,
386     const struct tm * __restrict t, long nsec)
387 {
388 	size_t prefixlen;
389 	size_t ret;
390 	char *newformat;
391 	char *oldformat;
392 	const char *prefix;
393 	const char *suffix;
394 	const char *tok;
395 	bool seen_percent;
396 
397 	seen_percent = false;
398 	if ((newformat = strdup(format)) == NULL)
399 		err(1, "strdup");
400 	tok = newformat;
401 	for (tok = newformat; *tok != '\0'; tok++) {
402 		switch (*tok) {
403 		case '%':
404 			/*
405 			 * If the previous token was a percent sign,
406 			 * then there are two percent tokens in a row.
407 			 */
408 			if (seen_percent)
409 				seen_percent = false;
410 			else
411 				seen_percent = true;
412 			break;
413 		case 'N':
414 			if (seen_percent) {
415 				oldformat = newformat;
416 				prefix = oldformat;
417 				prefixlen = tok - oldformat - 1;
418 				suffix = tok + 1;
419 				/*
420 				 * Construct a new format string from the
421 				 * prefix (i.e., the part of the old format
422 				 * from its beginning to the currently handled
423 				 * "%N" conversion specification), the
424 				 * nanoseconds, and the suffix (i.e., the part
425 				 * of the old format from the next token to the
426 				 * end).
427 				 */
428 				if (asprintf(&newformat, "%.*s%.9ld%s",
429 				    (int)prefixlen, prefix, nsec,
430 				    suffix) < 0) {
431 					err(1, "asprintf");
432 				}
433 				free(oldformat);
434 				tok = newformat + prefixlen + 9;
435 			}
436 			seen_percent = false;
437 			break;
438 		default:
439 			seen_percent = false;
440 			break;
441 		}
442 	}
443 
444 	ret = strftime(s, maxsize, newformat, t);
445 	free(newformat);
446 	return (ret);
447 }
448 
449 static void
badformat(void)450 badformat(void)
451 {
452 	warnx("illegal time format");
453 	usage();
454 }
455 
456 static void
iso8601_usage(const char * badarg)457 iso8601_usage(const char *badarg)
458 {
459 	errx(1, "invalid argument '%s' for -I", badarg);
460 }
461 
462 static void
multipleformats(void)463 multipleformats(void)
464 {
465 	errx(1, "multiple output formats specified");
466 }
467 
468 static void
usage(void)469 usage(void)
470 {
471 	(void)fprintf(stderr, "%s\n%s\n%s\n",
472 	    "usage: date [-jnRu] [-I[date|hours|minutes|seconds|ns]] [-f input_fmt]",
473 	    "            "
474 	    "[ -z output_zone ] [-r filename|seconds] [-v[+|-]val[y|m|w|d|H|M|S]]",
475 	    "            "
476 	    "[[[[[[cc]yy]mm]dd]HH]MM[.SS] | new_date] [+output_fmt]"
477 	    );
478 	exit(1);
479 }
480