Coverage Report

Created: 2026-10-22 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/mprintf.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#include "curlx/dynbuf.h"
27
#include "curl_printf.h"
28
#include "curlx/strparse.h"
29
#include "curlx/snprintf.h"  /* for curlx_win32_snprintf() */
30
31
66
#define BUFFSIZE 326 /* buffer for long-to-str and float-to-str calcs, should
32
                        fit negative DBL_MAX (317 letters) */
33
192
#define MAX_PARAMETERS 128 /* number of input arguments */
34
137
#define MAX_SEGMENTS   128 /* number of output segments */
35
36
/* Lower-case digits. */
37
const unsigned char Curl_ldigits[] = "0123456789abcdef";
38
39
/* Upper-case digits. */
40
const unsigned char Curl_udigits[] = "0123456789ABCDEF";
41
42
#define OUTCHAR(x)                        \
43
15
  do {                                    \
44
15
    if(stream((unsigned char)(x), userp)) \
45
15
      return TRUE;                        \
46
15
    (*donep)++;                           \
47
15
  } while(0)
48
49
/* Data type to read from the arglist */
50
typedef enum {
51
  MTYPE_STRING,
52
  MTYPE_PTR,
53
  MTYPE_INTPTR,
54
  MTYPE_INT,
55
  MTYPE_LONG,
56
  MTYPE_LONGLONG,
57
  MTYPE_INTU,
58
  MTYPE_LONGU,
59
  MTYPE_LONGLONGU,
60
  MTYPE_DOUBLE,
61
  MTYPE_LONGDOUBLE,
62
  MTYPE_WIDTH,
63
  MTYPE_PRECISION
64
} FormatType;
65
66
/* conversion and display flags */
67
enum {
68
  FLAGS_SPACE      = 1 << 0,
69
  FLAGS_SHOWSIGN   = 1 << 1,
70
  FLAGS_LEFT       = 1 << 2,
71
  FLAGS_ALT        = 1 << 3,
72
  FLAGS_SHORT      = 1 << 4,
73
  FLAGS_LONG       = 1 << 5,
74
  FLAGS_LONGLONG   = 1 << 6,
75
  FLAGS_LONGDOUBLE = 1 << 7,
76
  FLAGS_PAD_NIL    = 1 << 8,
77
  FLAGS_UNSIGNED   = 1 << 9,
78
  FLAGS_OCTAL      = 1 << 10,
79
  FLAGS_HEX        = 1 << 11,
80
  FLAGS_UPPER      = 1 << 12,
81
  FLAGS_WIDTH      = 1 << 13, /* '*' or '*<num>$' used */
82
  FLAGS_WIDTHPARAM = 1 << 14, /* width PARAMETER was specified */
83
  FLAGS_PREC       = 1 << 15, /* precision was specified */
84
  FLAGS_PRECPARAM  = 1 << 16, /* precision PARAMETER was specified */
85
  FLAGS_CHAR       = 1 << 17, /* %c story */
86
  FLAGS_FLOATE     = 1 << 18, /* %e or %E */
87
  FLAGS_FLOATG     = 1 << 19, /* %g or %G */
88
  FLAGS_SUBSTR     = 1 << 20  /* no input, only substring */
89
};
90
91
enum {
92
  DOLLAR_UNKNOWN,
93
  DOLLAR_NOPE,
94
  DOLLAR_USE
95
};
96
97
/*
98
 * Describes an input va_arg type and hold its value.
99
 */
100
struct va_input {
101
  FormatType type; /* FormatType */
102
  union {
103
    const char *str;
104
    void *ptr;
105
    int64_t nums; /* signed */
106
    uint64_t numu; /* unsigned */
107
    double dnum;
108
  } val;
109
};
110
111
/*
112
 * Describes an output segment.
113
 */
114
struct outsegment {
115
  int width;     /* width OR width parameter number */
116
  int precision; /* precision OR precision parameter number */
117
  unsigned int flags;
118
  unsigned int input; /* input argument array index */
119
  const char *start; /* format string start to output */
120
  size_t outlen;     /* number of bytes from the format string to output */
121
};
122
123
struct nsprintf {
124
  char *buffer;
125
  size_t length;
126
  size_t max;
127
};
128
129
/* Output bytes are staged here and appended to the dynbuf in chunks: the
130
   dynbuf append overhead (bounds checks, growth, memcpy, null-termination)
131
   once per byte dominates formatting. 512 bytes of stack holds a typical
132
   request line or header in a single flush. */
133
#define ASPRINTF_STAGE_SIZE 512
134
135
struct asprintf {
136
  struct dynbuf *b;
137
  char merr;
138
  size_t nstage;
139
  unsigned char stage[ASPRINTF_STAGE_SIZE];
140
};
141
142
struct ioprintf {
143
  FILE *fd;
144
  bool error;
145
};
146
147
/* the provided input number is 1-based but this returns the number 0-based.
148
 *
149
 * returns -1 if no valid number was provided.
150
 */
151
static int dollarstring(const char *p, const char **end)
152
55
{
153
55
  curl_off_t num;
154
55
  if(curlx_str_number(&p, &num, MAX_PARAMETERS) ||
155
3
     curlx_str_single(&p, '$') || !num)
156
53
    return -1;
157
2
  *end = p;
158
2
  return (int)num - 1;
159
55
}
160
161
137
#define is_arg_used(x, y)   ((x)[(y) / 8] & (1 << ((y) & 7)))
162
137
#define mark_arg_used(x, y) ((x)[(y) / 8] |= (unsigned char)(1 << ((y) & 7)))
163
164
/*
165
 * Parse the format string.
166
 *
167
 * Create two arrays. One describes the inputs, one describes the outputs.
168
 *
169
 * Returns zero on success.
170
 */
171
172
189
#define PFMT_OK          0
173
0
#define PFMT_DOLLAR      1 /* bad dollar for main param */
174
0
#define PFMT_DOLLARWIDTH 2 /* bad dollar use for width */
175
0
#define PFMT_DOLLARPREC  3 /* bad dollar use for precision */
176
0
#define PFMT_MANYARGS    4 /* too many input arguments used */
177
0
#define PFMT_PREC        5 /* precision overflow */
178
0
#define PFMT_PRECMIX     6 /* bad mix of precision specifiers */
179
0
#define PFMT_WIDTH       7 /* width overflow */
180
0
#define PFMT_INPUTGAP    8 /* gap in arguments */
181
0
#define PFMT_WIDTHARG    9 /* attempted to use same arg twice, for width */
182
0
#define PFMT_PRECARG    10 /* attempted to use same arg twice, for prec */
183
0
#define PFMT_MANYSEGS   11 /* maxed out output segments */
184
185
static int parse_flags(const char **fmtp, unsigned int *flagsp, int use_dollar,
186
                       int *precp, int *widthp)
