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