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