187
135
{
188
135
  const char *fmt = *fmtp;
189
135
  bool loopit = TRUE;
190
135
  unsigned int flags = 0;
191
135
  int width = 0;
192
135
  int precision = 0;
193
194
  /* Handle the flags */
195
167
  do {
196
167
    switch(*fmt++) {
197
0
    case ' ':
198
0
      flags |= FLAGS_SPACE;
199
0
      break;
200
7
    case '+':
201
7
      flags |= FLAGS_SHOWSIGN;
202
7
      break;
203
0
    case '-':
204
0
      flags |= FLAGS_LEFT;
205
0
      flags &= ~(unsigned int)FLAGS_PAD_NIL;
206
0
      break;
207
3
    case '#':
208
3
      flags |= FLAGS_ALT;
209
3
      break;
210
8
    case '.':
211
8
      if('*' == *fmt) {
212
        /* The precision is picked from a specified parameter */
213
1
        flags |= FLAGS_PRECPARAM;
214
1
        fmt++;
215
216
1
        if(use_dollar == DOLLAR_USE) {
217
0
          precision = dollarstring(fmt, &fmt);
218
0
          if(precision < 0)
219
            /* illegal combo */
220
0
            return PFMT_DOLLARPREC;
221
0
        }
222
1
        else
223
          /* get it from the next argument */
224
1
          precision = -1;
225
1
      }
226
7
      else {
227
7
        bool is_neg;
228
7
        curl_off_t num;
229
7
        flags |= FLAGS_PREC;
230
7
        is_neg = ('-' == *fmt);
231
7
        if(is_neg)
232
0
          fmt++;
233
7
        if(curlx_str_number(&fmt, &num, INT_MAX))
234
0
          return PFMT_PREC;
235
7
        precision = (int)num;
236
7
        if(is_neg)
237
0
          precision = -precision;
238
7
      }
239
8
      if((flags & (FLAGS_PREC | FLAGS_PRECPARAM)) ==
240
8
         (FLAGS_PREC | FLAGS_PRECPARAM))
241
        /* it is not permitted to use both kinds of precision for the same
242
           argument */
243
0
        return PFMT_PRECMIX;
244
8
      break;
245
8
    case 'h':
246
0
      flags |= FLAGS_SHORT;
247
0
      break;
248
#ifdef _WIN32
249
    case 'I':
250
      /* Non-ANSI integer extensions I32 I64 */
251
      if((fmt[0] == '3') && (fmt[1] == '2')) {
252
        flags |= FLAGS_LONG;
253
        fmt += 2;
254
      }
255
      else if((fmt[0] == '6') && (fmt[1] == '4')) {
256
        flags |= FLAGS_LONGLONG;
257
        fmt += 2;
258
      }
259
      else {
260
#if SIZEOF_SIZE_T > SIZEOF_LONG
261
        flags |= FLAGS_LONGLONG;
262
#else
263
        flags |= FLAGS_LONG;
264
#endif
265
      }
266
      break;
267
#endif /* _WIN32 */
268
6
    case 'l':
269
6
      if(flags & FLAGS_LONG)
270
2
        flags |= FLAGS_LONGLONG;
271
4
      else
272
4
        flags |= FLAGS_LONG;
273
6
      break;
274
0
    case 'L':
275
0
      flags |= FLAGS_LONGDOUBLE;
276
0
      break;
277
0
    case 'q':
278
0
      flags |= FLAGS_LONGLONG;
279
0
      break;
280
0
    case 'z':
281
      /* the code below generates a warning if -Wunreachable-code is
282
         used */
283
#if SIZEOF_SIZE_T > SIZEOF_LONG
284
      flags |= FLAGS_LONGLONG;
285
#else
286
0
      flags |= FLAGS_LONG;
287
0
#endif
288
0
      break;
289
0
    case 'O':
290
#if SIZEOF_CURL_OFF_T > SIZEOF_LONG
291
      flags |= FLAGS_LONGLONG;
292
#else
293
0
      flags |= FLAGS_LONG;
294
0
#endif
295
0
      break;
296
7
    case '0':
297
7
      if(!(flags & FLAGS_LEFT))
298
7
        flags |= FLAGS_PAD_NIL;
299
7
      FALLTHROUGH();
300
7
    case '1':
301
7
    case '2':
302
7
    case '3':
303
7
    case '4':
304
7
    case '5':
305
7
    case '6':
306
7
    case '7':
307
7
    case '8':
308
7
    case '9': {
309
7
      curl_off_t num;
310
7
      flags |= FLAGS_WIDTH;
311
7
      fmt--;
312
7
      if(curlx_str_number(&fmt, &num, INT_MAX))
313
0
        return PFMT_WIDTH;
314
7
      width = (int)num;
315
7
      break;
316
7
    }
317
1
    case '*':  /* read width from argument list */
318
1
      flags |= FLAGS_WIDTHPARAM;
319
1
      if(use_dollar == DOLLAR_USE) {
320
0
        width = dollarstring(fmt, &fmt);
321
0
        if(width < 0)
322
          /* illegal combo */
323
0
          return PFMT_DOLLARWIDTH;
324
0
      }
325
1
      else
326
        /* pick from the next argument */
327
1
        width = -1;
328
1
      break;
329
135
    default:
330
135
      loopit = FALSE;
331
135
      fmt--;
332
135
      break;
333
167
    } /* switch */
334
167
  } while(loopit); /* do */
335
135
  *flagsp = flags;
336
135
  *precp = precision;
337
135
  *widthp = width;
338
135
  *fmtp = fmt;
339
135
  return PFMT_OK;
340
135
}
341
342
static bool parse_conversion(const char f, unsigned int *flagp,
343
                             FormatType *typep)
344
135
{
345
135
  unsigned int flags = *flagp;
346
135
  FormatType type;
347
135
  switch(f) {
348
0
  case 'S':
349
0
    flags |= FLAGS_ALT;
350
0
    type = MTYPE_STRING;
351
0
    break;
352
81
  case 's':
353
81
    type = MTYPE_STRING;
354
81
    break;
355
0
  case 'n':
356
0
    type = MTYPE_INTPTR;
357
0
    break;
358
1
  case 'p':
359
1
    type = MTYPE_PTR;
360
1
    break;
361
26
  case 'd':
362
27
  case 'i':
363
27
    if(flags & FLAGS_LONGLONG)
364
1
      type = MTYPE_LONGLONG;
365
26
    else if(flags & FLAGS_LONG)
366
1
      type = MTYPE_LONG;
367
25
    else
368
25
      type = MTYPE_INT;
369
27
    break;
370
12
  case 'u':
371
12
    if(flags & FLAGS_LONGLONG)
372
1
      type = MTYPE_LONGLONGU;
373
11
    else if(flags & FLAGS_LONG)
374
1
      type = MTYPE_LONGU;
375
10
    else
376
10
      type = MTYPE_INTU;
377
12
    flags |= FLAGS_UNSIGNED;
378
12
    break;
379
1
  case 'o':
380
1
    if(flags & FLAGS_LONGLONG)
381
0
      type = MTYPE_LONGLONGU;
382
1
    else if(flags & FLAGS_LONG)
383
0
      type = MTYPE_LONGU;
384
1
    else
385
1
      type = MTYPE_INTU;
386
1
    flags |= FLAGS_OCTAL | FLAGS_UNSIGNED;
387
1
    break;
388
1
  case 'x':
389
1
    if(flags & FLAGS_LONGLONG)
390
0
      type = MTYPE_LONGLONGU;
391
1
    else if(flags & FLAGS_LONG)
392
0
      type = MTYPE_LONGU;
393
1
    else
394
1
      type = MTYPE_INTU;
395
1
    flags |= FLAGS_HEX | FLAGS_UNSIGNED;
396
1
    break;
397
1
  case 'X':
398
1
    if(flags & FLAGS_LONGLONG)
399
0
      type = MTYPE_LONGLONGU;
400
1
    else if(flags & FLAGS_LONG)
401
0
      type = MTYPE_LONGU;
402
1
    else
403
1
      type = MTYPE_INTU;
404
1
    flags |= FLAGS_HEX | FLAGS_UPPER | FLAGS_UNSIGNED;
405
1
    break;
406
2
  case 'c':
407
2
    type = MTYPE_INT;
408
2
    flags |= FLAGS_CHAR;
409
2
    break;
410
6
  case 'f':
411
6
    type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE;
412
6
    break;
413
0
  case 'F':
414
0
    type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE;
415
0
    flags |= FLAGS_UPPER;
416
0
    break;
417
1
  case 'e':
418
1
    type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE;
419
1
    flags |= FLAGS_FLOATE;
420
1
    break;
421
0
  case 'E':
422
0
    type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE;
423
0
    flags |= FLAGS_FLOATE | FLAGS_UPPER;
424
0
    break;
425
1
  case 'g':
426
1
    type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE;
427
1
    flags |= FLAGS_FLOATG;
428
1
    break;
429
1
  case 'G':
430
1
    type = flags & FLAGS_LONGDOUBLE ? MTYPE_LONGDOUBLE : MTYPE_DOUBLE;
431
1
    flags |= FLAGS_FLOATG | FLAGS_UPPER;
432
1
    break;
433
0
  default:
434
    /* invalid instruction, disregard and continue */
435
0
    return TRUE;
436
135
  } /* switch */
437
438
135
  *flagp |= flags;
439
135
  *typep = type;
440
135
  return FALSE;
441
135
}
442
443
static int parsefmt(const char *format,
444
                    struct outsegment *out,
445
                    struct va_input *in,
446
                    int *opieces,
447
                    int *ipieces, va_list arglist)
