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