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