448
54
{
449
54
  const char *fmt = format;
450
54
  int param_num = 0;
451
54
  int max_param = -1;
452
54
  int i;
453
54
  int ocount = 0;
454
54
  unsigned char usedinput[MAX_PARAMETERS / 8];
455
54
  size_t outlen = 0;
456
54
  struct outsegment *optr;
457
54
  int use_dollar = DOLLAR_UNKNOWN;
458
54
  const char *start = fmt;
459
460
  /* clear, set a bit for each used input */
461
54
  memset(usedinput, 0, sizeof(usedinput));
462
463
461
  while(*fmt) {
464
407
    if(*fmt == '%') {
465
136
      struct va_input *iptr;
466
136
      FormatType type;
467
136
      unsigned int flags = 0;
468
136
      int width = 0;
469
136
      int precision = 0;
470
136
      int param = -1;
471
136
      int rc;
472
136
      fmt++;
473
136
      outlen = (size_t)(fmt - start - 1);
474
136
      if(*fmt == '%') {
475
        /* this means a %% that should be output only as %. Create an output
476
           segment. */
477
1
        if(outlen) {
478
1
          optr = &out[ocount++];
479
1
          if(ocount > MAX_SEGMENTS)
480
0
            return PFMT_MANYSEGS;
481
1
          optr->input = 0;
482
1
          optr->flags = FLAGS_SUBSTR;
483
1
          optr->start = start;
484
1
          optr->outlen = outlen;
485
1
        }
486
1
        start = fmt;
487
1
        fmt++;
488
1
        continue; /* while */
489
1
      }
490
491
135
      if(use_dollar != DOLLAR_NOPE) {
492
55
        param = dollarstring(fmt, &fmt);
493
55
        if(param < 0) {
494
53
          if(use_dollar == DOLLAR_USE)
495
            /* illegal combo */
496
0
            return PFMT_DOLLAR;
497
498
          /* we got no positional, get the next arg */
499
53
          param = -1;
500
53
          use_dollar = DOLLAR_NOPE;
501
53
        }
502
2
        else
503
2
          use_dollar = DOLLAR_USE;
504
55
      }
505
506
135
      rc = parse_flags(&fmt, &flags, use_dollar, &precision, &width);
507
135
      if(rc)
508
0
        return rc;
509
510
135
      if(parse_conversion(*fmt, &flags, &type))
511
0
        continue;
512
513
135
      if(flags & FLAGS_WIDTHPARAM) {
514
1
        if(width < 0)
515
1
          width = param_num++;
516
0
        else {
517
          /* if this identifies a parameter already used, this is illegal */
518
0
          if(is_arg_used(usedinput, width))
519
0
            return PFMT_WIDTHARG;
520
0
        }
521
1
        if(width >= MAX_PARAMETERS)
522
0
          return PFMT_MANYARGS;
523
1
        if(width >= max_param)
524
1
          max_param = width;
525
526
1
        in[width].type = MTYPE_WIDTH;
527
        /* mark as used */
528
1
        mark_arg_used(usedinput, width);
529
1
      }
530
531
135
      if(flags & FLAGS_PRECPARAM) {
532
1
        if(precision < 0)
533
1
          precision = param_num++;
534
0
        else {
535
          /* if this identifies a parameter already used, this is illegal */
536
0
          if(is_arg_used(usedinput, precision))
537
0
            return PFMT_PRECARG;
538
0
        }
539
1
        if(precision >= MAX_PARAMETERS)
540
0
          return PFMT_MANYARGS;
541
1
        if(precision >= max_param)
542
1
          max_param = precision;
543
544
1
        in[precision].type = MTYPE_PRECISION;
545
1
        mark_arg_used(usedinput, precision);
546
1
      }
547
548
      /* Handle the specifier */
549
135
      if(param < 0)
550
133
        param = param_num++;
551
135
      if(param >= MAX_PARAMETERS)
552
0
        return PFMT_MANYARGS;
553
135
      if(param >= max_param)
554
134
        max_param = param;
555
556
135
      iptr = &in[param];
557
135
      iptr->type = type;
558
559
      /* mark this input as used */
560
135
      mark_arg_used(usedinput, param);
561
562
135
      fmt++;
563
135
      optr = &out[ocount++];
564
135
      if(ocount > MAX_SEGMENTS)
565
0
        return PFMT_MANYSEGS;
566
135
      optr->input = (unsigned int)param;
567
135
      optr->flags = flags;
568
135
      optr->width = width;
569
135
      optr->precision = precision;
570
135
      optr->start = start;
571
135
      optr->outlen = outlen;
572
135
      start = fmt;
573
135
    }
574
271
    else
575
271
      fmt++;
576
407
  }
577
578
  /* is there a trailing piece */
579
54
  outlen = (size_t)(fmt - start);
580
54
  if(outlen) {
581
1
    optr = &out[ocount++];
582
1
    if(ocount > MAX_SEGMENTS)
583
0
      return PFMT_MANYSEGS;
584
1
    optr->input = 0;
585
1
    optr->flags = FLAGS_SUBSTR;
586
1
    optr->start = start;
587
1
    optr->outlen = outlen;
588
1
  }
589
590
  /* Read the arg list parameters into our data list */
591
191
  for(i = 0; i < max_param + 1; i++) {
592
137
    struct va_input *iptr = &in[i];
593
137
    if(!is_arg_used(usedinput, i))
594
      /* bad input */
595
0
      return PFMT_INPUTGAP;
596
597
    /* based on the type, read the correct argument */
598
137
    switch(iptr->type) {
599
81
    case MTYPE_STRING:
600
81
      iptr->val.str = va_arg(arglist, const char *);
601
81
      break;
602
603
0
    case MTYPE_INTPTR:
604
1
    case MTYPE_PTR:
605
1
      iptr->val.ptr = va_arg(arglist, void *);
606
1
      break;
607
608
1
    case MTYPE_LONGLONGU:
609
1
      iptr->val.numu = va_arg(arglist, uint64_t);
610
1
      break;
611
612
1
    case MTYPE_LONGLONG:
613
1
      iptr->val.nums = va_arg(arglist, int64_t);
614
1
      break;
615
616
1
    case MTYPE_LONGU:
617
1
      iptr->val.numu = va_arg(arglist, unsigned long);
618
1
      break;
619
620
1
    case MTYPE_LONG:
621
1
      iptr->val.nums = va_arg(arglist, long);
622
1
      break;
623
624
13
    case MTYPE_INTU:
625
13
      iptr->val.numu = va_arg(arglist, unsigned int);
626
13
      break;
627
628
27
    case MTYPE_INT:
629
28
    case MTYPE_WIDTH:
630
29
    case MTYPE_PRECISION:
631
29
      iptr->val.nums = va_arg(arglist, int);
632
29
      break;
633
634
9
    case MTYPE_DOUBLE:
635
9
      iptr->val.dnum = va_arg(arglist, double);
636
9
      break;
637
638
0
    case MTYPE_LONGDOUBLE:
639
0
      iptr->val.dnum = (double)va_arg(arglist, long double);
640
0
      break;
641
642
0
    default:
643
0
      DEBUGASSERT(NULL); /* unexpected */
644
0
      break;
645
137
    }
646
137
  }
647
54
  *ipieces = max_param + 1;
648
54
  *opieces = ocount;
649
650
54
  return PFMT_OK;
651
54
}
652
653
struct mproperty {
654
  int width;            /* Width of a field. */
655
  int prec;             /* Precision of a field. */
656
  unsigned int flags;
657
};
658
659
/* block output callback: consume up to 'len' bytes, return the number of
660
   bytes accepted. Accepting fewer than 'len' bytes aborts formatting, like
661
   the byte callback returning failure. May be NULL, in which case output
662
   falls back to the per-byte 'stream' callback. */
