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