Home | History | Annotate | Line # | Download | only in date
date.c revision 1.66
      1 /* $NetBSD: date.c,v 1.66 2024/01/21 16:55:56 christos Exp $ */
      2 
      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 #if HAVE_NBTOOL_CONFIG_H
     33 #include "nbtool_config.h"
     34 #endif
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT(
     39 "@(#) Copyright (c) 1985, 1987, 1988, 1993\
     40  The Regents of the University of California.  All rights reserved.");
     41 #endif /* not lint */
     42 
     43 #ifndef lint
     44 #if 0
     45 static char sccsid[] = "@(#)date.c	8.2 (Berkeley) 4/28/95";
     46 #else
     47 __RCSID("$NetBSD: date.c,v 1.66 2024/01/21 16:55:56 christos Exp $");
     48 #endif
     49 #endif /* not lint */
     50 
     51 #include <sys/param.h>
     52 #include <sys/time.h>
     53 
     54 #include <ctype.h>
     55 #include <err.h>
     56 #include <fcntl.h>
     57 #include <errno.h>
     58 #include <locale.h>
     59 #include <stdio.h>
     60 #include <stdlib.h>
     61 #include <string.h>
     62 #include <syslog.h>
     63 #include <time.h>
     64 #include <tzfile.h>
     65 #include <unistd.h>
     66 #include <util.h>
     67 #if !HAVE_NBTOOL_CONFIG_H
     68 #include <utmpx.h>
     69 #endif
     70 
     71 #include "extern.h"
     72 
     73 static time_t tval;
     74 static int Rflag, aflag, jflag, rflag, nflag;
     75 static char *fmt;
     76 
     77 __dead static void badcanotime(const char *, const char *, size_t);
     78 static void setthetime(const char *);
     79 __dead static void usage(void);
     80 
     81 int
     82 main(int argc, char *argv[])
     83 {
     84 	char *buf;
     85 	size_t bufsiz;
     86 	const char *format;
     87 	int ch;
     88 	long long val;
     89 	struct tm *tm;
     90 
     91 	setprogname(argv[0]);
     92 	(void)setlocale(LC_ALL, "");
     93 
     94 	while ((ch = getopt(argc, argv, "ad:f:jnRr:u")) != -1) {
     95 		switch (ch) {
     96 		case 'a':		/* adjust time slowly */
     97 			aflag = 1;
     98 			nflag = 1;
     99 			break;
    100 		case 'd':
    101 			rflag = 1;
    102 #ifndef HAVE_NBTOOL_CONFIG_H
    103 			tval = parsedate(optarg, NULL, NULL);
    104 			if (tval == -1) {
    105 				errx(EXIT_FAILURE,
    106 				    "%s: Unrecognized date format", optarg);
    107 			}
    108 			break;
    109 #else
    110 			/* handle YYYYMMDD, or fail */
    111 			{
    112 				struct tm tm;
    113 				char *p;
    114 				memset(&tm, 0, sizeof(tm));
    115 				p = strptime(optarg, "%Y%m%d", &tm);
    116 				if (*p == '\0'
    117 				    && tm.tm_year >= 0 && tm.tm_year < 1000
    118 				    && tm.tm_mon >= 0 && tm.tm_mon <= 11
    119 				    && tm.tm_mday >= 1 && tm.tm_mday <= 31
    120 				    && (tval = mktime(&tm)) != -1)
    121 					break;
    122 			}
    123 			errx(EXIT_FAILURE,
    124 			    "-d not supported in the tool version");
    125 #endif
    126 		case 'f':
    127 			fmt = optarg;
    128 			break;
    129 		case 'j':		/* don't set time */
    130 			jflag = 1;
    131 			break;
    132 		case 'n':		/* don't set network */
    133 			nflag = 1;
    134 			break;
    135 		case 'R':		/* RFC-5322 email format */
    136 			Rflag = 1;
    137 			break;
    138 		case 'r':		/* user specified seconds */
    139 			if (optarg[0] == '\0') {
    140 				errx(EXIT_FAILURE, "<empty>: Invalid number");
    141 			}
    142 			errno = 0;
    143 			val = strtoll(optarg, &buf, 0);
    144 			if (errno) {
    145 				err(EXIT_FAILURE, "%s", optarg);
    146 			}
    147 			if (optarg[0] == '\0' || *buf != '\0') {
    148 				errx(EXIT_FAILURE,
    149 				    "%s: Invalid number", optarg);
    150 			}
    151 			rflag = 1;
    152 			tval = (time_t)val;
    153 			break;
    154 		case 'u':		/* do everything in UTC */
    155 			(void)setenv("TZ", "UTC0", 1);
    156 			break;
    157 		default:
    158 			usage();
    159 		}
    160 	}
    161 	argc -= optind;
    162 	argv += optind;
    163 
    164 	if (!rflag && time(&tval) == -1)
    165 		err(EXIT_FAILURE, "time");
    166 
    167 
    168 	/* allow the operands in any order */
    169 	if (*argv && **argv == '+') {
    170 		format = *argv;
    171 		++argv;
    172 	} else if (Rflag) {
    173 		(void)setlocale(LC_TIME, "C");
    174 		format = "+%a, %-e %b %Y %H:%M:%S %z";
    175 	} else
    176 		format = "+%a %b %e %H:%M:%S %Z %Y";
    177 
    178 	if (*argv) {
    179 		setthetime(*argv);
    180 		++argv;
    181 	} else if (fmt)
    182 		usage();
    183 
    184 	if (*argv && **argv == '+')
    185 		format = *argv;
    186 
    187 	if ((buf = malloc(bufsiz = 1024)) == NULL)
    188 		goto bad;
    189 
    190 	if ((tm = localtime(&tval)) == NULL)
    191 		err(EXIT_FAILURE, "%lld: localtime", (long long)tval);
    192 
    193 	while (strftime(buf, bufsiz, format, tm) == 0)
    194 		if ((buf = realloc(buf, bufsiz <<= 1)) == NULL)
    195 			goto bad;
    196 
    197 	(void)printf("%s\n", buf + 1);
    198 	free(buf);
    199 	return 0;
    200 bad:
    201 	err(EXIT_FAILURE, "Cannot allocate format buffer");
    202 }
    203 
    204 static void
    205 badcanotime(const char *msg, const char *val, size_t where)
    206 {
    207 	warnx("%s in canonical time", msg);
    208 	warnx("%s", val);
    209 	warnx("%*s", (int)where + 1, "^");
    210 	usage();
    211 }
    212 
    213 #define ATOI2(s) ((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
    214 
    215 static void
    216 setthetime(const char *p)
    217 {
    218 	struct timeval tv;
    219 	time_t new_time;
    220 	struct tm *lt;
    221 	const char *dot, *t, *op;
    222 	size_t len;
    223 	int yearset;
    224 
    225 	if ((lt = localtime(&tval)) == NULL)
    226 		err(EXIT_FAILURE, "%lld: localtime", (long long)tval);
    227 
    228 	lt->tm_isdst = -1;			/* Divine correct DST */
    229 
    230 	if (fmt) {
    231 		t = strptime(p, fmt, lt);
    232 		if (t == NULL) {
    233 			warnx("Failed conversion of ``%s''"
    234 			    " using format ``%s''\n", p, fmt);
    235 		} else if (*t != '\0')
    236 			warnx("Ignoring %zu extraneous"
    237 				" characters in date string (%s)",
    238 				strlen(t), t);
    239 		goto setit;
    240 	}
    241 	for (t = p, dot = NULL; *t; ++t) {
    242 		if (*t == '.') {
    243 			if (dot == NULL) {
    244 				dot = t;
    245 			} else {
    246 				badcanotime("Unexpected dot", p, t - p);
    247 			}
    248 		} else if (!isdigit((unsigned char)*t)) {
    249 			badcanotime("Expected digit", p, t - p);
    250 		}
    251 	}
    252 
    253 
    254 	if (dot != NULL) {			/* .ss */
    255 		len = strlen(dot);
    256 		if (len > 3) {
    257 			badcanotime("Unexpected digit after seconds field",
    258 				    p, strlen(p) - 1);
    259 		} else if (len < 3) {
    260 			badcanotime("Expected digit in seconds field",
    261 				    p, strlen(p));
    262 		}
    263 		++dot;
    264 		lt->tm_sec = ATOI2(dot);
    265 		if (lt->tm_sec > 61)
    266 			badcanotime("Seconds out of range", p, strlen(p) - 1);
    267 	} else {
    268 		len = 0;
    269 		lt->tm_sec = 0;
    270 	}
    271 
    272 	op = p;
    273 	yearset = 0;
    274 	switch (strlen(p) - len) {
    275 	case 12:				/* cc */
    276 		lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
    277 		if (lt->tm_year < 0)
    278 			badcanotime("Year before 1900", op, p - op + 1);
    279 		yearset = 1;
    280 		/* FALLTHROUGH */
    281 	case 10:				/* yy */
    282 		if (yearset) {
    283 			lt->tm_year += ATOI2(p);
    284 		} else {
    285 			yearset = ATOI2(p);
    286 			if (yearset < 69)
    287 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
    288 			else
    289 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
    290 		}
    291 		/* FALLTHROUGH */
    292 	case 8:					/* mm */
    293 		lt->tm_mon = ATOI2(p);
    294 		if (lt->tm_mon > 12 || lt->tm_mon == 0)
    295 			badcanotime("Month out of range", op, p - op - 1);
    296 		--lt->tm_mon;			/* time struct is 0 - 11 */
    297 		/* FALLTHROUGH */
    298 	case 6:					/* dd */
    299 		lt->tm_mday = ATOI2(p);
    300 		switch (lt->tm_mon) {
    301 		case 0:
    302 		case 2:
    303 		case 4:
    304 		case 6:
    305 		case 7:
    306 		case 9:
    307 		case 11:
    308 			if (lt->tm_mday > 31 || lt->tm_mday == 0)
    309 				badcanotime("Day out of range (max 31)",
    310 					    op, p - op - 1);
    311 			break;
    312 		case 3:
    313 		case 5:
    314 		case 8:
    315 		case 10:
    316 			if (lt->tm_mday > 30 || lt->tm_mday == 0)
    317 				badcanotime("Day out of range (max 30)",
    318 					    op, p - op - 1);
    319 			break;
    320 		case 1:
    321 			if (isleap(lt->tm_year + TM_YEAR_BASE)) {
    322 				if (lt->tm_mday > 29 || lt->tm_mday == 0) {
    323 					badcanotime("Day out of range "
    324 						    "(max 29)",
    325 						    op, p - op - 1);
    326 				}
    327 			} else {
    328 				if (lt->tm_mday > 28 || lt->tm_mday == 0) {
    329 					badcanotime("Day out of range "
    330 						    "(max 28)",
    331 						    op, p - op - 1);
    332 				}
    333 			}
    334 			break;
    335 		default:
    336 			/*
    337 			 * If the month was given, it's already been
    338 			 * checked.  If a bad value came back from
    339 			 * localtime, something's badly broken.
    340 			 * (make this an assertion?)
    341 			 */
    342 			errx(EXIT_FAILURE, "localtime gave invalid month %d",
    343 			    lt->tm_mon);
    344 		}
    345 		/* FALLTHROUGH */
    346 	case 4:					/* hh */
    347 		lt->tm_hour = ATOI2(p);
    348 		if (lt->tm_hour > 23)
    349 			badcanotime("Hour out of range", op, p - op - 1);
    350 		/* FALLTHROUGH */
    351 	case 2:					/* mm */
    352 		lt->tm_min = ATOI2(p);
    353 		if (lt->tm_min > 59)
    354 			badcanotime("Minute out of range", op, p - op - 1);
    355 		break;
    356 	case 0:					/* was just .sss */
    357 		if (len != 0)
    358 			break;
    359 		/* FALLTHROUGH */
    360 	default:
    361 	    if (strlen(p) - len > 12) {
    362 		    badcanotime("Too many digits", p, 12);
    363 	    } else {
    364 		    badcanotime("Not enough digits", p, strlen(p) - len);
    365 	    }
    366 	}
    367 setit:
    368 	/* convert broken-down time to UTC clock time */
    369 	if ((new_time = mktime(lt)) == -1) {
    370 		/* Can this actually happen? */
    371 		err(EXIT_FAILURE, "mktime");
    372 	}
    373 
    374 	/* if jflag is set, don't actually change the time, just return */
    375 	if (jflag) {
    376 		tval = new_time;
    377 		return;
    378 	}
    379 
    380 	/* set the time */
    381 #ifndef HAVE_NBTOOL_CONFIG_H
    382 	struct utmpx utx;
    383 	memset(&utx, 0, sizeof(utx));
    384 	utx.ut_type = OLD_TIME;
    385 	(void)gettimeofday(&utx.ut_tv, NULL);
    386 	pututxline(&utx);
    387 
    388 	if (nflag || netsettime(new_time)) {
    389 		logwtmp("|", "date", "");
    390 		if (aflag) {
    391 			tv.tv_sec = new_time - tval;
    392 			tv.tv_usec = 0;
    393 			if (adjtime(&tv, NULL))
    394 				err(EXIT_FAILURE, "adjtime");
    395 		} else {
    396 			tval = new_time;
    397 			tv.tv_sec = tval;
    398 			tv.tv_usec = 0;
    399 			if (settimeofday(&tv, NULL))
    400 				err(EXIT_FAILURE, "settimeofday");
    401 		}
    402 		logwtmp("{", "date", "");
    403 	}
    404 	utx.ut_type = NEW_TIME;
    405 	(void)gettimeofday(&utx.ut_tv, NULL);
    406 	pututxline(&utx);
    407 
    408 	if ((p = getlogin()) == NULL)
    409 		p = "???";
    410 	syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
    411 #else
    412 	errx(EXIT_FAILURE, "Can't set the time in the tools version");
    413 #endif
    414 }
    415 
    416 static void
    417 usage(void)
    418 {
    419 	(void)fprintf(stderr,
    420 	    "Usage: %s [-ajnRu] [-d date] [-r seconds] [+format]",
    421 	    getprogname());
    422 	(void)fprintf(stderr, " [[[[[[CC]yy]mm]dd]HH]MM[.SS]]\n");
    423 	(void)fprintf(stderr,
    424 	    "       %s [-ajnRu] -f input_format new_date [+format]\n",
    425 	    getprogname());
    426 	exit(EXIT_FAILURE);
    427 	/* NOTREACHED */
    428 }
    429