663
typedef size_t (*mp_streamn)(const unsigned char *buf, size_t len, void *f);
664
665
/* commit any output the sink is holding. Returns non-zero on failure. Sinks
666
   whose accepted bytes are already committed do not need one. */
667
typedef int (*mp_flush)(void *f);
668
669
/* emit a run of bytes through the block callback when available, else byte
670
   by byte. Returns TRUE to abort formatting (mirroring OUTCHAR). */
671
static bool stream_run(void *userp,
672
                       int (*stream)(unsigned char, void *),
673
                       mp_streamn streamn,
674
                       const unsigned char *buf, size_t len, int *donep)
675
195
{
676
195
  if(!len)
677
24
    return FALSE;
678
171
  if(streamn) {
679
171
    size_t n = streamn(buf, len, userp);
680
171
    *donep += (int)n;
681
171
    return n != len;
682
171
  }
683
0
  while(len--) {
684
0
    if(stream(*buf++, userp))
685
0
      return TRUE;
686
0
    (*donep)++;
687
0
  }
688
0
  return FALSE;
689
0
}
690
691
/* Padding is always spaces or zeros, so it comes from a constant rather than a
692
   buffer that has to be filled first. 16 keeps every width used in the tree to
693
   a single run; wider padding loops. */
694
static const char pad_spaces[] = "                ";
695
static const char pad_zeros[] = "0000000000000000";
696
7
#define PAD_RUN 16 /* strlen() of both of the above */
697
698
/* emit 'num' copies of the pad byte. Returns TRUE to abort formatting. */
699
static bool stream_pad(void *userp,
700
                       int (*stream)(unsigned char, void *),
701
                       mp_streamn streamn,
702
                       unsigned char pad, int num, int *donep)
703
125
{
704
125
  const unsigned char *src;
705
125
  if(num <= 0)
706
118
    return FALSE;
707
7
  if(pad == '0')
708
6
    src = (const unsigned char *)pad_zeros;
709
1
  else
710
1
    src = (const unsigned char *)pad_spaces;
711
7
  while(num > PAD_RUN) {
712
0
    if(stream_run(userp, stream, streamn, src, PAD_RUN, donep))
713
0
      return TRUE;
714
0
    num -= PAD_RUN;
715
0
  }
716
7
  return stream_run(userp, stream, streamn, src, (size_t)num, donep);
717
7
}
718
719
/* emit the leading null-terminated part of a run of at most 'len' bytes.
720
   Returns TRUE to abort formatting.
721
722
   A byte loop and not memchr(): 'len' is the requested precision, which
723
   out_string() does not clamp to the string length, so "%.64s" on a 10-byte
724
   string arrives with len == 64 and memchr() would read past the object. */
725
static bool stream_zrun(void *userp,
726
                        int (*stream)(unsigned char, void *),
727
                        mp_streamn streamn,
728
                        const char *str, size_t len, int *donep)
729
58
{
730
58
  size_t n = 0;
731
332
  while(n < len && str[n])
732
274
    n++;
733
58
  return stream_run(userp, stream, streamn,
734
58
                    (const unsigned char *)str, n, donep);
735
58
}
736
737
static bool out_double(void *userp,
738
                       int (*stream)(unsigned char, void *),
739
                       mp_streamn streamn,
740
                       struct mproperty *p,
741
                       double dnum,
742
                       char *work, int *donep)
