1 /*
2  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3  *
4  * SPDX-License-Identifier: MPL-2.0 AND BSD-2-Clause
5  *
6  * This Source Code Form is subject to the terms of the Mozilla Public
7  * License, v. 2.0. If a copy of the MPL was not distributed with this
8  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9  *
10  * See the COPYRIGHT file distributed with this work for additional
11  * information regarding copyright ownership.
12  */
13 
14 /*-
15  * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
16  * All rights reserved.
17  *
18  * This code was contributed to The NetBSD Foundation by Klaus Klein.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 #include <ctype.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <time.h>
47 
48 #include <isc/tm.h>
49 #include <isc/util.h>
50 
51 /*
52  * Portable conversion routines for struct tm, replacing
53  * timegm() and strptime(), which are not available on all
54  * platforms and don't always behave the same way when they
55  * are.
56  */
57 
58 /*
59  * We do not implement alternate representations. However, we always
60  * check whether a given modifier is allowed for a certain conversion.
61  */
62 #define ALT_E 0x01
63 #define ALT_O 0x02
64 #define LEGAL_ALT(x)                          \
65 	{                                     \
66 		if ((alt_format & ~(x)) != 0) \
67 			return ((0));         \
68 	}
69 
70 #ifndef TM_YEAR_BASE
71 #define TM_YEAR_BASE 1900
72 #endif /* ifndef TM_YEAR_BASE */
73 
74 static const char *day[7] = { "Sunday",	  "Monday", "Tuesday", "Wednesday",
75 			      "Thursday", "Friday", "Saturday" };
76 static const char *abday[7] = {
77 	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
78 };
79 static const char *mon[12] = {
80 	"January", "February", "March",	    "April",   "May",	   "June",
81 	"July",	   "August",   "September", "October", "November", "December"
82 };
83 static const char *abmon[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
84 				 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
85 static const char *am_pm[2] = { "AM", "PM" };
86 
87 static int
conv_num(const char ** buf,int * dest,int llim,int ulim)88 conv_num(const char **buf, int *dest, int llim, int ulim) {
89 	int result = 0;
90 
91 	/* The limit also determines the number of valid digits. */
92 	int rulim = ulim;
93 
94 	if (!isdigit((unsigned char)**buf)) {
95 		return (0);
96 	}
97 
98 	do {
99 		result *= 10;
100 		result += *(*buf)++ - '0';
101 		rulim /= 10;
102 	} while ((result * 10 <= ulim) && rulim && **buf >= '0' &&
103 		 **buf <= '9');
104 
105 	if (result < llim || result > ulim) {
106 		return (0);
107 	}
108 
109 	*dest = result;
110 	return (1);
111 }
112 
113 time_t
isc_tm_timegm(struct tm * tm)114 isc_tm_timegm(struct tm *tm) {
115 	time_t ret;
116 	int i, yday = 0, leapday;
117 	int mdays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 };
118 
119 	leapday = ((((tm->tm_year + 1900) % 4) == 0 &&
120 		    ((tm->tm_year + 1900) % 100) != 0) ||
121 		   ((tm->tm_year + 1900) % 400) == 0)
122 			  ? 1
123 			  : 0;
124 	mdays[1] += leapday;
125 
126 	yday = tm->tm_mday - 1;
127 	for (i = 1; i <= tm->tm_mon; i++) {
128 		yday += mdays[i - 1];
129 	}
130 	ret = tm->tm_sec + (60 * tm->tm_min) + (3600 * tm->tm_hour) +
131 	      (86400 *
132 	       (yday + ((tm->tm_year - 70) * 365) + ((tm->tm_year - 69) / 4) -
133 		((tm->tm_year - 1) / 100) + ((tm->tm_year + 299) / 400)));
134 	return (ret);
135 }
136 
137 char *
isc_tm_strptime(const char * buf,const char * fmt,struct tm * tm)138 isc_tm_strptime(const char *buf, const char *fmt, struct tm *tm) {
139 	char c, *ret;
140 	const char *bp;
141 	size_t len = 0;
142 	int alt_format, i, split_year = 0;
143 
144 	REQUIRE(buf != NULL);
145 	REQUIRE(fmt != NULL);
146 	REQUIRE(tm != NULL);
147 
148 	memset(tm, 0, sizeof(struct tm));
149 
150 	bp = buf;
151 
152 	while ((c = *fmt) != '\0') {
153 		/* Clear `alternate' modifier prior to new conversion. */
154 		alt_format = 0;
155 
156 		/* Eat up white-space. */
157 		if (isspace((unsigned char)c)) {
158 			while (isspace((unsigned char)*bp)) {
159 				bp++;
160 			}
161 
162 			fmt++;
163 			continue;
164 		}
165 
166 		if ((c = *fmt++) != '%') {
167 			goto literal;
168 		}
169 
170 	again:
171 		switch (c = *fmt++) {
172 		case '%': /* "%%" is converted to "%". */
173 		literal:
174 			if (c != *bp++) {
175 				return (0);
176 			}
177 			break;
178 
179 		/*
180 		 * "Alternative" modifiers. Just set the appropriate flag
181 		 * and start over again.
182 		 */
183 		case 'E': /* "%E?" alternative conversion modifier. */
184 			LEGAL_ALT(0);
185 			alt_format |= ALT_E;
186 			goto again;
187 
188 		case 'O': /* "%O?" alternative conversion modifier. */
189 			LEGAL_ALT(0);
190 			alt_format |= ALT_O;
191 			goto again;
192 
193 		/*
194 		 * "Complex" conversion rules, implemented through recursion.
195 		 */
196 		case 'c': /* Date and time, using the locale's format. */
197 			LEGAL_ALT(ALT_E);
198 			if (!(bp = isc_tm_strptime(bp, "%x %X", tm))) {
199 				return (0);
200 			}
201 			break;
202 
203 		case 'D': /* The date as "%m/%d/%y". */
204 			LEGAL_ALT(0);
205 			if (!(bp = isc_tm_strptime(bp, "%m/%d/%y", tm))) {
206 				return (0);
207 			}
208 			break;
209 
210 		case 'R': /* The time as "%H:%M". */
211 			LEGAL_ALT(0);
212 			if (!(bp = isc_tm_strptime(bp, "%H:%M", tm))) {
213 				return (0);
214 			}
215 			break;
216 
217 		case 'r': /* The time in 12-hour clock representation. */
218 			LEGAL_ALT(0);
219 			if (!(bp = isc_tm_strptime(bp, "%I:%M:%S %p", tm))) {
220 				return (0);
221 			}
222 			break;
223 
224 		case 'T': /* The time as "%H:%M:%S". */
225 			LEGAL_ALT(0);
226 			if (!(bp = isc_tm_strptime(bp, "%H:%M:%S", tm))) {
227 				return (0);
228 			}
229 			break;
230 
231 		case 'X': /* The time, using the locale's format. */
232 			LEGAL_ALT(ALT_E);
233 			if (!(bp = isc_tm_strptime(bp, "%H:%M:%S", tm))) {
234 				return (0);
235 			}
236 			break;
237 
238 		case 'x': /* The date, using the locale's format. */
239 			LEGAL_ALT(ALT_E);
240 			if (!(bp = isc_tm_strptime(bp, "%m/%d/%y", tm))) {
241 				return (0);
242 			}
243 			break;
244 
245 		/*
246 		 * "Elementary" conversion rules.
247 		 */
248 		case 'A': /* The day of week, using the locale's form. */
249 		case 'a':
250 			LEGAL_ALT(0);
251 			for (i = 0; i < 7; i++) {
252 				/* Full name. */
253 				len = strlen(day[i]);
254 				if (strncasecmp(day[i], bp, len) == 0) {
255 					break;
256 				}
257 
258 				/* Abbreviated name. */
259 				len = strlen(abday[i]);
260 				if (strncasecmp(abday[i], bp, len) == 0) {
261 					break;
262 				}
263 			}
264 
265 			/* Nothing matched. */
266 			if (i == 7) {
267 				return (0);
268 			}
269 
270 			tm->tm_wday = i;
271 			bp += len;
272 			break;
273 
274 		case 'B': /* The month, using the locale's form. */
275 		case 'b':
276 		case 'h':
277 			LEGAL_ALT(0);
278 			for (i = 0; i < 12; i++) {
279 				/* Full name. */
280 				len = strlen(mon[i]);
281 				if (strncasecmp(mon[i], bp, len) == 0) {
282 					break;
283 				}
284 
285 				/* Abbreviated name. */
286 				len = strlen(abmon[i]);
287 				if (strncasecmp(abmon[i], bp, len) == 0) {
288 					break;
289 				}
290 			}
291 
292 			/* Nothing matched. */
293 			if (i == 12) {
294 				return (0);
295 			}
296 
297 			tm->tm_mon = i;
298 			bp += len;
299 			break;
300 
301 		case 'C': /* The century number. */
302 			LEGAL_ALT(ALT_E);
303 			if (!(conv_num(&bp, &i, 0, 99))) {
304 				return (0);
305 			}
306 
307 			if (split_year) {
308 				tm->tm_year = (tm->tm_year % 100) + (i * 100);
309 			} else {
310 				tm->tm_year = i * 100;
311 				split_year = 1;
312 			}
313 			break;
314 
315 		case 'd': /* The day of month. */
316 		case 'e':
317 			LEGAL_ALT(ALT_O);
318 			if (!(conv_num(&bp, &tm->tm_mday, 1, 31))) {
319 				return (0);
320 			}
321 			break;
322 
323 		case 'k': /* The hour (24-hour clock representation). */
324 			LEGAL_ALT(0);
325 		/* FALLTHROUGH */
326 		case 'H':
327 			LEGAL_ALT(ALT_O);
328 			if (!(conv_num(&bp, &tm->tm_hour, 0, 23))) {
329 				return (0);
330 			}
331 			break;
332 
333 		case 'l': /* The hour (12-hour clock representation). */
334 			LEGAL_ALT(0);
335 		/* FALLTHROUGH */
336 		case 'I':
337 			LEGAL_ALT(ALT_O);
338 			if (!(conv_num(&bp, &tm->tm_hour, 1, 12))) {
339 				return (0);
340 			}
341 			if (tm->tm_hour == 12) {
342 				tm->tm_hour = 0;
343 			}
344 			break;
345 
346 		case 'j': /* The day of year. */
347 			LEGAL_ALT(0);
348 			if (!(conv_num(&bp, &i, 1, 366))) {
349 				return (0);
350 			}
351 			tm->tm_yday = i - 1;
352 			break;
353 
354 		case 'M': /* The minute. */
355 			LEGAL_ALT(ALT_O);
356 			if (!(conv_num(&bp, &tm->tm_min, 0, 59))) {
357 				return (0);
358 			}
359 			break;
360 
361 		case 'm': /* The month. */
362 			LEGAL_ALT(ALT_O);
363 			if (!(conv_num(&bp, &i, 1, 12))) {
364 				return (0);
365 			}
366 			tm->tm_mon = i - 1;
367 			break;
368 
369 		case 'p': /* The locale's equivalent of AM/PM. */
370 			LEGAL_ALT(0);
371 			/* AM? */
372 			if (strcasecmp(am_pm[0], bp) == 0) {
373 				if (tm->tm_hour > 11) {
374 					return (0);
375 				}
376 
377 				bp += strlen(am_pm[0]);
378 				break;
379 			}
380 			/* PM? */
381 			else if (strcasecmp(am_pm[1], bp) == 0)
382 			{
383 				if (tm->tm_hour > 11) {
384 					return (0);
385 				}
386 
387 				tm->tm_hour += 12;
388 				bp += strlen(am_pm[1]);
389 				break;
390 			}
391 
392 			/* Nothing matched. */
393 			return (0);
394 
395 		case 'S': /* The seconds. */
396 			LEGAL_ALT(ALT_O);
397 			if (!(conv_num(&bp, &tm->tm_sec, 0, 61))) {
398 				return (0);
399 			}
400 			break;
401 
402 		case 'U': /* The week of year, beginning on sunday. */
403 		case 'W': /* The week of year, beginning on monday. */
404 			LEGAL_ALT(ALT_O);
405 			/*
406 			 * XXX This is bogus, as we can not assume any valid
407 			 * information present in the tm structure at this
408 			 * point to calculate a real value, so just check the
409 			 * range for now.
410 			 */
411 			if (!(conv_num(&bp, &i, 0, 53))) {
412 				return (0);
413 			}
414 			break;
415 
416 		case 'w': /* The day of week, beginning on sunday. */
417 			LEGAL_ALT(ALT_O);
418 			if (!(conv_num(&bp, &tm->tm_wday, 0, 6))) {
419 				return (0);
420 			}
421 			break;
422 
423 		case 'Y': /* The year. */
424 			LEGAL_ALT(ALT_E);
425 			if (!(conv_num(&bp, &i, 0, 9999))) {
426 				return (0);
427 			}
428 
429 			tm->tm_year = i - TM_YEAR_BASE;
430 			break;
431 
432 		case 'y': /* The year within 100 years of the epoch. */
433 			LEGAL_ALT(ALT_E | ALT_O);
434 			if (!(conv_num(&bp, &i, 0, 99))) {
435 				return (0);
436 			}
437 
438 			if (split_year) {
439 				tm->tm_year = ((tm->tm_year / 100) * 100) + i;
440 				break;
441 			}
442 			split_year = 1;
443 			if (i <= 68) {
444 				tm->tm_year = i + 2000 - TM_YEAR_BASE;
445 			} else {
446 				tm->tm_year = i + 1900 - TM_YEAR_BASE;
447 			}
448 			break;
449 
450 		/*
451 		 * Miscellaneous conversions.
452 		 */
453 		case 'n': /* Any kind of white-space. */
454 		case 't':
455 			LEGAL_ALT(0);
456 			while (isspace((unsigned char)*bp)) {
457 				bp++;
458 			}
459 			break;
460 
461 		default: /* Unknown/unsupported conversion. */
462 			return (0);
463 		}
464 	}
465 
466 	/* LINTED functional specification */
467 	DE_CONST(bp, ret);
468 	return (ret);
469 }
470