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