743
8
{
744
8
  char fmt[32] = "%";
745
8
  char *fptr = &fmt[1];
746
8
  size_t left = sizeof(fmt) - strlen(fmt);
747
8
  int flags = p->flags;
748
8
  int width = p->width;
749
8
  int prec = p->prec;
750
751
8
  if(flags & FLAGS_LEFT)
752
0
    *fptr++ = '-';
753
8
  if(flags & FLAGS_SHOWSIGN)
754
1
    *fptr++ = '+';
755
8
  if(flags & FLAGS_SPACE)
756
0
    *fptr++ = ' ';
757
8
  if(flags & FLAGS_ALT)
758
0
    *fptr++ = '#';
759
760
8
  *fptr = 0;
761
762
8
  if(width >= 0) {
763
8
    size_t dlen;
764
8
    if(width >= BUFFSIZE)
765
0
      width = BUFFSIZE - 1;
766
    /* RECURSIVE USAGE */
767
8
    dlen = (size_t)curl_msnprintf(fptr, left, "%d", width);
768
8
    fptr += dlen;
769
8
    left -= dlen;
770
8
  }
771
8
  if(prec >= 0) {
772
    /* for each digit in the integer part, we can have one less
773
       precision */
774
6
    int maxprec = BUFFSIZE - 1;
775
6
    double val = dnum;
776
6
    int len;
777
6
    if(prec > maxprec)
778
0
      prec = maxprec - 1;
779
6
    if(width > 0 && prec <= width)
780
0
      maxprec -= width;
781
6
    while(maxprec && (val >= 10.0)) {
782
0
      val /= 10;
783
0
      maxprec--;
784
0
    }
785
786
6
    if(prec > maxprec)
787
0
      prec = maxprec - 1;
788
6
    if(prec < 0)
789
0
      prec = 0;
790
    /* RECURSIVE USAGE */
791
6
    len = curl_msnprintf(fptr, left, ".%d", prec);
792
6
    fptr += len;
793
6
  }
794
8
  if(flags & FLAGS_LONG)
795
0
    *fptr++ = 'l';
796
797
8
  if(flags & FLAGS_FLOATE)
798
1
    *fptr++ = (char)((flags & FLAGS_UPPER) ? 'E' : 'e');
799
7
  else if(flags & FLAGS_FLOATG)
800
2
    *fptr++ = (char)((flags & FLAGS_UPPER) ? 'G' : 'g');
801
5
  else
802
5
    *fptr++ = (flags & FLAGS_UPPER) ? 'F' : 'f';
803
804
8
  *fptr = 0; /* and a final null-termination */
805
806
  /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
807
     output characters */
808
8
#ifdef CURL_HAVE_DIAG
809
8
#pragma GCC diagnostic push
810
8
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
811
8
#endif
812
#ifdef _WIN32
813
  curlx_win32_snprintf(work, BUFFSIZE, fmt, dnum);
814
#else
815
  /* !checksrc! disable BANNEDFUNC 1 */
816
8
  snprintf(work, BUFFSIZE, fmt, dnum);
817
8
#endif
818
8
#ifdef CURL_HAVE_DIAG
819
8
#pragma GCC diagnostic pop
820
8
#endif
821
8
  DEBUGASSERT(strlen(work) < BUFFSIZE);
822
8
  return stream_run(userp, stream, streamn,
823
8
                    (const unsigned char *)work, strlen(work), donep);
824
8
}
825
826
static bool out_number(void *userp,
827
                       int (*stream)(unsigned char, void *),
828
                       mp_streamn streamn,
829
                       struct mproperty *p,
830
                       uint64_t num,
831
                       int64_t nums,
832
                       char *work, int *donep)
833
44
{
834
44
  const unsigned char *digits = Curl_ldigits;
835
44
  int flags = p->flags;
836
44
  int width = p->width;
837
44
  int prec = p->prec;
838
44
  bool is_alt = flags & FLAGS_ALT;
839
44
  bool is_neg = FALSE;
840
44
  int base = 10;
841
842
  /* 'workend' points to the final buffer byte position, but with an extra
843
     byte as margin to avoid the (FALSE?) warning Coverity gives us
844
     otherwise */
845
44
  char *workend = &work[BUFFSIZE - 2];
846
44
  char *w;
847
848
44
  if(flags & FLAGS_CHAR) {
849
    /* Character. */
850
2
    if(!(flags & FLAGS_LEFT)) {
851
2
      if(stream_pad(userp, stream, streamn, ' ', width - 1, donep))
852
0
        return TRUE;
853
2
      width = 1;
854
2
    }
855
2
    OUTCHAR((char)num);
856
2
    if(flags & FLAGS_LEFT) {
857
0
      if(stream_pad(userp, stream, streamn, ' ', width - 1, donep))
858
0
        return TRUE;
859
0
    }
860
2
    return FALSE;
861
2
  }
862
42
  if(flags & FLAGS_OCTAL)
863
    /* Octal unsigned integer */
864
1
    base = 8;
865
866
41
  else if(flags & FLAGS_HEX) {
867
    /* Hexadecimal unsigned integer */
868
3
    digits = (flags & FLAGS_UPPER) ? Curl_udigits : Curl_ldigits;
869
3
    base = 16;
870
3
  }
871
38
  else if(flags & FLAGS_UNSIGNED)
872
    /* Decimal unsigned integer */
873
12
    ;
874
875
26
  else {
876
    /* Decimal integer. */
877
26
    is_neg = (nums < 0);
878
26
    if(is_neg) {
879
      /* signed_num might fail to hold absolute negative minimum by 1 */
880
7
      int64_t signed_num; /* Used to convert negative in positive. */
881
7
      signed_num = nums + (int64_t)1;
882
7
      signed_num = -signed_num;
883
7
      num = (uint64_t)signed_num;
884
7
      num += (uint64_t)1;
885
7
    }
886
26
  }
887
888
  /* Supply a default precision if none was given. */
889
42
  if(prec == -1)
890
42
    prec = 1;
891
892
  /* Put the number in WORK. */
893
42
  w = workend;
894
42
  DEBUGASSERT(base <= 16);
895
42
  switch(base) {
896
38
  case 10:
897
80
    while(num > 0) {
898
42
      *w-- = (char)('0' + (num % 10));
899
42
      num /= 10;
900
42
    }
901
38
    break;
902
4
  default:
903
22
    while(num > 0) {
904
18
      *w-- = digits[num % base];
905
18
      num /= base;
906
18
    }
907
4
    break;
908
42
  }
909
42
  width -= (int)(workend - w);
910
42
  prec -= (int)(workend - w);
911
912
42
  if(is_alt && base == 8 && prec <= 0) {
913
1
    *w-- = '0';
914
1
    --width;
915
1
  }
916
917
42
  if(prec > 0) {
918
10
    width -= prec;
919
20
    while(prec-- > 0 && w >= work)
920
10
      *w-- = '0';
921
10
  }
922
923
42
  if(is_alt && base == 16)
924
3
    width -= 2;
925
926
42
  if(is_neg || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE))
927
7
    --width;
928
929
42
  if(!(flags & FLAGS_LEFT) && !(flags & FLAGS_PAD_NIL)) {
930
36
    if(stream_pad(userp, stream, streamn, ' ', width, donep))
931
0
      return TRUE;
932
36
    width = 0;
933
36
  }
934
935
42
  if(is_neg)
936
7
    OUTCHAR('-');
937
35
  else if(flags & FLAGS_SHOWSIGN)
938
0
    OUTCHAR('+');
939
35
  else if(flags & FLAGS_SPACE)
940
0
    OUTCHAR(' ');
941
942
42
  if(is_alt && base == 16) {
943
3
    OUTCHAR('0');
944
3
    if(flags & FLAGS_UPPER)
945
1
      OUTCHAR('X');
946
2
    else
947
2
      OUTCHAR('x');
948
3
  }
949
950
42
  if(!(flags & FLAGS_LEFT) && (flags & FLAGS_PAD_NIL)) {
951
6
    if(stream_pad(userp, stream, streamn, '0', width, donep))
952
0
      return TRUE;
953
6
    width = 0;
954
6
  }
955
956
  /* Write the number. */
957
42
  if(stream_run(userp, stream, streamn, (const unsigned char *)w + 1,
958
42
                (size_t)(workend - w), donep))
959
1
    return TRUE;
960
961
41
  if(flags & FLAGS_LEFT) {
962
0
    if(stream_pad(userp, stream, streamn, ' ', width, donep))
963
0
      return TRUE;
964
0
  }
965
966
41
  return FALSE;
