1239313Sdim/*-
2239313Sdim * Copyright (c) 1985, 1987, 1988, 1993
3239313Sdim *	The Regents of the University of California.  All rights reserved.
4239313Sdim *
5239313Sdim * Redistribution and use in source and binary forms, with or without
6239313Sdim * modification, are permitted provided that the following conditions
7239313Sdim * are met:
8239313Sdim * 1. Redistributions of source code must retain the above copyright
9239313Sdim *    notice, this list of conditions and the following disclaimer.
10239313Sdim * 2. Redistributions in binary form must reproduce the above copyright
11239313Sdim *    notice, this list of conditions and the following disclaimer in the
12239313Sdim *    documentation and/or other materials provided with the distribution.
13239313Sdim * 4. Neither the name of the University nor the names of its contributors
14239313Sdim *    may be used to endorse or promote products derived from this software
15239313Sdim *    without specific prior written permission.
16239313Sdim *
17239313Sdim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18239313Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19239313Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20239313Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21239313Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22239313Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23239313Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24239313Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25239313Sdim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26239313Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27239313Sdim * SUCH DAMAGE.
28239313Sdim */
29239313Sdim
30239313Sdim#ifndef lint
31239313Sdimstatic char const copyright[] =
32239313Sdim"@(#) Copyright (c) 1985, 1987, 1988, 1993\n\
33239313Sdim	The Regents of the University of California.  All rights reserved.\n";
34239313Sdim#endif /* not lint */
35239313Sdim
36239313Sdim#if 0
37239313Sdim#ifndef lint
38239313Sdimstatic char sccsid[] = "@(#)date.c	8.2 (Berkeley) 4/28/95";
39239313Sdim#endif /* not lint */
40239313Sdim#endif
41239313Sdim
42239313Sdim#include <sys/cdefs.h>
43239313Sdim__FBSDID("$FreeBSD: stable/10/bin/date/date.c 323291 2017-09-07 23:28:35Z marius $");
44239313Sdim
45239313Sdim#include <sys/param.h>
46239313Sdim#include <sys/time.h>
47239313Sdim#include <sys/stat.h>
48239313Sdim
49239313Sdim#include <ctype.h>
50239313Sdim#include <err.h>
51239313Sdim#include <locale.h>
52239313Sdim#include <stdio.h>
53239313Sdim#include <stdlib.h>
54239313Sdim#include <string.h>
55239313Sdim#include <syslog.h>
56239313Sdim#include <unistd.h>
57239313Sdim#include <utmpx.h>
58239313Sdim
59239313Sdim#include "extern.h"
60239313Sdim#include "vary.h"
61239313Sdim
62239313Sdim#ifndef	TM_YEAR_BASE
63239313Sdim#define	TM_YEAR_BASE	1900
64239313Sdim#endif
65239313Sdim
66239313Sdimstatic time_t tval;
67239313Sdimint retval;
68239313Sdim
69239313Sdimstatic void setthetime(const char *, const char *, int, int);
70239313Sdimstatic void badformat(void);
71239313Sdimstatic void usage(void);
72239313Sdim
73239313Sdimstatic const char *rfc2822_format = "%a, %d %b %Y %T %z";
74239313Sdim
75239313Sdimint
76239313Sdimmain(int argc, char *argv[])
77239313Sdim{
78239313Sdim	struct timezone tz;
79239313Sdim	int ch, rflag;
80239313Sdim	int jflag, nflag, Rflag;
81239313Sdim	const char *format;
82239313Sdim	char buf[1024];
83239313Sdim	char *endptr, *fmt;
84239313Sdim	char *tmp;
85239313Sdim	int set_timezone;
86239313Sdim	struct vary *v;
87239313Sdim	const struct vary *badv;
88239313Sdim	struct tm *lt;
89239313Sdim	struct stat sb;
90239313Sdim
91	v = NULL;
92	fmt = NULL;
93	(void) setlocale(LC_TIME, "");
94	tz.tz_dsttime = tz.tz_minuteswest = 0;
95	rflag = 0;
96	jflag = nflag = Rflag = 0;
97	set_timezone = 0;
98	while ((ch = getopt(argc, argv, "d:f:jnRr:t:uv:")) != -1)
99		switch((char)ch) {
100		case 'd':		/* daylight savings time */
101			tz.tz_dsttime = strtol(optarg, &endptr, 10) ? 1 : 0;
102			if (endptr == optarg || *endptr != '\0')
103				usage();
104			set_timezone = 1;
105			break;
106		case 'f':
107			fmt = optarg;
108			break;
109		case 'j':
110			jflag = 1;	/* don't set time */
111			break;
112		case 'n':		/* don't set network */
113			nflag = 1;
114			break;
115		case 'R':		/* RFC 2822 datetime format */
116			Rflag = 1;
117			break;
118		case 'r':		/* user specified seconds */
119			rflag = 1;
120			tval = strtoq(optarg, &tmp, 0);
121			if (*tmp != 0) {
122				if (stat(optarg, &sb) == 0)
123					tval = sb.st_mtim.tv_sec;
124				else
125					usage();
126			}
127			break;
128		case 't':		/* minutes west of UTC */
129					/* error check; don't allow "PST" */
130			tz.tz_minuteswest = strtol(optarg, &endptr, 10);
131			if (endptr == optarg || *endptr != '\0')
132				usage();
133			set_timezone = 1;
134			break;
135		case 'u':		/* do everything in UTC */
136			(void)setenv("TZ", "UTC0", 1);
137			break;
138		case 'v':
139			v = vary_append(v, optarg);
140			break;
141		default:
142			usage();
143		}
144	argc -= optind;
145	argv += optind;
146
147	/*
148	 * If -d or -t, set the timezone or daylight savings time; this
149	 * doesn't belong here; the kernel should not know about either.
150	 */
151	if (set_timezone && settimeofday(NULL, &tz) != 0)
152		err(1, "settimeofday (timezone)");
153
154	if (!rflag && time(&tval) == -1)
155		err(1, "time");
156
157	format = "%+";
158
159	if (Rflag)
160		format = rfc2822_format;
161
162	/* allow the operands in any order */
163	if (*argv && **argv == '+') {
164		format = *argv + 1;
165		++argv;
166	}
167
168	if (*argv) {
169		setthetime(fmt, *argv, jflag, nflag);
170		++argv;
171	} else if (fmt != NULL)
172		usage();
173
174	if (*argv && **argv == '+')
175		format = *argv + 1;
176
177	lt = localtime(&tval);
178	if (lt == NULL)
179		errx(1, "invalid time");
180	badv = vary_apply(v, lt);
181	if (badv) {
182		fprintf(stderr, "%s: Cannot apply date adjustment\n",
183			badv->arg);
184		vary_destroy(v);
185		usage();
186	}
187	vary_destroy(v);
188
189	if (format == rfc2822_format)
190		/*
191		 * When using RFC 2822 datetime format, don't honor the
192		 * locale.
193		 */
194		setlocale(LC_TIME, "C");
195
196	(void)strftime(buf, sizeof(buf), format, lt);
197	(void)printf("%s\n", buf);
198	if (fflush(stdout))
199		err(1, "stdout");
200	exit(retval);
201}
202
203#define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
204
205static void
206setthetime(const char *fmt, const char *p, int jflag, int nflag)
207{
208	struct utmpx utx;
209	struct tm *lt;
210	struct timeval tv;
211	const char *dot, *t;
212	int century;
213
214	lt = localtime(&tval);
215	if (lt == NULL)
216		errx(1, "invalid time");
217	lt->tm_isdst = -1;		/* divine correct DST */
218
219	if (fmt != NULL) {
220		t = strptime(p, fmt, lt);
221		if (t == NULL) {
222			fprintf(stderr, "Failed conversion of ``%s''"
223				" using format ``%s''\n", p, fmt);
224			badformat();
225		} else if (*t != '\0')
226			fprintf(stderr, "Warning: Ignoring %ld extraneous"
227				" characters in date string (%s)\n",
228				(long) strlen(t), t);
229	} else {
230		for (t = p, dot = NULL; *t; ++t) {
231			if (isdigit(*t))
232				continue;
233			if (*t == '.' && dot == NULL) {
234				dot = t;
235				continue;
236			}
237			badformat();
238		}
239
240		if (dot != NULL) {			/* .ss */
241			dot++; /* *dot++ = '\0'; */
242			if (strlen(dot) != 2)
243				badformat();
244			lt->tm_sec = ATOI2(dot);
245			if (lt->tm_sec > 61)
246				badformat();
247		} else
248			lt->tm_sec = 0;
249
250		century = 0;
251		/* if p has a ".ss" field then let's pretend it's not there */
252		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
253		case 12:				/* cc */
254			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
255			century = 1;
256			/* FALLTHROUGH */
257		case 10:				/* yy */
258			if (century)
259				lt->tm_year += ATOI2(p);
260			else {
261				lt->tm_year = ATOI2(p);
262				if (lt->tm_year < 69)	/* hack for 2000 ;-} */
263					lt->tm_year += 2000 - TM_YEAR_BASE;
264				else
265					lt->tm_year += 1900 - TM_YEAR_BASE;
266			}
267			/* FALLTHROUGH */
268		case 8:					/* mm */
269			lt->tm_mon = ATOI2(p);
270			if (lt->tm_mon > 12)
271				badformat();
272			--lt->tm_mon;		/* time struct is 0 - 11 */
273			/* FALLTHROUGH */
274		case 6:					/* dd */
275			lt->tm_mday = ATOI2(p);
276			if (lt->tm_mday > 31)
277				badformat();
278			/* FALLTHROUGH */
279		case 4:					/* HH */
280			lt->tm_hour = ATOI2(p);
281			if (lt->tm_hour > 23)
282				badformat();
283			/* FALLTHROUGH */
284		case 2:					/* MM */
285			lt->tm_min = ATOI2(p);
286			if (lt->tm_min > 59)
287				badformat();
288			break;
289		default:
290			badformat();
291		}
292	}
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		/* set the time */
300		if (nflag || netsettime(tval)) {
301			utx.ut_type = OLD_TIME;
302			(void)gettimeofday(&utx.ut_tv, NULL);
303			pututxline(&utx);
304			tv.tv_sec = tval;
305			tv.tv_usec = 0;
306			if (settimeofday(&tv, NULL) != 0)
307				err(1, "settimeofday (timeval)");
308			utx.ut_type = NEW_TIME;
309			(void)gettimeofday(&utx.ut_tv, NULL);
310			pututxline(&utx);
311		}
312
313		if ((p = getlogin()) == NULL)
314			p = "???";
315		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
316	}
317}
318
319static void
320badformat(void)
321{
322	warnx("illegal time format");
323	usage();
324}
325
326static void
327usage(void)
328{
329	(void)fprintf(stderr, "%s\n%s\n",
330	    "usage: date [-jnRu] [-d dst] [-r seconds] [-t west] "
331	    "[-v[+|-]val[ymwdHMS]] ... ",
332	    "            "
333	    "[-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]");
334	exit(1);
335}
336