xref: /freebsd/bin/date/date.c (revision 3193579b66fd7067f898dbc54bdea81a0e6f9bd0)
1 /*
2  * Copyright (c) 1985, 1987, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static char const copyright[] =
36 "@(#) Copyright (c) 1985, 1987, 1988, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #if 0
41 #ifndef lint
42 static char sccsid[] = "@(#)date.c	8.2 (Berkeley) 4/28/95";
43 #endif /* not lint */
44 #endif
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/time.h>
51 
52 #include <ctype.h>
53 #include <err.h>
54 #include <locale.h>
55 #include <libutil.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <syslog.h>
60 #include <unistd.h>
61 
62 #include "extern.h"
63 #include "vary.h"
64 
65 #ifndef	TM_YEAR_BASE
66 #define	TM_YEAR_BASE	1900
67 #endif
68 
69 static time_t tval;
70 int retval;
71 
72 static void setthetime(const char *, const char *, int, int);
73 static void badformat(void);
74 static void usage(void);
75 
76 int
77 main(int argc, char *argv[])
78 {
79 	struct timezone tz;
80 	int ch, rflag;
81 	int jflag, nflag;
82 	const char *format;
83 	char buf[1024];
84 	char *endptr, *fmt;
85 	char *tmp;
86 	int set_timezone;
87 	struct vary *v;
88 	const struct vary *badv;
89 	struct tm lt;
90 
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 = 0;
97 	set_timezone = 0;
98 	while ((ch = getopt(argc, argv, "d:f:jnr: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':		/* user specified seconds */
116 			rflag = 1;
117 			tval = strtoq(optarg, &tmp, 0);
118 			if (*tmp != 0)
119 				usage();
120 			break;
121 		case 't':		/* minutes west of UTC */
122 					/* error check; don't allow "PST" */
123 			tz.tz_minuteswest = strtol(optarg, &endptr, 10);
124 			if (endptr == optarg || *endptr != '\0')
125 				usage();
126 			set_timezone = 1;
127 			break;
128 		case 'u':		/* do everything in UTC */
129 			(void)setenv("TZ", "UTC0", 1);
130 			break;
131 		case 'v':
132 			v = vary_append(v, optarg);
133 			break;
134 		default:
135 			usage();
136 		}
137 	argc -= optind;
138 	argv += optind;
139 
140 	/*
141 	 * If -d or -t, set the timezone or daylight savings time; this
142 	 * doesn't belong here; the kernel should not know about either.
143 	 */
144 	if (set_timezone && settimeofday((struct timeval *)NULL, &tz))
145 		err(1, "settimeofday (timezone)");
146 
147 	if (!rflag && time(&tval) == -1)
148 		err(1, "time");
149 
150 	format = "%+";
151 
152 	/* allow the operands in any order */
153 	if (*argv && **argv == '+') {
154 		format = *argv + 1;
155 		++argv;
156 	}
157 
158 	if (*argv) {
159 		setthetime(fmt, *argv, jflag, nflag);
160 		++argv;
161 	} else if (fmt != NULL)
162 		usage();
163 
164 	if (*argv && **argv == '+')
165 		format = *argv + 1;
166 
167 	lt = *localtime(&tval);
168 	badv = vary_apply(v, &lt);
169 	if (badv) {
170 		fprintf(stderr, "%s: Cannot apply date adjustment\n",
171 			badv->arg);
172 		vary_destroy(v);
173 		usage();
174 	}
175 	vary_destroy(v);
176 	(void)strftime(buf, sizeof(buf), format, &lt);
177 	(void)printf("%s\n", buf);
178 	if (fflush(stdout))
179 		err(1, "stdout");
180 	exit(retval);
181 }
182 
183 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
184 
185 static void
186 setthetime(const char *fmt, const char *p, int jflag, int nflag)
187 {
188 	struct tm *lt;
189 	struct timeval tv;
190 	const char *dot, *t;
191 	int century;
192 
193 	if (fmt != NULL) {
194 		lt = localtime(&tval);
195 		t = strptime(p, fmt, lt);
196 		if (t == NULL) {
197 			fprintf(stderr, "Failed conversion of ``%s''"
198 				" using format ``%s''\n", p, fmt);
199 			badformat();
200 		} else if (*t != '\0')
201 			fprintf(stderr, "Warning: Ignoring %ld extraneous"
202 				" characters in date string (%s)\n",
203 				(long) strlen(t), t);
204 	} else {
205 		for (t = p, dot = NULL; *t; ++t) {
206 			if (isdigit(*t))
207 				continue;
208 			if (*t == '.' && dot == NULL) {
209 				dot = t;
210 				continue;
211 			}
212 			badformat();
213 		}
214 
215 		lt = localtime(&tval);
216 
217 		if (dot != NULL) {			/* .ss */
218 			dot++; /* *dot++ = '\0'; */
219 			if (strlen(dot) != 2)
220 				badformat();
221 			lt->tm_sec = ATOI2(dot);
222 			if (lt->tm_sec > 61)
223 				badformat();
224 		} else
225 			lt->tm_sec = 0;
226 
227 		century = 0;
228 		/* if p has a ".ss" field then let's pretend it's not there */
229 		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
230 		case 12:				/* cc */
231 			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
232 			century = 1;
233 			/* FALLTHROUGH */
234 		case 10:				/* yy */
235 			if (century)
236 				lt->tm_year += ATOI2(p);
237 			else {				/* hack for 2000 ;-} */
238 				lt->tm_year = ATOI2(p);
239 				if (lt->tm_year < 69)
240 					lt->tm_year += 2000 - TM_YEAR_BASE;
241 				else
242 					lt->tm_year += 1900 - TM_YEAR_BASE;
243 			}
244 			/* FALLTHROUGH */
245 		case 8:					/* mm */
246 			lt->tm_mon = ATOI2(p);
247 			if (lt->tm_mon > 12)
248 				badformat();
249 			--lt->tm_mon;		/* time struct is 0 - 11 */
250 			/* FALLTHROUGH */
251 		case 6:					/* dd */
252 			lt->tm_mday = ATOI2(p);
253 			if (lt->tm_mday > 31)
254 				badformat();
255 			/* FALLTHROUGH */
256 		case 4:					/* HH */
257 			lt->tm_hour = ATOI2(p);
258 			if (lt->tm_hour > 23)
259 				badformat();
260 			/* FALLTHROUGH */
261 		case 2:					/* MM */
262 			lt->tm_min = ATOI2(p);
263 			if (lt->tm_min > 59)
264 				badformat();
265 			break;
266 		default:
267 			badformat();
268 		}
269 	}
270 
271 	/* Let mktime() decide whether summer time is in effect. */
272 	lt->tm_isdst = -1;
273 
274 	/* convert broken-down time to GMT clock time */
275 	if ((tval = mktime(lt)) == -1)
276 		errx(1, "nonexistent time");
277 
278 	if (!jflag) {
279 		/* set the time */
280 		if (nflag || netsettime(tval)) {
281 			logwtmp("|", "date", "");
282 			tv.tv_sec = tval;
283 			tv.tv_usec = 0;
284 			if (settimeofday(&tv, (struct timezone *)NULL))
285 				err(1, "settimeofday (timeval)");
286 			logwtmp("{", "date", "");
287 		}
288 
289 		if ((p = getlogin()) == NULL)
290 			p = "???";
291 		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
292 	}
293 }
294 
295 static void
296 badformat(void)
297 {
298 	warnx("illegal time format");
299 	usage();
300 }
301 
302 static void
303 usage(void)
304 {
305 	(void)fprintf(stderr, "%s\n%s\n",
306 	    "usage: date [-jnu] [-d dst] [-r seconds] [-t west] "
307 	    "[-v[+|-]val[ymwdHMS]] ... ",
308 	    "            "
309 	    "[-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]");
310 	exit(1);
311 }
312