967
41
}
968
969
static const char nilstr[] = "(nil)";
970
971
static bool out_string(void *userp,
972
                       int (*stream)(unsigned char, void *),
973
                       mp_streamn streamn,
974
                       struct mproperty *p,
975
                       const char *str,
976
                       int *donep)
977
81
{
978
81
  int flags = p->flags;
979
81
  int width = p->width;
980
81
  int prec = p->prec;
981
81
  size_t len;
982
983
81
  if(!str) {
984
    /* Write null string if there is space. */
985
0
    if(prec == -1 || prec >= (int)CURL_CSTRLEN(nilstr)) {
986
0
      str = nilstr;
987
0
      len = CURL_CSTRLEN(nilstr);
988
      /* Disable quotes around (nil) */
989
0
      flags &= ~(unsigned int)FLAGS_ALT;
990
0
    }
991
0
    else {
992
0
      str = "";
993
0
      len = 0;
994
0
    }
995
0
  }
996
81
  else if(prec != -1)
997
1
    len = (size_t)prec;
998
80
  else if(*str == '\0')
999
24
    len = 0;
1000
56
  else
1001
56
    len = strlen(str);
1002
1003
81
  width -= (len > INT_MAX) ? INT_MAX : (int)len;
1004
1005
81
  if(flags & FLAGS_ALT)
1006
0
    OUTCHAR('"');
1007
1008
81
  if(!(flags & FLAGS_LEFT)) {
1009
80
    if(stream_pad(userp, stream, streamn, ' ', width, donep))
1010
0
      return TRUE;
1011
80
    width = 0;
1012
80
  }
1013
1014
  /* With no precision, len is already the exact length; emit it without
1015
     scanning again. With precision, scan up to len but stop at NUL, since
1016
     the string may be shorter or the buffer may not be null-terminated. */
1017
81
  if(prec == -1) {
1018
80
    if(stream_run(userp, stream, streamn,
1019
80
                  (const unsigned char *)str, len, donep))
1020
5
      return TRUE;
1021
80
  }
1022
1
  else if(stream_zrun(userp, stream, streamn, str, len, donep))
1023
0
    return TRUE;
1024
76
  if(flags & FLAGS_LEFT) {
1025
1
    if(stream_pad(userp, stream, streamn, ' ', width, donep))
1026
0
      return TRUE;
1027
1
  }
1028
1029
76
  if(flags & FLAGS_ALT)
1030
0
    OUTCHAR('"');
1031
1032
76
  return FALSE;
1033
76
}
1034
1035
static bool out_pointer(void *userp,
1036
                        int (*stream)(unsigned char, void *),
1037
                        mp_streamn streamn,
1038
                        struct mproperty *p,
1039
                        const char *ptr,
1040
                        char *work,
1041
                        int *donep)
1042
1
{
1043
  /* Generic pointer. */
1044
1
  if(ptr) {
1045
1
    size_t num = (size_t)ptr;
1046
1047
    /* If the pointer is not NULL, write it as a %#x spec. */
1048
1
    p->flags |= FLAGS_HEX | FLAGS_ALT;
1049
1
    if(out_number(userp, stream, streamn, p, num, 0, work, donep))
1050
0
      return TRUE;
1051
1
  }
1052
0
  else {
1053
    /* Write "(nil)" for a nil pointer. */
1054
0
    int width = p->width;
1055
0
    int flags = p->flags;
1056
1057
0
    width -= (int)CURL_CSTRLEN(nilstr);
1058
0
    if(flags & FLAGS_LEFT) {
1059
0
      if(stream_pad(userp, stream, streamn, ' ', width, donep))
1060
0
        return TRUE;
1061
0
      width = 0;
1062
0
    }
1063
0
    if(stream_run(userp, stream, streamn, (const unsigned char *)nilstr,
1064
0
                  sizeof(nilstr) - 1, donep))
1065
0
      return TRUE;
1066
0
    if(!(flags & FLAGS_LEFT)) {
1067
0
      if(stream_pad(userp, stream, streamn, ' ', width, donep))
1068
0
        return TRUE;
1069
0
    }
1070
0
  }
1071
1
  return FALSE;
1072
1
}
1073
1074
/*
1075
 * formatf() - the general printf function.
1076
 *
1077
 * It calls parsefmt() to parse the format string. It populates two arrays;
1078
 * one that describes the input arguments and one that describes a number of
1079
 * output segments.
1080
 *
1081
 * On success, the input array describes the type of all arguments and their
1082
 * values.
1083
 *
1084
 * The function then iterates over the output segments and outputs them one
1085
 * by one until done. Using the appropriate input arguments (if any).
1086
 *
1087
 * All output is sent to the 'stream()' callback, one byte at a time.
1088
 */
1089
static int formatf(void *userp, /* untouched by format(), sent to the
1090
                                   stream() function in the second argument */
1091
                   /* function pointer called for each output character */
1092
                   int (*stream)(unsigned char, void *),
1093
                   /* optional block-output function pointer */
1094
                   mp_streamn streamn,
1095
                   /* optional, commits output the sink is holding */
1096
                   mp_flush flush,
1097
                   const char *format, /* %-formatted string */
1098
                   va_list ap_save) /* list of parameters */
