xref: /netbsd-src/lib/libc/time/strptime.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /*	$NetBSD: strptime.c,v 1.63 2020/09/21 15:31:54 ginsbach Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code was contributed to The NetBSD Foundation by Klaus Klein.
8  * Heavily optimised by David Laight
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 __RCSID("$NetBSD: strptime.c,v 1.63 2020/09/21 15:31:54 ginsbach Exp $");
35 #endif
36 
37 #include "namespace.h"
38 #include <sys/localedef.h>
39 #include <sys/types.h>
40 #include <ctype.h>
41 #include <locale.h>
42 #include <string.h>
43 #include <time.h>
44 #include <tzfile.h>
45 #include "private.h"
46 #include "setlocale_local.h"
47 
48 #ifdef __weak_alias
49 __weak_alias(strptime,_strptime)
50 __weak_alias(strptime_l, _strptime_l)
51 #endif
52 
53 static const u_char *conv_num(const unsigned char *, int *, uint, uint);
54 static const u_char *find_string(const u_char *, int *, const char * const *,
55 	const char * const *, int);
56 
57 #define _TIME_LOCALE(loc) \
58     ((_TimeLocale *)((loc)->part_impl[(size_t)LC_TIME]))
59 
60 /*
61  * We do not implement alternate representations. However, we always
62  * check whether a given modifier is allowed for a certain conversion.
63  */
64 #define ALT_E			0x01
65 #define ALT_O			0x02
66 #define LEGAL_ALT(x)		{ if (alt_format & ~(x)) return NULL; }
67 
68 #define S_YEAR			(1 << 0)
69 #define S_MON			(1 << 1)
70 #define S_YDAY			(1 << 2)
71 #define S_MDAY			(1 << 3)
72 #define S_WDAY			(1 << 4)
73 #define S_HOUR			(1 << 5)
74 
75 #define HAVE_MDAY(s)		(s & S_MDAY)
76 #define HAVE_MON(s)		(s & S_MON)
77 #define HAVE_WDAY(s)		(s & S_WDAY)
78 #define HAVE_YDAY(s)		(s & S_YDAY)
79 #define HAVE_YEAR(s)		(s & S_YEAR)
80 #define HAVE_HOUR(s)		(s & S_HOUR)
81 
82 static char utc[] = { "UTC" };
83 /* RFC-822/RFC-2822 */
84 static const char * const nast[5] = {
85        "EST",    "CST",    "MST",    "PST",    "\0\0\0"
86 };
87 static const char * const nadt[5] = {
88        "EDT",    "CDT",    "MDT",    "PDT",    "\0\0\0"
89 };
90 
91 /*
92  * Table to determine the ordinal date for the start of a month.
93  * Ref: http://en.wikipedia.org/wiki/ISO_week_date
94  */
95 static const int start_of_month[2][13] = {
96 	/* non-leap year */
97 	{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
98 	/* leap year */
99 	{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
100 };
101 
102 /*
103  * Calculate the week day of the first day of a year. Valid for
104  * the Gregorian calendar, which began Sept 14, 1752 in the UK
105  * and its colonies. Ref:
106  * http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
107  */
108 
109 static int
110 first_wday_of(int yr)
111 {
112 	return ((2 * (3 - (yr / 100) % 4)) + (yr % 100) + ((yr % 100) /  4) +
113 	    (isleap(yr) ? 6 : 0) + 1) % 7;
114 }
115 
116 #define delim(p)	((p) == '\0' || isspace((unsigned char)(p)))
117 
118 static int
119 fromzone(const unsigned char **bp, struct tm *tm, int mandatory)
120 {
121 	timezone_t tz;
122 	char buf[512], *p;
123 	const unsigned char *rp;
124 
125 	for (p = buf, rp = *bp; !delim(*rp) && p < &buf[sizeof(buf) - 1]; rp++)
126 		*p++ = *rp;
127 	*p = '\0';
128 
129 	if (mandatory)
130 		*bp = rp;
131 	if (!isalnum((unsigned char)*buf))
132 		return 0;
133 	tz = tzalloc(buf);
134 	if (tz == NULL)
135 		return 0;
136 
137 	*bp = rp;
138 	tm->tm_isdst = 0;	/* XXX */
139 #ifdef TM_GMTOFF
140 	tm->TM_GMTOFF = tzgetgmtoff(tz, tm->tm_isdst);
141 #endif
142 #ifdef TM_ZONE
143 	// Can't use tzgetname() here because we are going to free()
144 	tm->TM_ZONE = NULL; /* XXX */
145 #endif
146 	tzfree(tz);
147 	return 1;
148 }
149 
150 char *
151 strptime(const char *buf, const char *fmt, struct tm *tm)
152 {
153 	return strptime_l(buf, fmt, tm, _current_locale());
154 }
155 
156 char *
157 strptime_l(const char *buf, const char *fmt, struct tm *tm, locale_t loc)
158 {
159 	unsigned char c;
160 	const unsigned char *bp, *ep, *zname;
161 	int alt_format, i, split_year = 0, neg = 0, state = 0,
162 	    day_offset = -1, week_offset = 0, offs, mandatory;
163 	const char *new_fmt;
164 
165 	bp = (const u_char *)buf;
166 
167 	while (bp != NULL && (c = *fmt++) != '\0') {
168 		/* Clear `alternate' modifier prior to new conversion. */
169 		alt_format = 0;
170 		i = 0;
171 
172 		/* Eat up white-space. */
173 		if (isspace(c)) {
174 			while (isspace(*bp))
175 				bp++;
176 			continue;
177 		}
178 
179 		if (c != '%')
180 			goto literal;
181 
182 
183 again:		switch (c = *fmt++) {
184 		case '%':	/* "%%" is converted to "%". */
185 literal:
186 			if (c != *bp++)
187 				return NULL;
188 			LEGAL_ALT(0);
189 			continue;
190 
191 		/*
192 		 * "Alternative" modifiers. Just set the appropriate flag
193 		 * and start over again.
194 		 */
195 		case 'E':	/* "%E?" alternative conversion modifier. */
196 			LEGAL_ALT(0);
197 			alt_format |= ALT_E;
198 			goto again;
199 
200 		case 'O':	/* "%O?" alternative conversion modifier. */
201 			LEGAL_ALT(0);
202 			alt_format |= ALT_O;
203 			goto again;
204 
205 		/*
206 		 * "Complex" conversion rules, implemented through recursion.
207 		 */
208 		case 'c':	/* Date and time, using the locale's format. */
209 			new_fmt = _TIME_LOCALE(loc)->d_t_fmt;
210 			state |= S_WDAY | S_MON | S_MDAY | S_YEAR;
211 			goto recurse;
212 
213 		case 'D':	/* The date as "%m/%d/%y". */
214 			new_fmt = "%m/%d/%y";
215 			LEGAL_ALT(0);
216 			state |= S_MON | S_MDAY | S_YEAR;
217 			goto recurse;
218 
219 		case 'F':	/* The date as "%Y-%m-%d". */
220 			new_fmt = "%Y-%m-%d";
221 			LEGAL_ALT(0);
222 			state |= S_MON | S_MDAY | S_YEAR;
223 			goto recurse;
224 
225 		case 'R':	/* The time as "%H:%M". */
226 			new_fmt = "%H:%M";
227 			LEGAL_ALT(0);
228 			goto recurse;
229 
230 		case 'r':	/* The time in 12-hour clock representation. */
231 			new_fmt = _TIME_LOCALE(loc)->t_fmt_ampm;
232 			LEGAL_ALT(0);
233 			goto recurse;
234 
235 		case 'T':	/* The time as "%H:%M:%S". */
236 			new_fmt = "%H:%M:%S";
237 			LEGAL_ALT(0);
238 			goto recurse;
239 
240 		case 'X':	/* The time, using the locale's format. */
241 			new_fmt = _TIME_LOCALE(loc)->t_fmt;
242 			goto recurse;
243 
244 		case 'x':	/* The date, using the locale's format. */
245 			new_fmt = _TIME_LOCALE(loc)->d_fmt;
246 			state |= S_MON | S_MDAY | S_YEAR;
247 		    recurse:
248 			bp = (const u_char *)strptime((const char *)bp,
249 							    new_fmt, tm);
250 			LEGAL_ALT(ALT_E);
251 			continue;
252 
253 		/*
254 		 * "Elementary" conversion rules.
255 		 */
256 		case 'A':	/* The day of week, using the locale's form. */
257 		case 'a':
258 			bp = find_string(bp, &tm->tm_wday,
259 			    _TIME_LOCALE(loc)->day, _TIME_LOCALE(loc)->abday, 7);
260 			LEGAL_ALT(0);
261 			state |= S_WDAY;
262 			continue;
263 
264 		case 'B':	/* The month, using the locale's form. */
265 		case 'b':
266 		case 'h':
267 			bp = find_string(bp, &tm->tm_mon,
268 			    _TIME_LOCALE(loc)->mon, _TIME_LOCALE(loc)->abmon,
269 			    12);
270 			LEGAL_ALT(0);
271 			state |= S_MON;
272 			continue;
273 
274 		case 'C':	/* The century number. */
275 			i = 20;
276 			bp = conv_num(bp, &i, 0, 99);
277 
278 			i = i * 100 - TM_YEAR_BASE;
279 			if (split_year)
280 				i += tm->tm_year % 100;
281 			split_year = 1;
282 			tm->tm_year = i;
283 			LEGAL_ALT(ALT_E);
284 			state |= S_YEAR;
285 			continue;
286 
287 		case 'd':	/* The day of month. */
288 		case 'e':
289 			bp = conv_num(bp, &tm->tm_mday, 1, 31);
290 			LEGAL_ALT(ALT_O);
291 			state |= S_MDAY;
292 			continue;
293 
294 		case 'k':	/* The hour (24-hour clock representation). */
295 			LEGAL_ALT(0);
296 			/* FALLTHROUGH */
297 		case 'H':
298 			bp = conv_num(bp, &tm->tm_hour, 0, 23);
299 			LEGAL_ALT(ALT_O);
300 			state |= S_HOUR;
301 			continue;
302 
303 		case 'l':	/* The hour (12-hour clock representation). */
304 			LEGAL_ALT(0);
305 			/* FALLTHROUGH */
306 		case 'I':
307 			bp = conv_num(bp, &tm->tm_hour, 1, 12);
308 			if (tm->tm_hour == 12)
309 				tm->tm_hour = 0;
310 			LEGAL_ALT(ALT_O);
311 			state |= S_HOUR;
312 			continue;
313 
314 		case 'j':	/* The day of year. */
315 			i = 1;
316 			bp = conv_num(bp, &i, 1, 366);
317 			tm->tm_yday = i - 1;
318 			LEGAL_ALT(0);
319 			state |= S_YDAY;
320 			continue;
321 
322 		case 'M':	/* The minute. */
323 			bp = conv_num(bp, &tm->tm_min, 0, 59);
324 			LEGAL_ALT(ALT_O);
325 			continue;
326 
327 		case 'm':	/* The month. */
328 			i = 1;
329 			bp = conv_num(bp, &i, 1, 12);
330 			tm->tm_mon = i - 1;
331 			LEGAL_ALT(ALT_O);
332 			state |= S_MON;
333 			continue;
334 
335 		case 'p':	/* The locale's equivalent of AM/PM. */
336 			bp = find_string(bp, &i, _TIME_LOCALE(loc)->am_pm,
337 			    NULL, 2);
338 			if (HAVE_HOUR(state) && tm->tm_hour > 11)
339 				return NULL;
340 			tm->tm_hour += i * 12;
341 			LEGAL_ALT(0);
342 			continue;
343 
344 		case 'S':	/* The seconds. */
345 			bp = conv_num(bp, &tm->tm_sec, 0, 61);
346 			LEGAL_ALT(ALT_O);
347 			continue;
348 
349 #ifndef TIME_MAX
350 #define TIME_MAX	INT64_MAX
351 #endif
352 		case 's':	/* seconds since the epoch */
353 			{
354 				time_t sse = 0;
355 				uint64_t rulim = TIME_MAX;
356 
357 				if (*bp < '0' || *bp > '9') {
358 					bp = NULL;
359 					continue;
360 				}
361 
362 				do {
363 					sse *= 10;
364 					sse += *bp++ - '0';
365 					rulim /= 10;
366 				} while ((sse * 10 <= TIME_MAX) &&
367 					 rulim && *bp >= '0' && *bp <= '9');
368 
369 				if (sse < 0 || (uint64_t)sse > TIME_MAX) {
370 					bp = NULL;
371 					continue;
372 				}
373 
374 				if (localtime_r(&sse, tm) == NULL)
375 					bp = NULL;
376 				else
377 					state |= S_YDAY | S_WDAY |
378 					    S_MON | S_MDAY | S_YEAR;
379 			}
380 			continue;
381 
382 		case 'U':	/* The week of year, beginning on sunday. */
383 		case 'W':	/* The week of year, beginning on monday. */
384 			/*
385 			 * This is bogus, as we can not assume any valid
386 			 * information present in the tm structure at this
387 			 * point to calculate a real value, so save the
388 			 * week for now in case it can be used later.
389 			 */
390 			bp = conv_num(bp, &i, 0, 53);
391 			LEGAL_ALT(ALT_O);
392 			if (c == 'U')
393 				day_offset = TM_SUNDAY;
394 			else
395 				day_offset = TM_MONDAY;
396 			week_offset = i;
397 			continue;
398 
399 		case 'w':	/* The day of week, beginning on sunday. */
400 			bp = conv_num(bp, &tm->tm_wday, 0, 6);
401 			LEGAL_ALT(ALT_O);
402 			state |= S_WDAY;
403 			continue;
404 
405 		case 'u':	/* The day of week, monday = 1. */
406 			bp = conv_num(bp, &i, 1, 7);
407 			tm->tm_wday = i % 7;
408 			LEGAL_ALT(ALT_O);
409 			state |= S_WDAY;
410 			continue;
411 
412 		case 'g':	/* The year corresponding to the ISO week
413 				 * number but without the century.
414 				 */
415 			bp = conv_num(bp, &i, 0, 99);
416 			continue;
417 
418 		case 'G':	/* The year corresponding to the ISO week
419 				 * number with century.
420 				 */
421 			do
422 				bp++;
423 			while (isdigit(*bp));
424 			continue;
425 
426 		case 'V':	/* The ISO 8601:1988 week number as decimal */
427 			bp = conv_num(bp, &i, 1, 53);
428 			continue;
429 
430 		case 'Y':	/* The year. */
431 			i = TM_YEAR_BASE;	/* just for data sanity... */
432 			bp = conv_num(bp, &i, 0, 9999);
433 			tm->tm_year = i - TM_YEAR_BASE;
434 			LEGAL_ALT(ALT_E);
435 			state |= S_YEAR;
436 			continue;
437 
438 		case 'y':	/* The year within 100 years of the epoch. */
439 			/* LEGAL_ALT(ALT_E | ALT_O); */
440 			bp = conv_num(bp, &i, 0, 99);
441 
442 			if (split_year)
443 				/* preserve century */
444 				i += (tm->tm_year / 100) * 100;
445 			else {
446 				split_year = 1;
447 				if (i <= 68)
448 					i = i + 2000 - TM_YEAR_BASE;
449 				else
450 					i = i + 1900 - TM_YEAR_BASE;
451 			}
452 			tm->tm_year = i;
453 			state |= S_YEAR;
454 			continue;
455 
456 		case 'Z':
457 		case 'z':
458 			tzset();
459 			mandatory = c == 'z';
460 			/*
461 			 * We recognize all ISO 8601 formats:
462 			 * Z	= Zulu time/UTC
463 			 * [+-]hhmm
464 			 * [+-]hh:mm
465 			 * [+-]hh
466 			 * We recognize all RFC-822/RFC-2822 formats:
467 			 * UT|GMT
468 			 *          North American : UTC offsets
469 			 * E[DS]T = Eastern : -4 | -5
470 			 * C[DS]T = Central : -5 | -6
471 			 * M[DS]T = Mountain: -6 | -7
472 			 * P[DS]T = Pacific : -7 | -8
473 			 *          Nautical/Military
474 			 * [A-IL-M] = -1 ... -9 (J not used)
475 			 * [N-Y]  = +1 ... +12
476 			 * Note: J maybe used to denote non-nautical
477 			 *       local time
478 			 */
479 			if (mandatory)
480 				while (isspace(*bp))
481 					bp++;
482 
483 			zname = bp;
484 			switch (*bp++) {
485 			case 'G':
486 				if (*bp++ != 'M')
487 					goto namedzone;
488 				/*FALLTHROUGH*/
489 			case 'U':
490 				if (*bp++ != 'T')
491 					goto namedzone;
492 				else if (!delim(*bp) && *bp++ != 'C')
493 					goto namedzone;
494 				/*FALLTHROUGH*/
495 			case 'Z':
496 				if (!delim(*bp))
497 					goto namedzone;
498 				tm->tm_isdst = 0;
499 #ifdef TM_GMTOFF
500 				tm->TM_GMTOFF = 0;
501 #endif
502 #ifdef TM_ZONE
503 				tm->TM_ZONE = utc;
504 #endif
505 				continue;
506 			case '+':
507 				neg = 0;
508 				break;
509 			case '-':
510 				neg = 1;
511 				break;
512 			default:
513 namedzone:
514 				bp = zname;
515 
516 				/* Nautical / Military style */
517 				if (delim(bp[1]) &&
518 				    ((*bp >= 'A' && *bp <= 'I') ||
519 				     (*bp >= 'L' && *bp <= 'Y'))) {
520 #ifdef TM_GMTOFF
521 					/* Argh! No 'J'! */
522 					if (*bp >= 'A' && *bp <= 'I')
523 						tm->TM_GMTOFF =
524 						    (int)*bp - ('A' - 1);
525 					else if (*bp >= 'L' && *bp <= 'M')
526 						tm->TM_GMTOFF = (int)*bp - 'A';
527 					else if (*bp >= 'N' && *bp <= 'Y')
528 						tm->TM_GMTOFF = 'M' - (int)*bp;
529 					tm->TM_GMTOFF *= SECSPERHOUR;
530 #endif
531 #ifdef TM_ZONE
532 					tm->TM_ZONE = NULL; /* XXX */
533 #endif
534 					bp++;
535 					continue;
536 				}
537 				/* 'J' is local time */
538 				if (delim(bp[1]) && *bp == 'J') {
539 #ifdef TM_GMTOFF
540 					tm->TM_GMTOFF = -timezone;
541 #endif
542 #ifdef TM_ZONE
543 					tm->TM_ZONE = NULL; /* XXX */
544 #endif
545 					bp++;
546 					continue;
547 				}
548 
549 				/*
550 				 * From our 3 letter hard-coded table
551 				 * XXX: Can be removed, handled by tzload()
552 				 */
553 				if (delim(bp[0]) || delim(bp[1]) ||
554 				    delim(bp[2]) || !delim(bp[3]))
555 					goto loadzone;
556 				ep = find_string(bp, &i, nast, NULL, 4);
557 				if (ep != NULL) {
558 #ifdef TM_GMTOFF
559 					tm->TM_GMTOFF = (-5 - i) * SECSPERHOUR;
560 #endif
561 #ifdef TM_ZONE
562 					tm->TM_ZONE = __UNCONST(nast[i]);
563 #endif
564 					bp = ep;
565 					continue;
566 				}
567 				ep = find_string(bp, &i, nadt, NULL, 4);
568 				if (ep != NULL) {
569 					tm->tm_isdst = 1;
570 #ifdef TM_GMTOFF
571 					tm->TM_GMTOFF = (-4 - i) * SECSPERHOUR;
572 #endif
573 #ifdef TM_ZONE
574 					tm->TM_ZONE = __UNCONST(nadt[i]);
575 #endif
576 					bp = ep;
577 					continue;
578 				}
579 				/*
580 				 * Our current timezone
581 				 */
582 				ep = find_string(bp, &i,
583 					       	 (const char * const *)tzname,
584 					       	  NULL, 2);
585 				if (ep != NULL) {
586 					tm->tm_isdst = i;
587 #ifdef TM_GMTOFF
588 					tm->TM_GMTOFF = -timezone;
589 #endif
590 #ifdef TM_ZONE
591 					tm->TM_ZONE = tzname[i];
592 #endif
593 					bp = ep;
594 					continue;
595 				}
596 loadzone:
597 				/*
598 				 * The hard way, load the zone!
599 				 */
600 				if (fromzone(&bp, tm, mandatory))
601 					continue;
602 				goto out;
603 			}
604 			offs = 0;
605 			for (i = 0; i < 4; ) {
606 				if (isdigit(*bp)) {
607 					offs = offs * 10 + (*bp++ - '0');
608 					i++;
609 					continue;
610 				}
611 				if (i == 2 && *bp == ':') {
612 					bp++;
613 					continue;
614 				}
615 				break;
616 			}
617 			if (isdigit(*bp))
618 				goto out;
619 			switch (i) {
620 			case 2:
621 				offs *= SECSPERHOUR;
622 				break;
623 			case 4:
624 				i = offs % 100;
625 				offs /= 100;
626 				if (i >= SECSPERMIN)
627 					goto out;
628 				/* Convert minutes into decimal */
629 				offs = offs * SECSPERHOUR + i * SECSPERMIN;
630 				break;
631 			default:
632 			out:
633 				if (mandatory)
634 					return NULL;
635 				bp = zname;
636 				continue;
637 			}
638 			/* ISO 8601 & RFC 3339 limit to 23:59 max */
639 			if (offs >= (HOURSPERDAY * SECSPERHOUR))
640 				goto out;
641 			if (neg)
642 				offs = -offs;
643 			tm->tm_isdst = 0;	/* XXX */
644 #ifdef TM_GMTOFF
645 			tm->TM_GMTOFF = offs;
646 #endif
647 #ifdef TM_ZONE
648 			tm->TM_ZONE = NULL;	/* XXX */
649 #endif
650 			continue;
651 
652 		/*
653 		 * Miscellaneous conversions.
654 		 */
655 		case 'n':	/* Any kind of white-space. */
656 		case 't':
657 			while (isspace(*bp))
658 				bp++;
659 			LEGAL_ALT(0);
660 			continue;
661 
662 
663 		default:	/* Unknown/unsupported conversion. */
664 			return NULL;
665 		}
666 	}
667 
668 	if (!HAVE_YDAY(state) && HAVE_YEAR(state)) {
669 		if (HAVE_MON(state) && HAVE_MDAY(state)) {
670 			/* calculate day of year (ordinal date) */
671 			tm->tm_yday =  start_of_month[isleap_sum(tm->tm_year,
672 			    TM_YEAR_BASE)][tm->tm_mon] + (tm->tm_mday - 1);
673 			state |= S_YDAY;
674 		} else if (day_offset != -1) {
675 			/*
676 			 * Set the date to the first Sunday (or Monday)
677 			 * of the specified week of the year.
678 			 */
679 			if (!HAVE_WDAY(state)) {
680 				tm->tm_wday = day_offset;
681 				state |= S_WDAY;
682 			}
683 			tm->tm_yday = (7 -
684 			    first_wday_of(tm->tm_year + TM_YEAR_BASE) +
685 			    day_offset) % 7 + (week_offset - 1) * 7 +
686 			    tm->tm_wday  - day_offset;
687 			state |= S_YDAY;
688 		}
689 	}
690 
691 	if (HAVE_YDAY(state) && HAVE_YEAR(state)) {
692 		int isleap;
693 
694 		if (!HAVE_MON(state)) {
695 			/* calculate month of day of year */
696 			i = 0;
697 			isleap = isleap_sum(tm->tm_year, TM_YEAR_BASE);
698 			while (tm->tm_yday >= start_of_month[isleap][i])
699 				i++;
700 			if (i > 12) {
701 				i = 1;
702 				tm->tm_yday -= start_of_month[isleap][12];
703 				tm->tm_year++;
704 			}
705 			tm->tm_mon = i - 1;
706 			state |= S_MON;
707 		}
708 
709 		if (!HAVE_MDAY(state)) {
710 			/* calculate day of month */
711 			isleap = isleap_sum(tm->tm_year, TM_YEAR_BASE);
712 			tm->tm_mday = tm->tm_yday -
713 			    start_of_month[isleap][tm->tm_mon] + 1;
714 			state |= S_MDAY;
715 		}
716 
717 		if (!HAVE_WDAY(state)) {
718 			/* calculate day of week */
719 			i = 0;
720 			week_offset = first_wday_of(tm->tm_year);
721 			while (i++ <= tm->tm_yday) {
722 				if (week_offset++ >= 6)
723 					week_offset = 0;
724 			}
725 			tm->tm_wday = week_offset;
726 			state |= S_WDAY;
727 		}
728 	}
729 
730 	return __UNCONST(bp);
731 }
732 
733 
734 static const u_char *
735 conv_num(const unsigned char *buf, int *dest, uint llim, uint ulim)
736 {
737 	uint result = 0;
738 	unsigned char ch;
739 
740 	/* The limit also determines the number of valid digits. */
741 	uint rulim = ulim;
742 
743 	ch = *buf;
744 	if (ch < '0' || ch > '9')
745 		return NULL;
746 
747 	do {
748 		result *= 10;
749 		result += ch - '0';
750 		rulim /= 10;
751 		ch = *++buf;
752 	} while ((result * 10 <= ulim) && rulim && ch >= '0' && ch <= '9');
753 
754 	if (result < llim || result > ulim)
755 		return NULL;
756 
757 	*dest = result;
758 	return buf;
759 }
760 
761 static const u_char *
762 find_string(const u_char *bp, int *tgt, const char * const *n1,
763 		const char * const *n2, int c)
764 {
765 	int i;
766 	size_t len;
767 
768 	/* check full name - then abbreviated ones */
769 	for (; n1 != NULL; n1 = n2, n2 = NULL) {
770 		for (i = 0; i < c; i++, n1++) {
771 			len = strlen(*n1);
772 			if (strncasecmp(*n1, (const char *)bp, len) == 0) {
773 				*tgt = i;
774 				return bp + len;
775 			}
776 		}
777 	}
778 
779 	/* Nothing matched */
780 	return NULL;
781 }
782