1 /*
   2  * Copyright 2010 Nexenta Systems, Inc.  All rights reserved.
   3  * Copyright (c) 2001 Alexey Zelkin <phantom@FreeBSD.org>
   4  * All rights reserved.
   5  *
   6  * Redistribution and use in source and binary forms, with or without
   7  * modification, are permitted provided that the following conditions
   8  * are met:
   9  * 1. Redistributions of source code must retain the above copyright
  10  *    notice, this list of conditions and the following disclaimer.
  11  * 2. Redistributions in binary form must reproduce the above copyright
  12  *    notice, this list of conditions and the following disclaimer in the
  13  *    documentation and/or other materials provided with the distribution.
  14  *
  15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25  * SUCH DAMAGE.
  26  *
  27  */
  28 
  29 #ifndef _LCONV_C99
  30 #define _LCONV_C99
  31 #endif
  32 
  33 #include "lint.h"
  34 #include <sys/types.h>
  35 #include <ctype.h>
  36 #include <errno.h>
  37 #include <limits.h>
  38 #include <locale.h>
  39 #include <monetary.h>
  40 #include <stdarg.h>
  41 #include <stdio.h>
  42 #include <stdlib.h>
  43 #include <string.h>
  44 
  45 /* internal flags */
  46 #define NEED_GROUPING           0x01    /* print digits grouped (default) */
  47 #define SIGN_POSN_USED          0x02    /* '+' or '(' usage flag */
  48 #define LOCALE_POSN             0x04    /* use locale defined +/- (default) */
  49 #define PARENTH_POSN            0x08    /* enclose negative amount in () */
  50 #define SUPRESS_CURR_SYMBOL     0x10    /* supress the currency from output */
  51 #define LEFT_JUSTIFY            0x20    /* left justify */
  52 #define USE_INTL_CURRENCY       0x40    /* use international currency symbol */
  53 #define IS_NEGATIVE             0x80    /* is argument value negative ? */
  54 
  55 /* internal macros */
  56 #define PRINT(CH) {                                             \
  57         if (dst >= s + maxsize)                              \
  58                 goto e2big_error;                               \
  59         *dst++ = CH;                                            \
  60 }
  61 
  62 #define PRINTS(STR) {                                           \
  63         char *tmps = STR;                                       \
  64         while (*tmps != '\0')                                   \
  65                 PRINT(*tmps++);                                 \
  66 }
  67 
  68 #define GET_NUMBER(VAR) {                                       \
  69         VAR = 0;                                                \
  70         while (isdigit((unsigned char)*fmt)) {                  \
  71                 if (VAR > INT_MAX / 10)                              \
  72                         goto e2big_error;                       \
  73                 VAR *= 10;                                      \
  74                 VAR += *fmt - '0';                              \
  75                 if (VAR < 0)                                 \
  76                         goto e2big_error;                       \
  77                 fmt++;                                          \
  78         }                                                       \
  79 }
  80 
  81 #define GRPCPY(howmany) {                                       \
  82         int i = howmany;                                        \
  83         while (i-- > 0) {                                    \
  84                 avalue_size--;                                  \
  85                 *--bufend = *(avalue+avalue_size+padded);       \
  86         }                                                       \
  87 }
  88 
  89 #define GRPSEP {                                                \
  90         *--bufend = thousands_sep;                              \
  91         groups++;                                               \
  92 }
  93 
  94 static void __setup_vars(int, char *, char *, char *, char **);
  95 static int __calc_left_pad(int, char *);
  96 static char *__format_grouped_double(double, int *, int, int, int);
  97 
  98 ssize_t
  99 strfmon(char *_RESTRICT_KYWD s, size_t maxsize,
 100     const char *_RESTRICT_KYWD format, ...)
 101 {
 102         va_list         ap;
 103         char            *dst;           /* output destination pointer */
 104         const char      *fmt;           /* current format poistion pointer */
 105         struct lconv    *lc;            /* pointer to lconv structure */
 106         char            *asciivalue;    /* formatted double pointer */
 107 
 108         int             flags;          /* formatting options */
 109         int             pad_char;       /* padding character */
 110         int             pad_size;       /* pad size */
 111         int             width;          /* field width */
 112         int             left_prec;      /* left precision */
 113         int             right_prec;     /* right precision */
 114         double          value;          /* just value */
 115         char            space_char = ' '; /* space after currency */
 116 
 117         char            cs_precedes;    /* values gathered from struct lconv */
 118         char            sep_by_space;
 119         char            sign_posn;
 120         char            *signstr;
 121         char            *currency_symbol;
 122 
 123         char            *tmpptr;        /* temporary vars */
 124         int             sverrno;
 125 
 126         va_start(ap, format);
 127 
 128         lc = localeconv();
 129         dst = s;
 130         fmt = format;
 131         asciivalue = NULL;
 132         currency_symbol = NULL;
 133         pad_size = 0;
 134 
 135         while (*fmt) {
 136                 /* pass nonformating characters AS IS */
 137                 if (*fmt != '%')
 138                         goto literal;
 139 
 140                 /* '%' found ! */
 141 
 142                 /* "%%" mean just '%' */
 143                 if (*(fmt+1) == '%') {
 144                         fmt++;
 145         literal:
 146                         PRINT(*fmt++);
 147                         continue;
 148                 }
 149 
 150                 /* set up initial values */
 151                 flags = (NEED_GROUPING|LOCALE_POSN);
 152                 pad_char = ' ';         /* padding character is "space" */
 153                 left_prec = -1;         /* no left precision specified */
 154                 right_prec = -1;        /* no right precision specified */
 155                 width = -1;             /* no width specified */
 156                 value = 0;              /* we have no value to print now */
 157 
 158                 /* Flags */
 159                 for (;;) {
 160                         switch (*++fmt) {
 161                                 case '=':       /* fill character */
 162                                         pad_char = *++fmt;
 163                                         if (pad_char == '\0')
 164                                                 goto format_error;
 165                                         continue;
 166                                 case '^':       /* not group currency  */
 167                                         flags &= ~(NEED_GROUPING);
 168                                         continue;
 169                                 case '+':       /* use locale defined signs */
 170                                         if (flags & SIGN_POSN_USED)
 171                                                 goto format_error;
 172                                         flags |= (SIGN_POSN_USED|LOCALE_POSN);
 173                                         continue;
 174                                 case '(':       /* enclose negatives with () */
 175                                         if (flags & SIGN_POSN_USED)
 176                                                 goto format_error;
 177                                         flags |= (SIGN_POSN_USED|PARENTH_POSN);
 178                                         continue;
 179                                 case '!':       /* suppress currency symbol */
 180                                         flags |= SUPRESS_CURR_SYMBOL;
 181                                         continue;
 182                                 case '-':       /* alignment (left)  */
 183                                         flags |= LEFT_JUSTIFY;
 184                                         continue;
 185                                 default:
 186                                         break;
 187                         }
 188                         break;
 189                 }
 190 
 191                 /* field Width */
 192                 if (isdigit((unsigned char)*fmt)) {
 193                         GET_NUMBER(width);
 194                         /*
 195                          * Do we have enough space to put number with
 196                          * required width ?
 197                          */
 198                         if ((unsigned int)width >= maxsize - (dst - s))
 199                                 goto e2big_error;
 200                 }
 201 
 202                 /* Left precision */
 203                 if (*fmt == '#') {
 204                         if (!isdigit((unsigned char)*++fmt))
 205                                 goto format_error;
 206                         GET_NUMBER(left_prec);
 207                         if ((unsigned int)left_prec >= maxsize - (dst - s))
 208                                 goto e2big_error;
 209                 }
 210 
 211                 /* Right precision */
 212                 if (*fmt == '.') {
 213                         if (!isdigit((unsigned char)*++fmt))
 214                                 goto format_error;
 215                         GET_NUMBER(right_prec);
 216                         if ((unsigned int)right_prec >= maxsize - (dst - s) -
 217                             left_prec)
 218                                 goto e2big_error;
 219                 }
 220 
 221                 /* Conversion Characters */
 222                 switch (*fmt++) {
 223                         case 'i':       /* use internaltion currency format */
 224                                 flags |= USE_INTL_CURRENCY;
 225                                 break;
 226                         case 'n':       /* use national currency format */
 227                                 flags &= ~(USE_INTL_CURRENCY);
 228                                 break;
 229                         default:
 230                                 /* required char missing or premature EOS */
 231                                 goto format_error;
 232                 }
 233 
 234                 if (currency_symbol != NULL)
 235                         free(currency_symbol);
 236                 if (flags & USE_INTL_CURRENCY) {
 237                         currency_symbol = strdup(lc->int_curr_symbol);
 238                         if (currency_symbol != NULL)
 239                                 space_char = *(currency_symbol+3);
 240                 } else
 241                         currency_symbol = strdup(lc->currency_symbol);
 242 
 243                 if (currency_symbol == NULL)
 244                         goto end_error;                 /* ENOMEM. */
 245 
 246                 /* value itself */
 247                 value = va_arg(ap, double);
 248 
 249                 /* detect sign */
 250                 if (value < 0) {
 251                         flags |= IS_NEGATIVE;
 252                         value = -value;
 253                 }
 254 
 255                 /* fill left_prec with amount of padding chars */
 256                 if (left_prec >= 0) {
 257                         pad_size = __calc_left_pad((flags ^ IS_NEGATIVE),
 258                             currency_symbol) -
 259                             __calc_left_pad(flags, currency_symbol);
 260                         if (pad_size < 0)
 261                                 pad_size = 0;
 262                 }
 263 
 264                 if (asciivalue != NULL)
 265                         free(asciivalue);
 266                 asciivalue = __format_grouped_double(value, &flags,
 267                     left_prec, right_prec, pad_char);
 268                 if (asciivalue == NULL)
 269                         goto end_error;         /* errno already set */
 270                                                 /* to ENOMEM by malloc() */
 271 
 272                 /* set some variables for later use */
 273                 __setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn,
 274                     &signstr);
 275 
 276                 /*
 277                  * Description of some LC_MONETARY's values:
 278                  *
 279                  * p_cs_precedes & n_cs_precedes
 280                  *
 281                  * = 1 - $currency_symbol precedes the value
 282                  *       for a monetary quantity with a non-negative value
 283                  * = 0 - symbol succeeds the value
 284                  *
 285                  * p_sep_by_space & n_sep_by_space
 286                  *
 287                  * = 0 - no space separates $currency_symbol
 288                  *       from the value for a monetary quantity with a
 289                  *       non-negative value
 290                  * = 1 - space separates the symbol from the value
 291                  * = 2 - space separates the symbol and the sign string,
 292                  *       if adjacent.
 293                  *
 294                  * p_sign_posn & n_sign_posn
 295                  *
 296                  * = 0 - parentheses enclose the quantity and the
 297                  *       $currency_symbol
 298                  * = 1 - the sign string precedes the quantity and the
 299                  *       $currency_symbol
 300                  * = 2 - the sign string succeeds the quantity and the
 301                  *       $currency_symbol
 302                  * = 3 - the sign string precedes the $currency_symbol
 303                  * = 4 - the sign string succeeds the $currency_symbol
 304                  *
 305                  */
 306 
 307                 tmpptr = dst;
 308 
 309                 while (pad_size-- > 0)
 310                         PRINT(' ');
 311 
 312                 if (sign_posn == 0 && (flags & IS_NEGATIVE))
 313                         PRINT('(');
 314 
 315                 if (cs_precedes == 1) {
 316                         if (sign_posn == 1 || sign_posn == 3) {
 317                                 PRINTS(signstr);
 318                                 if (sep_by_space == 2)          /* XXX: ? */
 319                                         PRINT(' ');
 320                         }
 321 
 322                         if (!(flags & SUPRESS_CURR_SYMBOL)) {
 323                                 PRINTS(currency_symbol);
 324 
 325                                 if (sign_posn == 4) {
 326                                         if (sep_by_space == 2)
 327                                                 PRINT(space_char);
 328                                         PRINTS(signstr);
 329                                         if (sep_by_space == 1)
 330                                                 PRINT(' ');
 331                                 } else if (sep_by_space == 1)
 332                                         PRINT(space_char);
 333                         }
 334                 } else if (sign_posn == 1)
 335                         PRINTS(signstr);
 336 
 337                 PRINTS(asciivalue);
 338 
 339                 if (cs_precedes == 0) {
 340                         if (sign_posn == 3) {
 341                                 if (sep_by_space == 1)
 342                                         PRINT(' ');
 343                                 PRINTS(signstr);
 344                         }
 345 
 346                         if (!(flags & SUPRESS_CURR_SYMBOL)) {
 347                                 if ((sign_posn == 3 && sep_by_space == 2) ||
 348                                     (sep_by_space == 1 && (sign_posn == 0 ||
 349                                     sign_posn == 1 || sign_posn == 2 ||
 350                                     sign_posn == 4)))
 351                                         PRINT(space_char);
 352                                 PRINTS(currency_symbol); /* XXX: len */
 353                                 if (sign_posn == 4) {
 354                                         if (sep_by_space == 2)
 355                                                 PRINT(' ');
 356                                         PRINTS(signstr);
 357                                 }
 358                         }
 359                 }
 360 
 361                 if (sign_posn == 2) {
 362                         if (sep_by_space == 2)
 363                                 PRINT(' ');
 364                         PRINTS(signstr);
 365                 }
 366 
 367                 if (sign_posn == 0 && (flags & IS_NEGATIVE))
 368                         PRINT(')');
 369 
 370                 if (dst - tmpptr < width) {
 371                         if (flags & LEFT_JUSTIFY) {
 372                                 while (dst - tmpptr < width)
 373                                         PRINT(' ');
 374                         } else {
 375                                 pad_size = dst-tmpptr;
 376                                 (void) memmove(tmpptr + width-pad_size, tmpptr,
 377                                     pad_size);
 378                                 (void) memset(tmpptr, ' ', width-pad_size);
 379                                 dst += width-pad_size;
 380                         }
 381                 }
 382         }
 383 
 384         PRINT('\0');
 385         va_end(ap);
 386         free(asciivalue);
 387         free(currency_symbol);
 388         return (dst - s - 1);   /* size of put data except trailing '\0' */
 389 
 390 e2big_error:
 391         errno = E2BIG;
 392         goto end_error;
 393 
 394 format_error:
 395         errno = EINVAL;
 396 
 397 end_error:
 398         sverrno = errno;
 399         if (asciivalue != NULL)
 400                 free(asciivalue);
 401         if (currency_symbol != NULL)
 402                 free(currency_symbol);
 403         errno = sverrno;
 404         va_end(ap);
 405         return (-1);
 406 }
 407 
 408 static void
 409 __setup_vars(int flags, char *cs_precedes, char *sep_by_space,
 410     char *sign_posn, char **signstr)
 411 {
 412 
 413         struct lconv *lc = localeconv();
 414 
 415         if ((flags & IS_NEGATIVE) && (flags & USE_INTL_CURRENCY)) {
 416                 *cs_precedes = lc->int_n_cs_precedes;
 417                 *sep_by_space = lc->int_n_sep_by_space;
 418                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_n_sign_posn;
 419                 *signstr = (lc->negative_sign[0] == '\0') ? "-"
 420                     : lc->negative_sign;
 421         } else if (flags & USE_INTL_CURRENCY) {
 422                 *cs_precedes = lc->int_p_cs_precedes;
 423                 *sep_by_space = lc->int_p_sep_by_space;
 424                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_p_sign_posn;
 425                 *signstr = lc->positive_sign;
 426         } else if (flags & IS_NEGATIVE) {
 427                 *cs_precedes = lc->n_cs_precedes;
 428                 *sep_by_space = lc->n_sep_by_space;
 429                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->n_sign_posn;
 430                 *signstr = (lc->negative_sign[0] == '\0') ? "-"
 431                     : lc->negative_sign;
 432         } else {
 433                 *cs_precedes = lc->p_cs_precedes;
 434                 *sep_by_space = lc->p_sep_by_space;
 435                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->p_sign_posn;
 436                 *signstr = lc->positive_sign;
 437         }
 438 
 439         /* Set defult values for unspecified information. */
 440         if (*cs_precedes != 0)
 441                 *cs_precedes = 1;
 442         if (*sep_by_space == CHAR_MAX)
 443                 *sep_by_space = 0;
 444         if (*sign_posn == CHAR_MAX)
 445                 *sign_posn = 0;
 446 }
 447 
 448 static int
 449 __calc_left_pad(int flags, char *cur_symb)
 450 {
 451 
 452         char cs_precedes, sep_by_space, sign_posn, *signstr;
 453         int left_chars = 0;
 454 
 455         __setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, &signstr);
 456 
 457         if (cs_precedes != 0) {
 458                 left_chars += strlen(cur_symb);
 459                 if (sep_by_space != 0)
 460                         left_chars++;
 461         }
 462 
 463         switch (sign_posn) {
 464                 case 1:
 465                         left_chars += strlen(signstr);
 466                         break;
 467                 case 3:
 468                 case 4:
 469                         if (cs_precedes != 0)
 470                                 left_chars += strlen(signstr);
 471         }
 472         return (left_chars);
 473 }
 474 
 475 static int
 476 get_groups(int size, char *grouping)
 477 {
 478 
 479         int     chars = 0;
 480 
 481         if (*grouping == CHAR_MAX || *grouping <= 0) /* no grouping ? */
 482                 return (0);
 483 
 484         while (size > (int)*grouping) {
 485                 chars++;
 486                 size -= (int)*grouping++;
 487                 /* no more grouping ? */
 488                 if (*grouping == CHAR_MAX)
 489                         break;
 490                 /* rest grouping with same value ? */
 491                 if (*grouping == 0) {
 492                         chars += (size - 1) / *(grouping - 1);
 493                         break;
 494                 }
 495         }
 496         return (chars);
 497 }
 498 
 499 /* convert double to ASCII */
 500 static char *
 501 __format_grouped_double(double value, int *flags,
 502     int left_prec, int right_prec, int pad_char)
 503 {
 504 
 505         char            *rslt;
 506         char            *avalue;
 507         int             avalue_size;
 508         char            fmt[32];
 509 
 510         size_t          bufsize;
 511         char            *bufend;
 512 
 513         int             padded;
 514 
 515         struct lconv    *lc = localeconv();
 516         char            *grouping;
 517         char            decimal_point;
 518         char            thousands_sep;
 519 
 520         int groups = 0;
 521 
 522         grouping = lc->mon_grouping;
 523         decimal_point = *lc->mon_decimal_point;
 524         if (decimal_point == '\0')
 525                 decimal_point = *lc->decimal_point;
 526         thousands_sep = *lc->mon_thousands_sep;
 527         if (thousands_sep == '\0')
 528                 thousands_sep = *lc->thousands_sep;
 529 
 530         /* fill left_prec with default value */
 531         if (left_prec == -1)
 532                 left_prec = 0;
 533 
 534         /* fill right_prec with default value */
 535         if (right_prec == -1) {
 536                 if (*flags & USE_INTL_CURRENCY)
 537                         right_prec = lc->int_frac_digits;
 538                 else
 539                         right_prec = lc->frac_digits;
 540 
 541                 if (right_prec == CHAR_MAX)     /* POSIX locale ? */
 542                         right_prec = 2;
 543         }
 544 
 545         if (*flags & NEED_GROUPING)
 546                 left_prec += get_groups(left_prec, grouping);
 547 
 548         /* convert to string */
 549         (void) snprintf(fmt, sizeof (fmt), "%%%d.%df",
 550             left_prec + right_prec + 1, right_prec);
 551         avalue_size = asprintf(&avalue, fmt, value);
 552         if (avalue_size < 0)
 553                 return (NULL);
 554 
 555         /* make sure that we've enough space for result string */
 556         bufsize = strlen(avalue)*2+1;
 557         rslt = calloc(1, bufsize);
 558         if (rslt == NULL) {
 559                 free(avalue);
 560                 return (NULL);
 561         }
 562         bufend = rslt + bufsize - 1;    /* reserve space for trailing '\0' */
 563 
 564         /* skip spaces at beggining */
 565         padded = 0;
 566         while (avalue[padded] == ' ') {
 567                 padded++;
 568                 avalue_size--;
 569         }
 570 
 571         if (right_prec > 0) {
 572                 bufend -= right_prec;
 573                 (void) memcpy(bufend, avalue + avalue_size+padded-right_prec,
 574                     right_prec);
 575                 *--bufend = decimal_point;
 576                 avalue_size -= (right_prec + 1);
 577         }
 578 
 579         if ((*flags & NEED_GROUPING) &&
 580             thousands_sep != '\0' &&    /* XXX: need investigation */
 581             *grouping != CHAR_MAX &&
 582             *grouping > 0) {
 583                 while (avalue_size > (int)*grouping) {
 584                         GRPCPY(*grouping);
 585                         GRPSEP;
 586                         grouping++;
 587 
 588                         /* no more grouping ? */
 589                         if (*grouping == CHAR_MAX)
 590                                 break;
 591 
 592                         /* rest grouping with same value ? */
 593                         if (*grouping == 0) {
 594                                 grouping--;
 595                                 while (avalue_size > *grouping) {
 596                                         GRPCPY(*grouping);
 597                                         GRPSEP;
 598                                 }
 599                         }
 600                 }
 601                 if (avalue_size != 0)
 602                         GRPCPY(avalue_size);
 603                 padded -= groups;
 604 
 605         } else {
 606                 bufend -= avalue_size;
 607                 (void) memcpy(bufend, avalue+padded, avalue_size);
 608                 if (right_prec == 0)
 609                         padded--;       /* decrease assumed $decimal_point */
 610         }
 611 
 612         /* do padding with pad_char */
 613         if (padded > 0) {
 614                 bufend -= padded;
 615                 (void) memset(bufend, pad_char, padded);
 616         }
 617 
 618         bufsize = bufsize - (bufend - rslt) + 1;
 619         (void) memmove(rslt, bufend, bufsize);
 620         free(avalue);
 621         return (rslt);
 622 }