1099
54
{
1100
54
  int done = 0;   /* number of characters written */
1101
54
  int i;
1102
54
  int ocount = 0; /* number of output segments */
1103
54
  int icount = 0; /* number of input arguments */
1104
1105
54
  struct outsegment output[MAX_SEGMENTS];
1106
54
  struct va_input input[MAX_PARAMETERS];
1107
54
  char work[BUFFSIZE + 2];
1108
1109
  /* Parse the format string */
1110
54
  if(parsefmt(format, output, input, &ocount, &icount, ap_save))
1111
0
    return 0;
1112
1113
183
  for(i = 0; i < ocount; i++) {
1114
135
    struct outsegment *optr = &output[i];
1115
135
    struct va_input *iptr = &input[optr->input];
1116
135
    struct mproperty p;
1117
135
    size_t outlen = optr->outlen;
1118
1119
135
    if(outlen) {
1120
57
      if(stream_zrun(userp, stream, streamn, optr->start, outlen, &done))
1121
0
        return done;
1122
57
      if(optr->flags & FLAGS_SUBSTR)
1123
        /* this is a substring */
1124
2
        continue;
1125
57
    }
1126
1127
133
    p.flags = optr->flags;
1128
1129
    /* pick up the specified width */
1130
133
    if(p.flags & FLAGS_WIDTHPARAM) {
1131
1
      p.width = (int)input[optr->width].val.nums;
1132
1
      if(p.width < 0) {
1133
        /* "A negative field width is taken as a '-' flag followed by a
1134
           positive field width." */
1135
1
        if(p.width == INT_MIN)
1136
0
          p.width = INT_MAX;
1137
1
        else
1138
1
          p.width = -p.width;
1139
1
        p.flags |= FLAGS_LEFT;
1140
1
        p.flags &= ~(unsigned int)FLAGS_PAD_NIL;
1141
1
      }
1142
1
    }
1143
132
    else
1144
132
      p.width = optr->width;
1145
1146
    /* pick up the specified precision */
1147
133
    if(p.flags & FLAGS_PRECPARAM) {
1148
1
      p.prec = (int)input[optr->precision].val.nums;
1149
1
      if(p.prec < 0)
1150
        /* "A negative precision is taken as if the precision were
1151
           omitted." */
1152
0
        p.prec = -1;
1153
1
    }
1154
132
    else if(p.flags & FLAGS_PREC)
1155
6
      p.prec = optr->precision;
1156
126
    else
1157
126
      p.prec = -1;
1158
1159
133
    switch(iptr->type) {
1160
13
    case MTYPE_INTU:
1161
14
    case MTYPE_LONGU:
1162
15
    case MTYPE_LONGLONGU:
1163
15
      p.flags |= FLAGS_UNSIGNED;
1164
15
      if(out_number(userp, stream, streamn, &p, iptr->val.numu, 0, work,
1165
15
                    &done))
1166
0
        return done;
1167
15
      break;
1168
1169
26
    case MTYPE_INT:
1170
27
    case MTYPE_LONG:
1171
28
    case MTYPE_LONGLONG:
1172
28
      if(out_number(userp, stream, streamn, &p, iptr->val.numu,
1173
28
                    iptr->val.nums, work, &done))
1174
1
        return done;
1175
27
      break;
1176
1177
81
    case MTYPE_STRING:
1178
81
      if(out_string(userp, stream, streamn, &p, iptr->val.str, &done))
1179
5
        return done;
1180
76
      break;
1181
1182
76
    case MTYPE_PTR:
1183
1
      if(out_pointer(userp, stream, streamn, &p, iptr->val.ptr, work,
1184
1
                     &done))
1185
0
        return done;
1186
1
      break;
1187
1188
8
    case MTYPE_DOUBLE:
1189
8
    case MTYPE_LONGDOUBLE:
1190
8
      if(out_double(userp, stream, streamn, &p, iptr->val.dnum, work,
1191
8
                    &done))
1192
0
        return done;
1193
8
      break;
1194
1195
8
    case MTYPE_INTPTR:
1196
      /* %n is observable by the caller, so commit what is pending first and
1197
         perform it only if that succeeded, as a sink that never holds output
1198
         would. */
1199
0
      if(flush && flush(userp))
1200
0
        return done;
1201
      /* Answer the count of characters written. */
1202
0
      if(p.flags & FLAGS_LONGLONG)
1203
0
        *(int64_t *)iptr->val.ptr = (int64_t)done;
1204
0
      else if(p.flags & FLAGS_LONG)
1205
0
        *(long *)iptr->val.ptr = (long)done;
1206
0
      else if(!(p.flags & FLAGS_SHORT))
1207
0
        *(int *)iptr->val.ptr = done;
1208
0
      else
1209
0
        *(short *)iptr->val.ptr = (short)done;
1210
0
      break;
1211
1212
0
    default:
1213
0
      break;
1214
133
    }
1215
133
  }
1216
48
  return done;
1217
54
}
1218
1219
/* fputc() look-alike */
1220
static int addbyter(unsigned char outc, void *f)
1221
11
{
1222
11
  struct nsprintf *infop = f;
1223
11
  if(infop->length < infop->max) {
1224
    /* only do this if we have not reached max length yet */
1225
11
    *infop->buffer++ = (char)outc; /* store */
1226
11
    infop->length++; /* we are now one byte larger */
1227
11
    return 0;     /* fputc() returns like this on success */
1228
11
  }
1229
0
  return 1;
1230
11
}
1231
1232
/* block variant of addbyter */
1233
static size_t addrun(const unsigned char *buf, size_t len, void *f)
1234
91
{
1235
91
  struct nsprintf *infop = f;
1236
91
  size_t fit = infop->max - infop->length;
1237
91
  if(len > fit)
1238
3
    len = fit;
1239
91
  if(len) {
1240
90
    memcpy(infop->buffer, buf, len);
1241
90
    infop->buffer += len;
1242
90
    infop->length += len;
1243
90
  }
1244
91
  return len;
1245
91
}
1246
1247
int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
1248
                    va_list args)
1249
28
{
1250
28
  int retcode;
1251
28
  struct nsprintf info;
1252
1253
28
  info.buffer = buffer;
1254
28
  info.length = 0;
1255
28
  info.max = maxlength;
1256
1257
28
  retcode = formatf(&info, addbyter, addrun, NULL, format, args);
1258
28
  if(info.max) {
1259
    /* we null-terminate this */
1260
27
    if(info.max == info.length) {
1261
      /* we are at maximum, scrap the last letter */
1262
2
      info.buffer[-1] = 0;
1263
2
      DEBUGASSERT(retcode);
1264
2
      retcode--; /* do not count the NUL byte */
1265
2
    }
1266
25
    else
1267
25
      info.buffer[0] = 0;
1268
27
  }
1269
28
  return retcode;
1270
28
}
1271
1272
int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
1273
26
{
1274
26
  int retcode;
1275
26
  va_list args; /* argument pointer */
1276
26
  va_start(args, format);
1277
26
  retcode = curl_mvsnprintf(buffer, maxlength, format, args);
1278
26
  va_end(args);
1279
26
  return retcode;
1280
26
}
1281
1282
/* append the staged bytes to the dynbuf. Returns 1 on failure (and sets
1283
   merr), 0 on success. */
1284
static int alloc_flush(void *f)
1285
21
{
1286
21
  struct asprintf *infop = f;
1287
21
  if(infop->nstage) {
1288
20
    CURLcode result = curlx_dyn_addn(infop->b, infop->stage, infop->nstage);
1289
20
    infop->nstage = 0;
1290
20
    if(result) {
1291
0
      infop->merr = result == CURLE_TOO_LARGE ? MERR_TOO_LARGE : MERR_MEM;
1292
0
      return 1; /* fail */
1293
0
    }
1294
20
  }
1295
21
  return 0;
1296
21
}
1297
1298
/* append directly, bypassing the stage. Returns 1 on failure. */
1299
static int alloc_addn(struct asprintf *infop, const unsigned char *buf,
1300
                      size_t len)
1301
3
{
1302
3
  CURLcode result = curlx_dyn_addn(infop->b, buf, len);
1303
3
  if(result) {
1304
3
    infop->merr = result == CURLE_TOO_LARGE ? MERR_TOO_LARGE : MERR_MEM;
1305
3
    return 1; /* fail */
1306
3
  }
1307
0
  return 0;
1308
3
}
1309
1310
/* TRUE if 'more' additional bytes still fit the dynbuf size limit, counting
1311
   what is already staged. curlx_dyn_addn() rejects an append when
1312
   len + leng + 1 exceeds it. */
