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