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