1313
static bool alloc_fits(struct asprintf *infop, size_t more)
1314
65
{
1315
65
  return (infop->b->leng + infop->nstage + more + 1) <= infop->b->toobig;
1316
65
}
1317
1318
/* fputc() look-alike */
1319
static int alloc_addbyter(unsigned char outc, void *f)
1320
2
{
1321
2
  struct asprintf *infop = f;
1322
2
  if(infop->nstage == sizeof(infop->stage) && alloc_flush(infop))
1323
0
    return 1; /* fail */
1324
2
  if(!alloc_fits(infop, 1)) {
1325
    /* Does not fit the dynbuf size limit. Flush and append this byte on
1326
       its own, so the limit is reported at exactly this byte and formatting
1327
       stops where it would without staging. %n depends on that. */
1328
0
    if(alloc_flush(infop))
1329
0
      return 1;
1330
0
    return alloc_addn(infop, &outc, 1);
1331
0
  }
1332
2
  infop->stage[infop->nstage++] = outc;
1333
2
  return 0;
1334
2
}
1335
1336
/* block variant of alloc_addbyter */
1337
static size_t alloc_addrun(const unsigned char *buf, size_t len, void *f)
1338
62
{
1339
62
  struct asprintf *infop = f;
1340
62
  size_t accepted = 0;
1341
122
  while(accepted < len) {
1342
63
    size_t room = sizeof(infop->stage) - infop->nstage;
1343
63
    size_t n;
1344
63
    if(!room) {
1345
1
      if(alloc_flush(infop))
1346
0
        return accepted; /* accepted < len aborts formatting */
1347
1
      room = sizeof(infop->stage);
1348
1
    }
1349
63
    n = len - accepted;
1350
63
    if(n > room)
1351
2
      n = room;
1352
63
    if(!alloc_fits(infop, n)) {
1353
      /* Run does not fit the dynbuf size limit. Stage what does, then
1354
         append the first byte that does not on its own, so the limit is
1355
         reported at exactly that byte. */
1356
3
      size_t fits = infop->b->toobig - infop->b->leng - infop->nstage - 1;
1357
3
      if(fits) {
1358
2
        memcpy(&infop->stage[infop->nstage], buf + accepted, fits);
1359
2
        infop->nstage += fits;
1360
2
        accepted += fits;
1361
2
      }
1362
3
      if(alloc_flush(infop))
1363
0
        return accepted;
1364
3
      if(alloc_addn(infop, buf + accepted, 1))
1365
3
        return accepted; /* accepted < len aborts formatting */
1366
0
      accepted++;
1367
0
      continue;
1368
3
    }
1369
60
    memcpy(&infop->stage[infop->nstage], buf + accepted, n);
1370
60
    infop->nstage += n;
1371
60
    accepted += n;
1372
60
  }
1373
59
  return accepted;
1374
62
}
1375
1376
/* appends the formatted string, returns MERR error code */
1377
int curlx_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list args)
1378
7
{
1379
7
  struct asprintf info;
1380
7
  info.b = dyn;
1381
7
  info.merr = MERR_OK;
1382
7
  info.nstage = 0;
1383
1384
7
  (void)formatf(&info, alloc_addbyter, alloc_addrun, alloc_flush,
1385
7
                format, args);
1386
7
  if(!info.merr)
1387
4
    (void)alloc_flush(&info);
1388
7
  if(info.merr) {
1389
3
    curlx_dyn_free(info.b);
1390
3
    return info.merr;
1391
3
  }
1392
4
  return 0;
1393
7
}
1394
1395
char *curl_mvaprintf(const char *format, va_list args)
1396
13
{
1397
13
  struct asprintf info;
1398
13
  struct dynbuf dyn;
1399
13
  info.b = &dyn;
1400
13
  curlx_dyn_init(info.b, DYN_APRINTF);
1401
13
  info.merr = MERR_OK;
1402
13
  info.nstage = 0;
1403
1404
13
  (void)formatf(&info, alloc_addbyter, alloc_addrun, alloc_flush,
1405
13
                format, args);
1406
13
  if(!info.merr)
1407
13
    (void)alloc_flush(&info);
1408
13
  if(info.merr) {
1409
0
    curlx_dyn_free(info.b);
1410
0
    return NULL;
1411
0
  }
1412
13
  if(curlx_dyn_len(info.b))
1413
13
    return curlx_dyn_ptr(info.b);
1414
0
  return curlx_strdup("");
1415
13
}
1416
1417
char *curl_maprintf(const char *format, ...)
1418
1
{
1419
1
  va_list args;
1420
1
  char *s;
1421
1
  va_start(args, format);
1422
1
  s = curl_mvaprintf(format, args);
1423
1
  va_end(args);
1424
1
  return s;
1425
1
}
1426
1427
static int storebuffer(unsigned char outc, void *f)
1428
1
{
1429
1
  char **buffer = f;
1430
1
  **buffer = (char)outc;
1431
1
  (*buffer)++;
1432
1
  return 0;
1433
1
}
1434
1435
/* block variant of storebuffer */
1436
static size_t storerun(const unsigned char *buf, size_t len, void *f)
1437
9
{
1438
9
  char **buffer = f;
1439
9
  memcpy(*buffer, buf, len);
1440
9
  *buffer += len;
1441
9
  return len;
1442
9
}
1443
1444
int curl_msprintf(char *buffer, const char *format, ...)
1445
1
{
1446
1
  va_list args; /* argument pointer */
1447
1
  int retcode;
1448
1
  va_start(args, format);
1449
1
  retcode = formatf(&buffer, storebuffer, storerun, NULL, format, args);
1450
1
  va_end(args);
1451
1
  *buffer = 0; /* we null-terminate this */
1452
1
  return retcode;
1453
1
}
1454
1455
static int fputc_wrapper(unsigned char outc, void *f)
1456
1
{
1457
1
  struct ioprintf *i = f;
1458
1
  int out = outc;
1459
1
  FILE *s = i->fd;
1460
1
  int rc = fputc(out, s);
1461
1
  i->error = (rc == EOF);
1462
1
  return (rc == EOF);
1463
1
}
1464
1465
/* block variant of fputc_wrapper */
1466
static size_t fwrite_wrapper(const unsigned char *buf, size_t len, void *f)
1467
9
{
1468
9
  struct ioprintf *i = f;
1469
9
  size_t n;
1470
9
  FILE *s = i->fd;
1471
9
  n = fwrite(buf, 1, len, s);
1472
9
  i->error = (n != len);
1473
9
  return n;
1474
9
}
1475
1476
int curl_mvfprintf(FILE *fd, const char *format, va_list args)
1477
4
{
1478
4
  struct ioprintf info;
1479
4
  int n;
1480
4
  info.fd = fd;
1481
4
  info.error = FALSE;
1482
4
  n = formatf(&info, fputc_wrapper, fwrite_wrapper, NULL, format, args);
1483
4
  if(info.error)
1484
0
    return -1;
1485
4
  return n;
1486
4
}
1487
1488
int curl_mfprintf(FILE *fd, const char *format, ...)
1489
1
{
1490
1
  va_list args; /* argument pointer */
1491
1
  int n;
1492
1
  va_start(args, format);
1493
1
  n = curl_mvfprintf(fd, format, args);
1494
1
  va_end(args);
1495
1
  return n;
1496
1
}
1497
1498
int curl_mprintf(const char *format, ...)
1499
1
{
1500
1
  va_list args; /* argument pointer */
1501
1
  int n;
1502
1
  va_start(args, format);
1503
1
  n = curl_mvfprintf(stdout, format, args);
1504
1
  va_end(args);
1505
1
  return n;
1506
1
}
1507
1508
int curl_mvsprintf(char *buffer, const char *format, va_list args)
1509
1
{
1510
1
  int retcode = formatf(&buffer, storebuffer, storerun, NULL, format, args);
1511
1
  *buffer = 0; /* we null-terminate this */
1512
1
  return retcode;
1513
1
}
1514
1515
int curl_mvprintf(const char *format, va_list args)
1516
1
{
1517
  return curl_mvfprintf(stdout, format, args);
1518
1
}