1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Copyright (c) 2011 The FreeBSD Foundation
6  * All rights reserved.
7  * Portions of this software were developed by David Chisnall
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms are permitted
11  * provided that the above copyright notice and this paragraph are
12  * duplicated in all such forms and that any documentation,
13  * advertising materials, and other materials related to such
14  * distribution and use acknowledge that the software was developed
15  * by the University of California, Berkeley. The name of the
16  * University may not be used to endorse or promote products derived
17  * from this software without specific prior written permission.
18  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21  */
22 
23 #include <fcntl.h>
24 #include <sys/cdefs.h>
25 #include <sys/stat.h>
26 
27 #include <time.h>
28 #include <ctype.h>
29 #include <errno.h>
30 #include <locale.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <pthread.h>
35 
36 #include "win_patch.h"
37 
38 static char *	_add(const char *, char *, const char *);
39 static char *	_conv(int, const char *, char *, const char *, _locale_t);
40 static char *	_fmt(const char *, const struct tm *, char *, const char *,
41 			int *, _locale_t);
42 static char *	_yconv(int, int, int, int, char *, const char *, _locale_t);
43 
44 #ifndef YEAR_2000_NAME
45 #define YEAR_2000_NAME	"CHECK_STRFTIME_FORMATS_FOR_TWO_DIGIT_YEARS"
46 #endif /* !defined YEAR_2000_NAME */
47 
48 #define	IN_NONE	0
49 #define	IN_SOME	1
50 #define	IN_THIS	2
51 #define	IN_ALL	3
52 
53 #define	PAD_DEFAULT	0
54 #define	PAD_LESS	1
55 #define	PAD_SPACE	2
56 #define	PAD_ZERO	3
57 
58 static const char fmt_padding[][4][5] = {
59 	/* DEFAULT,	LESS,	SPACE,	ZERO */
60 #define	PAD_FMT_MONTHDAY	0
61 #define	PAD_FMT_HMS		0
62 #define	PAD_FMT_CENTURY		0
63 #define	PAD_FMT_SHORTYEAR	0
64 #define	PAD_FMT_MONTH		0
65 #define	PAD_FMT_WEEKOFYEAR	0
66 #define	PAD_FMT_DAYOFMONTH	0
67 	{ "%02d",	"%d",	"%2d",	"%02d" },
68 #define	PAD_FMT_SDAYOFMONTH	1
69 #define	PAD_FMT_SHMS		1
70 	{ "%2d",	"%d",	"%2d",	"%02d" },
71 #define	PAD_FMT_DAYOFYEAR	2
72 	{ "%03d",	"%d",	"%3d",	"%03d" },
73 #define	PAD_FMT_YEAR		3
74 	{ "%04d",	"%d",	"%4d",	"%04d" }
75 };
76 
77 size_t
_patch_strftime_l(char * __restrict s,size_t maxsize,const char * __restrict format,const struct tm * __restrict t,_locale_t loc)78 _patch_strftime_l(char * __restrict s, size_t maxsize, const char * __restrict format,
79     const struct tm * __restrict t, _locale_t loc)
80 {
81 	char *	p;
82 	int	warn;
83 
84 	tzset();
85 	warn = IN_NONE;
86 	p = _fmt(((format == NULL) ? "%c" : format), t, s, s + maxsize, &warn, loc);
87 #ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
88 	if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
89 		(void) fprintf_l(stderr, loc, "\n");
90 		if (format == NULL)
91 			(void) fputs("NULL strftime format ", stderr);
92 		else	(void) fprintf_l(stderr, loc, "strftime format \"%s\" ",
93 				format);
94 		(void) fputs("yields only two digits of years in ", stderr);
95 		if (warn == IN_SOME)
96 			(void) fputs("some locales", stderr);
97 		else if (warn == IN_THIS)
98 			(void) fputs("the current locale", stderr);
99 		else	(void) fputs("all locales", stderr);
100 		(void) fputs("\n", stderr);
101 	}
102 #endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
103 	if (p == s + maxsize)
104 		return (0);
105 	*p = '\0';
106 	return p - s;
107 }
108 
109 size_t
_patch_strftime(char * __restrict s,size_t maxsize,const char * __restrict format,const struct tm * __restrict t)110 _patch_strftime(char * __restrict s, size_t maxsize, const char * __restrict format,
111     const struct tm * __restrict t)
112 {
113 #if HAVE__GET_CURRENT_LOCALE
114 	return _patch_strftime_l(s, maxsize, format, t, _get_current_locale());
115 #elif HAVE__CREATE_LOCALE && !IS_NT61
116 	return _patch_strftime_l(s, maxsize, format, t, _create_locale(LC_TIME, "C"));
117 #else
118 	_locale_t locale;
119 	return _patch_strftime_l(s, maxsize, format, t, locale);
120 #endif
121 }
122 
123 static char *
_fmt(const char * format,const struct tm * const t,char * pt,const char * const ptlim,int * warnp,_locale_t loc)124 _fmt(const char *format, const struct tm * const t, char *pt,
125     const char * const ptlim, int *warnp, _locale_t loc)
126 {
127 	int Ealternative, Oalternative, PadIndex;
128 	const struct lc_time_T *tptr = &_C_time_locale;
129 
130 	for ( ; *format; ++format) {
131 		if (*format == '%') {
132 			Ealternative = 0;
133 			Oalternative = 0;
134 			PadIndex	 = PAD_DEFAULT;
135 label:
136 			switch (*++format) {
137 			case '\0':
138 				--format;
139 				break;
140 			case 'A':
141 				pt = _add((t->tm_wday < 0 ||
142 					t->tm_wday >= DAYSPERWEEK) ?
143 					"?" : tptr->weekday[t->tm_wday],
144 					pt, ptlim);
145 				continue;
146 			case 'a':
147 				pt = _add((t->tm_wday < 0 ||
148 					t->tm_wday >= DAYSPERWEEK) ?
149 					"?" : tptr->wday[t->tm_wday],
150 					pt, ptlim);
151 				continue;
152 			case 'B':
153 				pt = _add((t->tm_mon < 0 ||
154 					t->tm_mon >= MONSPERYEAR) ?
155 					"?" : (Oalternative ? tptr->alt_month :
156 					tptr->month)[t->tm_mon],
157 					pt, ptlim);
158 				continue;
159 			case 'b':
160 			case 'h':
161 				pt = _add((t->tm_mon < 0 ||
162 					t->tm_mon >= MONSPERYEAR) ?
163 					"?" : tptr->mon[t->tm_mon],
164 					pt, ptlim);
165 				continue;
166 			case 'C':
167 				/*
168 				 * %C used to do a...
169 				 *	_fmt("%a %b %e %X %Y", t);
170 				 * ...whereas now POSIX 1003.2 calls for
171 				 * something completely different.
172 				 * (ado, 1993-05-24)
173 				 */
174 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
175 					pt, ptlim, loc);
176 				continue;
177 			case 'c':
178 				{
179 				int warn2 = IN_SOME;
180 
181 				pt = _fmt(tptr->c_fmt, t, pt, ptlim, &warn2, loc);
182 				if (warn2 == IN_ALL)
183 					warn2 = IN_THIS;
184 				if (warn2 > *warnp)
185 					*warnp = warn2;
186 				}
187 				continue;
188 			case 'D':
189 				pt = _fmt("%m/%d/%y", t, pt, ptlim, warnp, loc);
190 				continue;
191 			case 'd':
192 				pt = _conv(t->tm_mday,
193 					fmt_padding[PAD_FMT_DAYOFMONTH][PadIndex],
194 					pt, ptlim, loc);
195 				continue;
196 			case 'E':
197 				if (Ealternative || Oalternative)
198 					break;
199 				Ealternative++;
200 				goto label;
201 			case 'O':
202 				/*
203 				 * C99 locale modifiers.
204 				 * The sequences
205 				 *	%Ec %EC %Ex %EX %Ey %EY
206 				 *	%Od %oe %OH %OI %Om %OM
207 				 *	%OS %Ou %OU %OV %Ow %OW %Oy
208 				 * are supposed to provide alternate
209 				 * representations.
210 				 *
211 				 * FreeBSD extension
212 				 *      %OB
213 				 */
214 				if (Ealternative || Oalternative)
215 					break;
216 				Oalternative++;
217 				goto label;
218 			case 'e':
219 				pt = _conv(t->tm_mday,
220 					fmt_padding[PAD_FMT_SDAYOFMONTH][PadIndex],
221 					pt, ptlim, loc);
222 				continue;
223 			case 'F':
224 				pt = _fmt("%Y-%m-%d", t, pt, ptlim, warnp, loc);
225 				continue;
226 			case 'H':
227 				pt = _conv(t->tm_hour, fmt_padding[PAD_FMT_HMS][PadIndex],
228 					pt, ptlim, loc);
229 				continue;
230 			case 'I':
231 				pt = _conv((t->tm_hour % 12) ?
232 					(t->tm_hour % 12) : 12,
233 					fmt_padding[PAD_FMT_HMS][PadIndex],
234 					pt, ptlim, loc);
235 				continue;
236 			case 'j':
237 				pt = _conv(t->tm_yday + 1,
238 					fmt_padding[PAD_FMT_DAYOFYEAR][PadIndex],
239 					pt, ptlim, loc);
240 				continue;
241 			case 'k':
242 				/*
243 				 * This used to be...
244 				 *	_conv(t->tm_hour % 12 ?
245 				 *		t->tm_hour % 12 : 12, 2, ' ');
246 				 * ...and has been changed to the below to
247 				 * match SunOS 4.1.1 and Arnold Robbins'
248 				 * strftime version 3.0. That is, "%k" and
249 				 * "%l" have been swapped.
250 				 * (ado, 1993-05-24)
251 				 */
252 				pt = _conv(t->tm_hour, fmt_padding[PAD_FMT_SHMS][PadIndex],
253 					pt, ptlim, loc);
254 				continue;
255 #ifdef KITCHEN_SINK
256 			case 'K':
257 				/*
258 				** After all this time, still unclaimed!
259 				*/
260 				pt = _add("kitchen sink", pt, ptlim);
261 				continue;
262 #endif /* defined KITCHEN_SINK */
263 			case 'l':
264 				/*
265 				 * This used to be...
266 				 *	_conv(t->tm_hour, 2, ' ');
267 				 * ...and has been changed to the below to
268 				 * match SunOS 4.1.1 and Arnold Robbin's
269 				 * strftime version 3.0. That is, "%k" and
270 				 * "%l" have been swapped.
271 				 * (ado, 1993-05-24)
272 				 */
273 				pt = _conv((t->tm_hour % 12) ?
274 					(t->tm_hour % 12) : 12,
275 					fmt_padding[PAD_FMT_SHMS][PadIndex],
276 					pt, ptlim, loc);
277 				continue;
278 			case 'M':
279 				pt = _conv(t->tm_min, fmt_padding[PAD_FMT_HMS][PadIndex],
280 					pt, ptlim, loc);
281 				continue;
282 			case 'm':
283 				pt = _conv(t->tm_mon + 1,
284 					fmt_padding[PAD_FMT_MONTH][PadIndex],
285 					pt, ptlim, loc);
286 				continue;
287 			case 'n':
288 				pt = _add("\n", pt, ptlim);
289 				continue;
290 			case 'p':
291 				pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
292 					tptr->pm : tptr->am,
293 					pt, ptlim);
294 				continue;
295 			case 'R':
296 				pt = _fmt("%H:%M", t, pt, ptlim, warnp, loc);
297 				continue;
298 			case 'r':
299 				pt = _fmt(tptr->ampm_fmt, t, pt, ptlim,
300 					warnp, loc);
301 				continue;
302 			case 'S':
303 				pt = _conv(t->tm_sec, fmt_padding[PAD_FMT_HMS][PadIndex],
304 					pt, ptlim, loc);
305 				continue;
306 			case 's':
307 				{
308 					struct tm	tm;
309 					char		buf[INT_STRLEN_MAXIMUM(
310 								time_t) + 1];
311 					time_t		mkt;
312 
313 					tm = *t;
314 					mkt = mktime(&tm);
315 					if (TYPE_SIGNED(time_t))
316 						(void) sprintf_l(buf, loc, "%lld", (long long)mkt);
317 					else
318 						(void) sprintf_l(buf, loc, "%llu", (unsigned long long)mkt);
319 					pt = _add(buf, pt, ptlim);
320 				}
321 				continue;
322 			case 'T':
323 				pt = _fmt("%H:%M:%S", t, pt, ptlim, warnp, loc);
324 				continue;
325 			case 't':
326 				pt = _add("\t", pt, ptlim);
327 				continue;
328 			case 'U':
329 				pt = _conv((t->tm_yday + DAYSPERWEEK -
330 					t->tm_wday) / DAYSPERWEEK,
331 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex],
332 					pt, ptlim, loc);
333 				continue;
334 			case 'u':
335 				/*
336 				 * From Arnold Robbins' strftime version 3.0:
337 				 * "ISO 8601: Weekday as a decimal number
338 				 * [1 (Monday) - 7]"
339 				 * (ado, 1993-05-24)
340 				 */
341 				pt = _conv((t->tm_wday == 0) ?
342 					DAYSPERWEEK : t->tm_wday,
343 					"%d", pt, ptlim, loc);
344 				continue;
345 			case 'V':	/* ISO 8601 week number */
346 			case 'G':	/* ISO 8601 year (four digits) */
347 			case 'g':	/* ISO 8601 year (two digits) */
348 /*
349  * From Arnold Robbins' strftime version 3.0: "the week number of the
350  * year (the first Monday as the first day of week 1) as a decimal number
351  * (01-53)."
352  * (ado, 1993-05-24)
353  *
354  * From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
355  * "Week 01 of a year is per definition the first week which has the
356  * Thursday in this year, which is equivalent to the week which contains
357  * the fourth day of January. In other words, the first week of a new year
358  * is the week which has the majority of its days in the new year. Week 01
359  * might also contain days from the previous year and the week before week
360  * 01 of a year is the last week (52 or 53) of the previous year even if
361  * it contains days from the new year. A week starts with Monday (day 1)
362  * and ends with Sunday (day 7). For example, the first week of the year
363  * 1997 lasts from 1996-12-30 to 1997-01-05..."
364  * (ado, 1996-01-02)
365  */
366 				{
367 					int	year;
368 					int	base;
369 					int	yday;
370 					int	wday;
371 					int	w;
372 
373 					year = t->tm_year;
374 					base = TM_YEAR_BASE;
375 					yday = t->tm_yday;
376 					wday = t->tm_wday;
377 					for ( ; ; ) {
378 						int	len;
379 						int	bot;
380 						int	top;
381 
382 						len = isleap_sum(year, base) ?
383 							DAYSPERLYEAR :
384 							DAYSPERNYEAR;
385 						/*
386 						 * What yday (-3 ... 3) does
387 						 * the ISO year begin on?
388 						 */
389 						bot = ((yday + 11 - wday) %
390 							DAYSPERWEEK) - 3;
391 						/*
392 						 * What yday does the NEXT
393 						 * ISO year begin on?
394 						 */
395 						top = bot -
396 							(len % DAYSPERWEEK);
397 						if (top < -3)
398 							top += DAYSPERWEEK;
399 						top += len;
400 						if (yday >= top) {
401 							++base;
402 							w = 1;
403 							break;
404 						}
405 						if (yday >= bot) {
406 							w = 1 + ((yday - bot) /
407 								DAYSPERWEEK);
408 							break;
409 						}
410 						--base;
411 						yday += isleap_sum(year, base) ?
412 							DAYSPERLYEAR :
413 							DAYSPERNYEAR;
414 					}
415 #ifdef XPG4_1994_04_09
416 					if ((w == 52 &&
417 						t->tm_mon == TM_JANUARY) ||
418 						(w == 1 &&
419 						t->tm_mon == TM_DECEMBER))
420 							w = 53;
421 #endif /* defined XPG4_1994_04_09 */
422 					if (*format == 'V')
423 						pt = _conv(w, fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex],
424 							pt, ptlim, loc);
425 					else if (*format == 'g') {
426 						*warnp = IN_ALL;
427 						pt = _yconv(year, base, 0, 1,
428 							pt, ptlim, loc);
429 					} else	pt = _yconv(year, base, 1, 1,
430 							pt, ptlim, loc);
431 				}
432 				continue;
433 			case 'v':
434 				/*
435 				 * From Arnold Robbins' strftime version 3.0:
436 				 * "date as dd-bbb-YYYY"
437 				 * (ado, 1993-05-24)
438 				 */
439 				pt = _fmt("%e-%b-%Y", t, pt, ptlim, warnp, loc);
440 				continue;
441 			case 'W':
442 				pt = _conv((t->tm_yday + DAYSPERWEEK -
443 					(t->tm_wday ?
444 					(t->tm_wday - 1) :
445 					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
446 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex],
447 					pt, ptlim, loc);
448 				continue;
449 			case 'w':
450 				pt = _conv(t->tm_wday, "%d", pt, ptlim, loc);
451 				continue;
452 			case 'X':
453 				pt = _fmt(tptr->X_fmt, t, pt, ptlim, warnp, loc);
454 				continue;
455 			case 'x':
456 				{
457 				int	warn2 = IN_SOME;
458 
459 				pt = _fmt(tptr->x_fmt, t, pt, ptlim, &warn2, loc);
460 				if (warn2 == IN_ALL)
461 					warn2 = IN_THIS;
462 				if (warn2 > *warnp)
463 					*warnp = warn2;
464 				}
465 				continue;
466 			case 'y':
467 				*warnp = IN_ALL;
468 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
469 					pt, ptlim, loc);
470 				continue;
471 			case 'Y':
472 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
473 					pt, ptlim, loc);
474 				continue;
475 			case 'Z':
476 #ifdef TM_ZONE
477 				if (t->TM_ZONE != NULL)
478 					pt = _add(t->TM_ZONE, pt, ptlim);
479 				else
480 #endif /* defined TM_ZONE */
481 				if (t->tm_isdst >= 0)
482 					pt = _add(_tzname[t->tm_isdst != 0],
483 						pt, ptlim);
484 				/*
485 				 * C99 says that %Z must be replaced by the
486 				 * empty string if the time zone is not
487 				 * determinable.
488 				 */
489 				continue;
490 			case 'z':
491 				{
492 				int		diff;
493 				char const *	sign;
494 
495 				if (t->tm_isdst < 0)
496 					continue;
497 #ifdef TM_GMTOFF
498 				diff = t->TM_GMTOFF;
499 #else /* !defined TM_GMTOFF */
500 				/*
501 				 * C99 says that the UTC offset must
502 				 * be computed by looking only at
503 				 * tm_isdst. This requirement is
504 				 * incorrect, since it means the code
505 				 * must rely on magic (in this case
506 				 * altzone and timezone), and the
507 				 * magic might not have the correct
508 				 * offset. Doing things correctly is
509 				 * tricky and requires disobeying C99;
510 				 * see GNU C strftime for details.
511 				 * For now, punt and conform to the
512 				 * standard, even though it's incorrect.
513 				 *
514 				 * C99 says that %z must be replaced by the
515 				 * empty string if the time zone is not
516 				 * determinable, so output nothing if the
517 				 * appropriate variables are not available.
518 				 */
519 				if (t->tm_isdst == 0)
520 					diff = -_timezone;
521 				else
522 #ifdef ALTZONE
523 					diff = -altzone;
524 #else /* !defined ALTZONE */
525 					// Fix the daylight saving time, see #54.
526 					diff = -(_timezone - 3600 * t->tm_isdst);
527 #endif /* !defined ALTZONE */
528 #endif /* !defined TM_GMTOFF */
529 				if (diff < 0) {
530 					sign = "-";
531 					diff = -diff;
532 				} else
533 					sign = "+";
534 				pt = _add(sign, pt, ptlim);
535 				diff /= SECSPERMIN;
536 				diff = (diff / MINSPERHOUR) * 100 +
537 					(diff % MINSPERHOUR);
538 				pt = _conv(diff,
539 					fmt_padding[PAD_FMT_YEAR][PadIndex],
540 					pt, ptlim, loc);
541 				}
542 				continue;
543 			case '+':
544 				pt = _fmt(tptr->date_fmt, t, pt, ptlim,
545 					warnp, loc);
546 				continue;
547 			case '-':
548 				if (PadIndex != PAD_DEFAULT)
549 					break;
550 				PadIndex = PAD_LESS;
551 				goto label;
552 			case '_':
553 				if (PadIndex != PAD_DEFAULT)
554 					break;
555 				PadIndex = PAD_SPACE;
556 				goto label;
557 			case '0':
558 				if (PadIndex != PAD_DEFAULT)
559 					break;
560 				PadIndex = PAD_ZERO;
561 				goto label;
562 			case '%':
563 			/*
564 			 * X311J/88-090 (4.12.3.5): if conversion char is
565 			 * undefined, behavior is undefined. Print out the
566 			 * character itself as printf(3) also does.
567 			 */
568 			default:
569 				break;
570 			}
571 		}
572 		if (pt == ptlim)
573 			break;
574 		*pt++ = *format;
575 	}
576 	return (pt);
577 }
578 
579 static char *
_conv(const int n,const char * const format,char * const pt,const char * const ptlim,_locale_t loc)580 _conv(const int n, const char * const format, char * const pt,
581     const char * const ptlim, _locale_t  loc)
582 {
583 	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
584 
585 	(void) sprintf_l(buf, loc, format, n);
586 	return _add(buf, pt, ptlim);
587 }
588 
589 static char *
_add(const char * str,char * pt,const char * const ptlim)590 _add(const char *str, char *pt, const char * const ptlim)
591 {
592 	while (pt < ptlim && (*pt = *str++) != '\0')
593 		++pt;
594 	return (pt);
595 }
596 
597 /*
598  * POSIX and the C Standard are unclear or inconsistent about
599  * what %C and %y do if the year is negative or exceeds 9999.
600  * Use the convention that %C concatenated with %y yields the
601  * same output as %Y, and that %Y contains at least 4 bytes,
602  * with more only if necessary.
603  */
604 
605 static char *
_yconv(const int a,const int b,const int convert_top,const int convert_yy,char * pt,const char * const ptlim,_locale_t loc)606 _yconv(const int a, const int b, const int convert_top, const int convert_yy,
607     char *pt, const char * const ptlim, _locale_t  loc)
608 {
609 	register int	lead;
610 	register int	trail;
611 
612 #define	DIVISOR	100
613 	trail = a % DIVISOR + b % DIVISOR;
614 	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
615 	trail %= DIVISOR;
616 	if (trail < 0 && lead > 0) {
617 		trail += DIVISOR;
618 		--lead;
619 	} else if (lead < 0 && trail > 0) {
620 		trail -= DIVISOR;
621 		++lead;
622 	}
623 	if (convert_top) {
624 		if (lead == 0 && trail < 0)
625 			pt = _add("-0", pt, ptlim);
626 		else	pt = _conv(lead, "%02d", pt, ptlim, loc);
627 	}
628 	if (convert_yy)
629 		pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt,
630 		     ptlim, loc);
631 	return (pt);
632 }
633