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