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