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