]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/date/date.c
Remove -n flag, fix setting date / time
[FreeBSD/FreeBSD.git] / bin / date / date.c
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 <stdbool.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <syslog.h>
59 #include <unistd.h>
60 #include <utmpx.h>
61
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
70 static void badformat(void);
71 static void iso8601_usage(const char *);
72 static void multipleformats(void);
73 static void printdate(const char *);
74 static void printisodate(struct tm *);
75 static void setthetime(const char *, const char *, int);
76 static void usage(void);
77
78 static const struct iso8601_fmt {
79         const char *refname;
80         const char *format_string;
81 } iso8601_fmts[] = {
82         { "date", "%Y-%m-%d" },
83         { "hours", "T%H" },
84         { "minutes", ":%M" },
85         { "seconds", ":%S" },
86 };
87 static const struct iso8601_fmt *iso8601_selected;
88
89 static const char *rfc2822_format = "%a, %d %b %Y %T %z";
90
91 int
92 main(int argc, char *argv[])
93 {
94         int ch, rflag;
95         bool Iflag, jflag, Rflag;
96         const char *format;
97         char buf[1024];
98         char *fmt;
99         char *tmp;
100         struct vary *v;
101         const struct vary *badv;
102         struct tm *lt;
103         struct stat sb;
104         size_t i;
105
106         v = NULL;
107         fmt = NULL;
108         (void) setlocale(LC_TIME, "");
109         rflag = 0;
110         Iflag = jflag = Rflag = 0;
111         while ((ch = getopt(argc, argv, "f:I::jRr:uv:")) != -1)
112                 switch((char)ch) {
113                 case 'f':
114                         fmt = optarg;
115                         break;
116                 case 'I':
117                         if (Rflag)
118                                 multipleformats();
119                         Iflag = 1;
120                         if (optarg == NULL) {
121                                 iso8601_selected = iso8601_fmts;
122                                 break;
123                         }
124                         for (i = 0; i < nitems(iso8601_fmts); i++)
125                                 if (strcmp(optarg, iso8601_fmts[i].refname) == 0)
126                                         break;
127                         if (i == nitems(iso8601_fmts))
128                                 iso8601_usage(optarg);
129
130                         iso8601_selected = &iso8601_fmts[i];
131                         break;
132                 case 'j':
133                         jflag = 1;      /* don't set time */
134                         break;
135                 case 'R':               /* RFC 2822 datetime format */
136                         if (Iflag)
137                                 multipleformats();
138                         Rflag = 1;
139                         break;
140                 case 'r':               /* user specified seconds */
141                         rflag = 1;
142                         tval = strtoq(optarg, &tmp, 0);
143                         if (*tmp != 0) {
144                                 if (stat(optarg, &sb) == 0)
145                                         tval = sb.st_mtim.tv_sec;
146                                 else
147                                         usage();
148                         }
149                         break;
150                 case 'u':               /* do everything in UTC */
151                         (void)setenv("TZ", "UTC0", 1);
152                         break;
153                 case 'v':
154                         v = vary_append(v, optarg);
155                         break;
156                 default:
157                         usage();
158                 }
159         argc -= optind;
160         argv += optind;
161
162         if (!rflag && time(&tval) == -1)
163                 err(1, "time");
164
165         format = "%+";
166
167         if (Rflag)
168                 format = rfc2822_format;
169
170         /* allow the operands in any order */
171         if (*argv && **argv == '+') {
172                 if (Iflag)
173                         multipleformats();
174                 format = *argv + 1;
175                 ++argv;
176         }
177
178         if (*argv) {
179                 setthetime(fmt, *argv, jflag);
180                 ++argv;
181         } else if (fmt != NULL)
182                 usage();
183
184         if (*argv && **argv == '+') {
185                 if (Iflag)
186                         multipleformats();
187                 format = *argv + 1;
188         }
189
190         lt = localtime(&tval);
191         if (lt == NULL)
192                 errx(1, "invalid time");
193         badv = vary_apply(v, lt);
194         if (badv) {
195                 fprintf(stderr, "%s: Cannot apply date adjustment\n",
196                         badv->arg);
197                 vary_destroy(v);
198                 usage();
199         }
200         vary_destroy(v);
201
202         if (Iflag)
203                 printisodate(lt);
204
205         if (format == rfc2822_format)
206                 /*
207                  * When using RFC 2822 datetime format, don't honor the
208                  * locale.
209                  */
210                 setlocale(LC_TIME, "C");
211
212         (void)strftime(buf, sizeof(buf), format, lt);
213         printdate(buf);
214 }
215
216 static void
217 printdate(const char *buf)
218 {
219         (void)printf("%s\n", buf);
220         if (fflush(stdout))
221                 err(1, "stdout");
222         exit(EXIT_SUCCESS);
223 }
224
225 static void
226 printisodate(struct tm *lt)
227 {
228         const struct iso8601_fmt *it;
229         char fmtbuf[32], buf[32], tzbuf[8];
230
231         fmtbuf[0] = 0;
232         for (it = iso8601_fmts; it <= iso8601_selected; it++)
233                 strlcat(fmtbuf, it->format_string, sizeof(fmtbuf));
234
235         (void)strftime(buf, sizeof(buf), fmtbuf, lt);
236
237         if (iso8601_selected > iso8601_fmts) {
238                 (void)strftime(tzbuf, sizeof(tzbuf), "%z", lt);
239                 memmove(&tzbuf[4], &tzbuf[3], 3);
240                 tzbuf[3] = ':';
241                 strlcat(buf, tzbuf, sizeof(buf));
242         }
243
244         printdate(buf);
245 }
246
247 #define ATOI2(s)        ((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
248
249 static void
250 setthetime(const char *fmt, const char *p, int jflag)
251 {
252         struct utmpx utx;
253         struct tm *lt;
254         struct timeval tv;
255         const char *dot, *t;
256         int century;
257
258         lt = localtime(&tval);
259         if (lt == NULL)
260                 errx(1, "invalid time");
261         lt->tm_isdst = -1;              /* divine correct DST */
262
263         if (fmt != NULL) {
264                 t = strptime(p, fmt, lt);
265                 if (t == NULL) {
266                         fprintf(stderr, "Failed conversion of ``%s''"
267                                 " using format ``%s''\n", p, fmt);
268                         badformat();
269                 } else if (*t != '\0')
270                         fprintf(stderr, "Warning: Ignoring %ld extraneous"
271                                 " characters in date string (%s)\n",
272                                 (long) strlen(t), t);
273         } else {
274                 for (t = p, dot = NULL; *t; ++t) {
275                         if (isdigit(*t))
276                                 continue;
277                         if (*t == '.' && dot == NULL) {
278                                 dot = t;
279                                 continue;
280                         }
281                         badformat();
282                 }
283
284                 if (dot != NULL) {                      /* .ss */
285                         dot++; /* *dot++ = '\0'; */
286                         if (strlen(dot) != 2)
287                                 badformat();
288                         lt->tm_sec = ATOI2(dot);
289                         if (lt->tm_sec > 61)
290                                 badformat();
291                 } else
292                         lt->tm_sec = 0;
293
294                 century = 0;
295                 /* if p has a ".ss" field then let's pretend it's not there */
296                 switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
297                 case 12:                                /* cc */
298                         lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
299                         century = 1;
300                         /* FALLTHROUGH */
301                 case 10:                                /* yy */
302                         if (century)
303                                 lt->tm_year += ATOI2(p);
304                         else {
305                                 lt->tm_year = ATOI2(p);
306                                 if (lt->tm_year < 69)   /* hack for 2000 ;-} */
307                                         lt->tm_year += 2000 - TM_YEAR_BASE;
308                                 else
309                                         lt->tm_year += 1900 - TM_YEAR_BASE;
310                         }
311                         /* FALLTHROUGH */
312                 case 8:                                 /* mm */
313                         lt->tm_mon = ATOI2(p);
314                         if (lt->tm_mon > 12)
315                                 badformat();
316                         --lt->tm_mon;           /* time struct is 0 - 11 */
317                         /* FALLTHROUGH */
318                 case 6:                                 /* dd */
319                         lt->tm_mday = ATOI2(p);
320                         if (lt->tm_mday > 31)
321                                 badformat();
322                         /* FALLTHROUGH */
323                 case 4:                                 /* HH */
324                         lt->tm_hour = ATOI2(p);
325                         if (lt->tm_hour > 23)
326                                 badformat();
327                         /* FALLTHROUGH */
328                 case 2:                                 /* MM */
329                         lt->tm_min = ATOI2(p);
330                         if (lt->tm_min > 59)
331                                 badformat();
332                         break;
333                 default:
334                         badformat();
335                 }
336         }
337
338         /* convert broken-down time to GMT clock time */
339         if ((tval = mktime(lt)) == -1)
340                 errx(1, "nonexistent time");
341
342         if (!jflag) {
343                 utx.ut_type = OLD_TIME;
344                 memset(utx.ut_id, 0, sizeof(utx.ut_id));
345                 (void)gettimeofday(&utx.ut_tv, NULL);
346                 pututxline(&utx);
347                 tv.tv_sec = tval;
348                 tv.tv_usec = 0;
349                 if (settimeofday(&tv, NULL) != 0)
350                         err(1, "settimeofday (timeval)");
351                 utx.ut_type = NEW_TIME;
352                 (void)gettimeofday(&utx.ut_tv, NULL);
353                 pututxline(&utx);
354
355                 if ((p = getlogin()) == NULL)
356                         p = "???";
357                 syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
358         }
359 }
360
361 static void
362 badformat(void)
363 {
364         warnx("illegal time format");
365         usage();
366 }
367
368 static void
369 iso8601_usage(const char *badarg)
370 {
371         errx(1, "invalid argument '%s' for -I", badarg);
372 }
373
374 static void
375 multipleformats(void)
376 {
377         errx(1, "multiple output formats specified");
378 }
379
380 static void
381 usage(void)
382 {
383         (void)fprintf(stderr, "%s\n%s\n%s\n",
384             "usage: date [-jnRu] [-r seconds|file] [-v[+|-]val[ymwdHMS]]",
385             "            "
386             "[-I[date | hours | minutes | seconds]]",
387             "            "
388             "[-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]"
389             );
390         exit(1);
391 }