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