xref: /openbsd-src/bin/date/date.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: date.c,v 1.43 2014/01/21 09:09:15 otto Exp $	*/
2 /*	$NetBSD: date.c,v 1.11 1995/09/07 06:21:05 jtc Exp $	*/
3 
4 /*
5  * Copyright (c) 1985, 1987, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/types.h>
34 #include <sys/time.h>
35 
36 #include <ctype.h>
37 #include <err.h>
38 #include <fcntl.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <locale.h>
43 #include <syslog.h>
44 #include <time.h>
45 #include <tzfile.h>
46 #include <unistd.h>
47 #include <util.h>
48 
49 extern	char *__progname;
50 
51 time_t tval;
52 int jflag;
53 int slidetime;
54 
55 static void setthetime(char *);
56 static void badformat(void);
57 static void usage(void);
58 
59 int
60 main(int argc, char *argv[])
61 {
62 	struct timezone tz;
63 	struct tm *tp;
64 	int ch, rflag;
65 	char *format, buf[1024], *outzone = NULL;
66 
67 	setlocale(LC_ALL, "");
68 
69 	tz.tz_dsttime = tz.tz_minuteswest = 0;
70 	rflag = 0;
71 	while ((ch = getopt(argc, argv, "ad:jr:ut:z:")) != -1)
72 		switch(ch) {
73 		case 'd':		/* daylight saving time */
74 			tz.tz_dsttime = atoi(optarg) ? 1 : 0;
75 			break;
76 		case 'a':
77 			slidetime++;
78 			break;
79 		case 'j':		/* don't set */
80 			jflag = 1;
81 			break;
82 		case 'r':		/* user specified seconds */
83 			rflag = 1;
84 			tval = atoll(optarg);
85 			break;
86 		case 'u':		/* do everything in UTC */
87 			if (setenv("TZ", "UTC", 1) == -1)
88 				err(1, "cannot unsetenv TZ");
89 			break;
90 		case 't':		/* minutes west of GMT */
91 					/* error check; don't allow "PST" */
92 			if (isdigit((unsigned char)*optarg)) {
93 				tz.tz_minuteswest = atoi(optarg);
94 				break;
95 			}
96 			/* FALLTHROUGH */
97 		case 'z':
98 			outzone = optarg;
99 			break;
100 		default:
101 			usage();
102 		}
103 	argc -= optind;
104 	argv += optind;
105 
106 	/*
107 	 * If -d or -t, set the timezone or daylight saving time; this
108 	 * doesn't belong here, the kernel should not know about either.
109 	 */
110 	if ((tz.tz_minuteswest || tz.tz_dsttime) &&
111 	    settimeofday(NULL, &tz))
112 		err(1, "settimeofday");
113 
114 	if (!rflag && time(&tval) == -1)
115 		err(1, "time");
116 
117 	format = "%a %b %e %H:%M:%S %Z %Y";
118 
119 	/* allow the operands in any order */
120 	if (*argv && **argv == '+') {
121 		format = *argv + 1;
122 		argv++;
123 		argc--;
124 	}
125 
126 	if (*argv) {
127 		setthetime(*argv);
128 		argv++;
129 		argc--;
130 	}
131 
132 	if (*argv && **argv == '+') {
133 		format = *argv + 1;
134 		argc--;
135 	}
136 
137 	if (argc > 0)
138 		errx(1, "too many arguments");
139 
140 	if (outzone)
141 		setenv("TZ", outzone, 1);
142 
143 	tp = localtime(&tval);
144 	if (tp == NULL)
145 		errx(1, "conversion error");
146 	(void)strftime(buf, sizeof(buf), format, tp);
147 	(void)printf("%s\n", buf);
148 	exit(0);
149 }
150 
151 #define	ATOI2(ar)	((ar) += 2, ((ar)[-2] - '0') * 10 + ((ar)[-1] - '0'))
152 void
153 setthetime(char *p)
154 {
155 	struct tm *lt;
156 	struct timeval tv;
157 	char *dot, *t;
158 	int yearset = 0;
159 
160 	for (t = p, dot = NULL; *t; ++t) {
161 		if (isdigit((unsigned char)*t))
162 			continue;
163 		if (*t == '.' && dot == NULL) {
164 			dot = t;
165 			continue;
166 		}
167 		badformat();
168 	}
169 
170 	lt = localtime(&tval);
171 
172 	lt->tm_isdst = -1;			/* correct for DST */
173 
174 	if (dot != NULL) {			/* .SS */
175 		*dot++ = '\0';
176 		if (strlen(dot) != 2)
177 			badformat();
178 		lt->tm_sec = ATOI2(dot);
179 		if (lt->tm_sec > 61)
180 			badformat();
181 	} else
182 		lt->tm_sec = 0;
183 
184 	switch (strlen(p)) {
185 	case 12:				/* cc */
186 		lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
187 		yearset = 1;
188 		/* FALLTHROUGH */
189 	case 10:				/* yy */
190 		if (!yearset) {
191 			/* mask out current year, leaving only century */
192 			lt->tm_year = ((lt->tm_year / 100) * 100);
193 		}
194 		lt->tm_year += ATOI2(p);
195 		/* FALLTHROUGH */
196 	case 8:					/* mm */
197 		lt->tm_mon = ATOI2(p);
198 		if ((lt->tm_mon > 12) || !lt->tm_mon)
199 			badformat();
200 		--lt->tm_mon;			/* time struct is 0 - 11 */
201 		/* FALLTHROUGH */
202 	case 6:					/* dd */
203 		lt->tm_mday = ATOI2(p);
204 		if ((lt->tm_mday > 31) || !lt->tm_mday)
205 			badformat();
206 		/* FALLTHROUGH */
207 	case 4:					/* HH */
208 		lt->tm_hour = ATOI2(p);
209 		if (lt->tm_hour > 23)
210 			badformat();
211 		/* FALLTHROUGH */
212 	case 2:					/* MM */
213 		lt->tm_min = ATOI2(p);
214 		if (lt->tm_min > 59)
215 			badformat();
216 		break;
217 	default:
218 		badformat();
219 	}
220 
221 	/* convert broken-down time to UTC clock time */
222 	if ((tval = mktime(lt)) < 0)
223 		errx(1, "specified date is outside allowed range");
224 
225 	if (jflag)
226 		return;
227 
228 	/* set the time */
229 	if (slidetime) {
230 		struct timeval tv_current;
231 
232 		if (gettimeofday(&tv_current, NULL) == -1)
233 			err(1, "Could not get local time of day");
234 
235 		tv.tv_sec = tval - tv_current.tv_sec;
236 		tv.tv_usec = 0;
237 		if (adjtime(&tv, NULL) == -1)
238 			errx(1, "adjtime");
239 	} else {
240 #ifndef SMALL
241 		logwtmp("|", "date", "");
242 #endif
243 		tv.tv_sec = tval;
244 		tv.tv_usec = 0;
245 		if (settimeofday(&tv, NULL))
246 			err(1, "settimeofday");
247 #ifndef SMALL
248 		logwtmp("{", "date", "");
249 #endif
250 	}
251 
252 	if ((p = getlogin()) == NULL)
253 		p = "???";
254 	syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
255 }
256 
257 static void
258 badformat(void)
259 {
260 	warnx("illegal time format");
261 	usage();
262 }
263 
264 static void
265 usage(void)
266 {
267 	(void)fprintf(stderr,
268 	    "usage: %s [-aju] [-d dst] [-r seconds] [-t minutes_west] [-z output_zone]\n",
269 	     __progname);
270 	(void)fprintf(stderr,
271 	    "%-*s[+format] [[[[[[cc]yy]mm]dd]HH]MM[.SS]]\n", (int)strlen(__progname) + 8, "");
272 	exit(1);
273 }
274