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