xref: /freebsd/bin/date/date.c (revision 4f52dfbb)
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 <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <syslog.h>
58 #include <unistd.h>
59 #include <utmpx.h>
60 
61 #include "extern.h"
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 int retval;
70 
71 static void setthetime(const char *, const char *, int, int);
72 static void badformat(void);
73 static void usage(void);
74 
75 static const char *rfc2822_format = "%a, %d %b %Y %T %z";
76 
77 int
78 main(int argc, char *argv[])
79 {
80 	struct timezone tz;
81 	int ch, rflag;
82 	int jflag, nflag, Rflag;
83 	const char *format;
84 	char buf[1024];
85 	char *endptr, *fmt;
86 	char *tmp;
87 	int set_timezone;
88 	struct vary *v;
89 	const struct vary *badv;
90 	struct tm *lt;
91 	struct stat sb;
92 
93 	v = NULL;
94 	fmt = NULL;
95 	(void) setlocale(LC_TIME, "");
96 	tz.tz_dsttime = tz.tz_minuteswest = 0;
97 	rflag = 0;
98 	jflag = nflag = Rflag = 0;
99 	set_timezone = 0;
100 	while ((ch = getopt(argc, argv, "d:f:jnRr:t:uv:")) != -1)
101 		switch((char)ch) {
102 		case 'd':		/* daylight savings time */
103 			tz.tz_dsttime = strtol(optarg, &endptr, 10) ? 1 : 0;
104 			if (endptr == optarg || *endptr != '\0')
105 				usage();
106 			set_timezone = 1;
107 			break;
108 		case 'f':
109 			fmt = optarg;
110 			break;
111 		case 'j':
112 			jflag = 1;	/* don't set time */
113 			break;
114 		case 'n':		/* don't set network */
115 			nflag = 1;
116 			break;
117 		case 'R':		/* RFC 2822 datetime format */
118 			Rflag = 1;
119 			break;
120 		case 'r':		/* user specified seconds */
121 			rflag = 1;
122 			tval = strtoq(optarg, &tmp, 0);
123 			if (*tmp != 0) {
124 				if (stat(optarg, &sb) == 0)
125 					tval = sb.st_mtim.tv_sec;
126 				else
127 					usage();
128 			}
129 			break;
130 		case 't':		/* minutes west of UTC */
131 					/* error check; don't allow "PST" */
132 			tz.tz_minuteswest = strtol(optarg, &endptr, 10);
133 			if (endptr == optarg || *endptr != '\0')
134 				usage();
135 			set_timezone = 1;
136 			break;
137 		case 'u':		/* do everything in UTC */
138 			(void)setenv("TZ", "UTC0", 1);
139 			break;
140 		case 'v':
141 			v = vary_append(v, optarg);
142 			break;
143 		default:
144 			usage();
145 		}
146 	argc -= optind;
147 	argv += optind;
148 
149 	/*
150 	 * If -d or -t, set the timezone or daylight savings time; this
151 	 * doesn't belong here; the kernel should not know about either.
152 	 */
153 	if (set_timezone && settimeofday(NULL, &tz) != 0)
154 		err(1, "settimeofday (timezone)");
155 
156 	if (!rflag && time(&tval) == -1)
157 		err(1, "time");
158 
159 	format = "%+";
160 
161 	if (Rflag)
162 		format = rfc2822_format;
163 
164 	/* allow the operands in any order */
165 	if (*argv && **argv == '+') {
166 		format = *argv + 1;
167 		++argv;
168 	}
169 
170 	if (*argv) {
171 		setthetime(fmt, *argv, jflag, nflag);
172 		++argv;
173 	} else if (fmt != NULL)
174 		usage();
175 
176 	if (*argv && **argv == '+')
177 		format = *argv + 1;
178 
179 	lt = localtime(&tval);
180 	if (lt == NULL)
181 		errx(1, "invalid time");
182 	badv = vary_apply(v, lt);
183 	if (badv) {
184 		fprintf(stderr, "%s: Cannot apply date adjustment\n",
185 			badv->arg);
186 		vary_destroy(v);
187 		usage();
188 	}
189 	vary_destroy(v);
190 
191 	if (format == rfc2822_format)
192 		/*
193 		 * When using RFC 2822 datetime format, don't honor the
194 		 * locale.
195 		 */
196 		setlocale(LC_TIME, "C");
197 
198 	(void)strftime(buf, sizeof(buf), format, lt);
199 	(void)printf("%s\n", buf);
200 	if (fflush(stdout))
201 		err(1, "stdout");
202 	exit(retval);
203 }
204 
205 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
206 
207 static void
208 setthetime(const char *fmt, const char *p, int jflag, int nflag)
209 {
210 	struct utmpx utx;
211 	struct tm *lt;
212 	struct timeval tv;
213 	const char *dot, *t;
214 	int century;
215 
216 	lt = localtime(&tval);
217 	if (lt == NULL)
218 		errx(1, "invalid time");
219 	lt->tm_isdst = -1;		/* divine correct DST */
220 
221 	if (fmt != NULL) {
222 		t = strptime(p, fmt, lt);
223 		if (t == NULL) {
224 			fprintf(stderr, "Failed conversion of ``%s''"
225 				" using format ``%s''\n", p, fmt);
226 			badformat();
227 		} else if (*t != '\0')
228 			fprintf(stderr, "Warning: Ignoring %ld extraneous"
229 				" characters in date string (%s)\n",
230 				(long) strlen(t), t);
231 	} else {
232 		for (t = p, dot = NULL; *t; ++t) {
233 			if (isdigit(*t))
234 				continue;
235 			if (*t == '.' && dot == NULL) {
236 				dot = t;
237 				continue;
238 			}
239 			badformat();
240 		}
241 
242 		if (dot != NULL) {			/* .ss */
243 			dot++; /* *dot++ = '\0'; */
244 			if (strlen(dot) != 2)
245 				badformat();
246 			lt->tm_sec = ATOI2(dot);
247 			if (lt->tm_sec > 61)
248 				badformat();
249 		} else
250 			lt->tm_sec = 0;
251 
252 		century = 0;
253 		/* if p has a ".ss" field then let's pretend it's not there */
254 		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
255 		case 12:				/* cc */
256 			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
257 			century = 1;
258 			/* FALLTHROUGH */
259 		case 10:				/* yy */
260 			if (century)
261 				lt->tm_year += ATOI2(p);
262 			else {
263 				lt->tm_year = ATOI2(p);
264 				if (lt->tm_year < 69)	/* hack for 2000 ;-} */
265 					lt->tm_year += 2000 - TM_YEAR_BASE;
266 				else
267 					lt->tm_year += 1900 - TM_YEAR_BASE;
268 			}
269 			/* FALLTHROUGH */
270 		case 8:					/* mm */
271 			lt->tm_mon = ATOI2(p);
272 			if (lt->tm_mon > 12)
273 				badformat();
274 			--lt->tm_mon;		/* time struct is 0 - 11 */
275 			/* FALLTHROUGH */
276 		case 6:					/* dd */
277 			lt->tm_mday = ATOI2(p);
278 			if (lt->tm_mday > 31)
279 				badformat();
280 			/* FALLTHROUGH */
281 		case 4:					/* HH */
282 			lt->tm_hour = ATOI2(p);
283 			if (lt->tm_hour > 23)
284 				badformat();
285 			/* FALLTHROUGH */
286 		case 2:					/* MM */
287 			lt->tm_min = ATOI2(p);
288 			if (lt->tm_min > 59)
289 				badformat();
290 			break;
291 		default:
292 			badformat();
293 		}
294 	}
295 
296 	/* convert broken-down time to GMT clock time */
297 	if ((tval = mktime(lt)) == -1)
298 		errx(1, "nonexistent time");
299 
300 	if (!jflag) {
301 		/* set the time */
302 		if (nflag || netsettime(tval)) {
303 			utx.ut_type = OLD_TIME;
304 			memset(utx.ut_id, 0, sizeof(utx.ut_id));
305 			(void)gettimeofday(&utx.ut_tv, NULL);
306 			pututxline(&utx);
307 			tv.tv_sec = tval;
308 			tv.tv_usec = 0;
309 			if (settimeofday(&tv, NULL) != 0)
310 				err(1, "settimeofday (timeval)");
311 			utx.ut_type = NEW_TIME;
312 			(void)gettimeofday(&utx.ut_tv, NULL);
313 			pututxline(&utx);
314 		}
315 
316 		if ((p = getlogin()) == NULL)
317 			p = "???";
318 		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
319 	}
320 }
321 
322 static void
323 badformat(void)
324 {
325 	warnx("illegal time format");
326 	usage();
327 }
328 
329 static void
330 usage(void)
331 {
332 	(void)fprintf(stderr, "%s\n%s\n",
333 	    "usage: date [-jnRu] [-d dst] [-r seconds] [-t west] "
334 	    "[-v[+|-]val[ymwdHMS]] ... ",
335 	    "            "
336 	    "[-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]");
337 	exit(1);
338 }
339