Coverage Report

Created: 2026-09-14 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/http_chunks.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
#ifndef CURL_DISABLE_HTTP
27
28
#include "urldata.h" /* it includes http_chunks.h */
29
#include "curl_trc.h"
30
#include "http.h"    /* for Curl_verify_header */
31
#include "sendf.h"   /* for the client write stuff */
32
#include "curlx/dynbuf.h"
33
#include "multiif.h"
34
#include "curlx/strparse.h"
35
36
/*
37
   Chunk format (simplified):
38
39
   <HEX SIZE>[ chunk extension ] CRLF
40
   <DATA> CRLF
41
42
   Highlights from RFC2616 section 3.6 say:
43
44
   The chunked encoding modifies the body of a message in order to
45
   transfer it as a series of chunks, each with its own size indicator,
46
   followed by an OPTIONAL trailer containing entity-header fields. This
47
   allows dynamically produced content to be transferred along with the
48
   information necessary for the recipient to verify that it has
49
   received the full message.
50
51
       Chunked-Body   = *chunk
52
                        last-chunk
53
                        trailer
54
                        CRLF
55
56
       chunk          = chunk-size [ chunk-extension ] CRLF
57
                        chunk-data CRLF
58
       chunk-size     = 1*HEX
59
       last-chunk     = 1*("0") [ chunk-extension ] CRLF
60
61
       chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
62
       chunk-ext-name = token
63
       chunk-ext-val  = token | quoted-string
64
       chunk-data     = chunk-size(OCTET)
65
       trailer        = *(entity-header CRLF)
66
67
   The chunk-size field is a string of hex digits indicating the size of
68
   the chunk. The chunked encoding is ended by any chunk whose size is
69
   zero, followed by the trailer, which is terminated by an empty line.
70
71
 */
72
73
void Curl_httpchunk_init(struct Curl_easy *data, struct Curl_chunker *ch,
74
                         bool ignore_body, bool in_connect)
75
1.61k
{
76
1.61k
  (void)data;
77
1.61k
  ch->hexindex = 0;      /* start at 0 */
78
1.61k
  ch->state = CHUNK_HEX; /* we get hex first! */
79
1.61k
  ch->last_code = CHUNKE_OK;
80
1.61k
  curlx_dyn_init(&ch->trailer, DYN_H1_TRAILER);
81
1.61k
  ch->ignore_body = ignore_body;
82
1.61k
  ch->in_connect = in_connect;
83
1.61k
}
84
85
void Curl_httpchunk_reset(struct Curl_easy *data, struct Curl_chunker *ch,
86
                          bool ignore_body)
87
97
{
88
97
  (void)data;
89
97
  ch->hexindex = 0;      /* start at 0 */
90
97
  ch->state = CHUNK_HEX; /* we get hex first! */
91
97
  ch->last_code = CHUNKE_OK;
92
97
  curlx_dyn_reset(&ch->trailer);
93
97
  ch->ignore_body = ignore_body;
94
97
}
95
96
void Curl_httpchunk_free(struct Curl_easy *data, struct Curl_chunker *ch)
97
1.61k
{
98
1.61k
  (void)data;
99
1.61k
  curlx_dyn_free(&ch->trailer);
100
1.61k
}
101
102
bool Curl_httpchunk_is_done(struct Curl_easy *data, struct Curl_chunker *ch)
103
1.14k
{
104
1.14k
  (void)data;
105
1.14k
  return ch->state == CHUNK_DONE;
106
1.14k
}
107
108
static CURLcode httpchunk_readwrite(struct Curl_easy *data,
109
                                    struct Curl_chunker *ch,
110
                                    struct Curl_cwriter *cw_next,
111
                                    const char *buf, size_t blen,
112
                                    size_t *pconsumed)
113
1.62k
{
114
1.62k
  CURLcode result = CURLE_OK;
115
1.62k
  size_t piece;
116
117
1.62k
  *pconsumed = 0; /* nothing's written yet */
118
  /* first check terminal states that will not progress anywhere */
119
1.62k
  if(ch->state == CHUNK_DONE)
120
0
    return CURLE_OK;
121
1.62k
  if(ch->state == CHUNK_FAILED)
122
0
    return CURLE_RECV_ERROR;
123
124
  /* the original data is written to the client, but we go on with the
125
     chunk read process, to properly calculate the content length */
126
1.62k
  if(data->set.http_te_skip && !ch->ignore_body) {
127
43
    if(cw_next)
128
43
      result = Curl_cwriter_write(data, cw_next, CLIENTWRITE_BODY, buf, blen);
129
0
    else
130
0
      result = Curl_client_write(data, CLIENTWRITE_BODY, buf, blen);
131
43
    if(result) {
132
1
      ch->state = CHUNK_FAILED;
133
1
      ch->last_code = CHUNKE_PASSTHRU_ERROR;
134
1
      return result;
135
1
    }
136
43
  }
137
138
50.4k
  while(blen) {
139
48.9k
    switch(ch->state) {
140
1.65k
    case CHUNK_HEX:
141
1.65k
      if(ISXDIGIT(*buf)) {
142
1.37k
        if(ch->hexindex >= CHUNK_MAXNUM_LEN) {
143
3
          failf(data, "chunk hex-length longer than %d", CHUNK_MAXNUM_LEN);
144
3
          ch->state = CHUNK_FAILED;
145
3
          ch->last_code = CHUNKE_TOO_LONG_HEX; /* longer than we support */
146
3
          return CURLE_RECV_ERROR;
147
3
        }
148
1.37k
        ch->hexbuffer[ch->hexindex++] = *buf;
149
1.37k
        buf++;
150
1.37k
        blen--;
151
1.37k
        (*pconsumed)++;
152
1.37k
      }
153
274
      else {
154
274
        const char *p;
155
274
        if(ch->hexindex == 0) {
156
          /* This is illegal data, we received junk where we expected
157
             a hexadecimal digit. */
158
7
          failf(data, "chunk hex-length char not a hex digit: 0x%x",
159
7
                (unsigned int)*buf);
160
7
          ch->state = CHUNK_FAILED;
161
7
          ch->last_code = CHUNKE_ILLEGAL_HEX;
162
7
          return CURLE_RECV_ERROR;
163
7
        }
164
        /* blen and buf are unmodified */
165
267
        ch->hexbuffer[ch->hexindex] = 0;
166
267
        p = &ch->hexbuffer[0];
167
267
        if(curlx_str_hex(&p, &ch->datasize, CURL_OFF_T_MAX)) {
168
1
          failf(data, "invalid chunk size: '%s'", ch->hexbuffer);
169
1
          ch->state = CHUNK_FAILED;
170
1
          ch->last_code = CHUNKE_ILLEGAL_HEX;
171
1
          return CURLE_RECV_ERROR;
172
1
        }
173
266
        ch->state = CHUNK_LF; /* now wait for the CRLF */
174
266
      }
175
1.64k
      break;
176
177
8.53k
    case CHUNK_LF:
178
      /* waiting for the LF after a chunk size */
179
8.53k
      if(*buf == 0x0a) {
180
        /* we are now expecting data to come, unless size was zero! */
181
236
        if(ch->datasize == 0) {
182
63
          ch->state = CHUNK_TRAILER; /* now check for trailers */
183
63
        }
184
173
        else {
185
173
          ch->state = CHUNK_DATA;
186
173
          CURL_TRC_WRITE(data, "http_chunked, chunk start of %"
187
173
                         FMT_OFF_T " bytes", ch->datasize);
188
173
        }
189
236
      }
190
191
8.53k
      buf++;
192
8.53k
      blen--;
193
8.53k
      (*pconsumed)++;
194
8.53k
      break;
195
196
594
    case CHUNK_DATA:
197
      /* We expect 'datasize' of data. We have 'blen' right now, it can be
198
         more or less than 'datasize'. Get the smallest piece. */
199
594
      piece = blen;
200
594
      if(ch->datasize < (curl_off_t)blen)
201
69
        piece = curlx_sotouz(ch->datasize);
202
203
      /* Write the data portion available */
204
594
      if(!data->set.http_te_skip && !ch->ignore_body) {
205
152
        if(cw_next)
206
152
          result = Curl_cwriter_write(data, cw_next, CLIENTWRITE_BODY,
207
152
                                      buf, piece);
208
0
        else
209
0
          result = Curl_client_write(data, CLIENTWRITE_BODY, buf, piece);
210
152
        if(result) {
211
1
          ch->state = CHUNK_FAILED;
212
1
          ch->last_code = CHUNKE_PASSTHRU_ERROR;
213
1
          return result;
214
1
        }
215
152
      }
216
217
593
      *pconsumed += piece;
218
593
      ch->datasize -= piece; /* decrease amount left to expect */
219
593
      buf += piece;    /* move read pointer forward */
220
593
      blen -= piece;   /* decrease space left in this round */
221
593
      CURL_TRC_WRITE(data, "http_chunked, write %zu body bytes, %"
222
593
                     FMT_OFF_T " bytes in chunk remain",
223
593
                     piece, ch->datasize);
224
225
593
      if(ch->datasize == 0)
226
        /* end of data this round, we now expect a trailing CRLF */
227
76
        ch->state = CHUNK_POSTLF;
228
593
      break;
229
230
142
    case CHUNK_POSTLF:
231
142
      if(*buf == 0x0a) {
232
        /* The last one before we go back to hex state and start all over. */
233
55
        Curl_httpchunk_reset(data, ch, (bool)ch->ignore_body);
234
55
      }
235
87
      else if(*buf != 0x0d) {
236
16
        ch->state = CHUNK_FAILED;
237
16
        ch->last_code = CHUNKE_BAD_CHUNK;
238
16
        return CURLE_RECV_ERROR;
239
16
      }
240
126
      buf++;
241
126
      blen--;
242
126
      (*pconsumed)++;
243
126
      break;
244
245
34.7k
    case CHUNK_TRAILER:
246
34.7k
      if((*buf == 0x0d) || (*buf == 0x0a)) {
247
1.64k
        const char *tr = curlx_dyn_ptr(&ch->trailer);
248
        /* this is the end of a trailer, but if the trailer was zero bytes
249
           there was no trailer and we move on */
250
251
1.64k
        if(tr) {
252
1.64k
          size_t trlen;
253
1.64k
          result = curlx_dyn_addn(&ch->trailer, STRCONST("\x0d\x0a"));
254
1.64k
          if(result) {
255
0
            ch->state = CHUNK_FAILED;
256
0
            ch->last_code = CHUNKE_OUT_OF_MEMORY;
257
0
            return result;
258
0
          }
259
1.64k
          tr = curlx_dyn_ptr(&ch->trailer);
260
1.64k
          trlen = curlx_dyn_len(&ch->trailer);
261
262
          /* a trailer is delivered to the client as a header, so it must pass
263
             the same checks as a regular response header */
264
1.64k
          result = Curl_verify_header(data, tr, trlen);
265
1.64k
          if(result) {
266
7
            ch->state = CHUNK_FAILED;
267
7
            ch->last_code = CHUNKE_BAD_CHUNK;
268
7
            return result;
269
7
          }
270
271
1.63k
          if(!data->set.http_te_skip) {
272
1.28k
            int hd_type = CLIENTWRITE_HEADER | CLIENTWRITE_TRAILER;
273
1.28k
            if(ch->in_connect)
274
38
              hd_type |= CLIENTWRITE_CONNECT;
275
1.28k
            if(cw_next)
276
1.24k
              result = Curl_cwriter_write(data, cw_next, hd_type, tr, trlen);
277
38
            else
278
38
              result = Curl_client_write(data, hd_type, tr, trlen);
279
1.28k
            CURL_TRC_WRITE(data, "wrote trailer '%s'", tr);
280
1.28k
            if(result) {
281
6
              ch->state = CHUNK_FAILED;
282
6
              ch->last_code = CHUNKE_PASSTHRU_ERROR;
283
6
              return result;
284
6
            }
285
1.28k
          }
286
1.63k
          curlx_dyn_reset(&ch->trailer);
287
1.63k
          ch->state = CHUNK_TRAILER_CR;
288
1.63k
          if(*buf == 0x0a)
289
            /* already on the LF */
290
1.32k
            break;
291
1.63k
        }
292
6
        else {
293
          /* no trailer, we are on the final CRLF pair */
294
6
          ch->state = CHUNK_TRAILER_POSTCR;
295
6
          break; /* do not advance the pointer */
296
6
        }
297
1.64k
      }
298
33.0k
      else {
299
33.0k
        result = curlx_dyn_addn(&ch->trailer, buf, 1);
300
33.0k
        if(result) {
301
1
          ch->state = CHUNK_FAILED;
302
1
          ch->last_code = CHUNKE_OUT_OF_MEMORY;
303
1
          return result;
304
1
        }
305
33.0k
      }
306
33.3k
      buf++;
307
33.3k
      blen--;
308
33.3k
      (*pconsumed)++;
309
33.3k
      break;
310
311
1.63k
    case CHUNK_TRAILER_CR:
312
1.63k
      if(*buf == 0x0a) {
313
1.62k
        ch->state = CHUNK_TRAILER_POSTCR;
314
1.62k
        buf++;
315
1.62k
        blen--;
316
1.62k
        (*pconsumed)++;
317
1.62k
      }
318
2
      else {
319
2
        ch->state = CHUNK_FAILED;
320
2
        ch->last_code = CHUNKE_BAD_CHUNK;
321
2
        return CURLE_RECV_ERROR;
322
2
      }
323
1.62k
      break;
324
325
1.63k
    case CHUNK_TRAILER_POSTCR:
326
      /* We enter this state when a CR should arrive so we expect to
327
         have to first pass a CR before we wait for LF */
328
1.63k
      if((*buf != 0x0d) && (*buf != 0x0a)) {
329
        /* not a CR then it must be another header in the trailer */
330
1.62k
        ch->state = CHUNK_TRAILER;
331
1.62k
        break;
332
1.62k
      }
333
14
      if(*buf == 0x0d) {
334
        /* skip if CR */
335
2
        buf++;
336
2
        blen--;
337
2
        (*pconsumed)++;
338
2
      }
339
      /* now wait for the final LF */
340
14
      ch->state = CHUNK_STOP;
341
14
      break;
342
343
14
    case CHUNK_STOP:
344
14
      if(*buf == 0x0a) {
345
13
        blen--;
346
13
        (*pconsumed)++;
347
        /* Record the length of any data left in the end of the buffer
348
           even if there is no more chunks to read */
349
13
        ch->datasize = blen;
350
13
        ch->state = CHUNK_DONE;
351
13
        CURL_TRC_WRITE(data, "http_chunk, response complete");
352
13
        return CURLE_OK;
353
13
      }
354
1
      else {
355
1
        ch->state = CHUNK_FAILED;
356
1
        ch->last_code = CHUNKE_BAD_CHUNK;
357
1
        CURL_TRC_WRITE(data, "http_chunk error, expected 0x0a, seeing 0x%ux",
358
1
                       (unsigned int)*buf);
359
1
        return CURLE_RECV_ERROR;
360
1
      }
361
0
    case CHUNK_DONE:
362
0
      return CURLE_OK;
363
364
0
    case CHUNK_FAILED:
365
0
      return CURLE_RECV_ERROR;
366
48.9k
    }
367
48.9k
  }
368
1.56k
  return CURLE_OK;
369
1.62k
}
370
371
static const char *Curl_chunked_strerror(CHUNKcode code)
372
31
{
373
31
  switch(code) {
374
0
  default:
375
0
    return "OK";
376
3
  case CHUNKE_TOO_LONG_HEX:
377
3
    return "Too long hexadecimal number";
378
6
  case CHUNKE_ILLEGAL_HEX:
379
6
    return "Illegal or missing hexadecimal sequence";
380
21
  case CHUNKE_BAD_CHUNK:
381
21
    return "Malformed encoding found";
382
0
  case CHUNKE_PASSTHRU_ERROR:
383
0
    return "Error writing data to client";
384
0
  case CHUNKE_BAD_ENCODING:
385
0
    return "Bad content-encoding found";
386
1
  case CHUNKE_OUT_OF_MEMORY:
387
1
    return "Out of memory";
388
31
  }
389
31
}
390
391
CURLcode Curl_httpchunk_read(struct Curl_easy *data,
392
                             struct Curl_chunker *ch,
393
                             char *buf, size_t blen,
394
                             size_t *pconsumed)
395
1.15k
{
396
1.15k
  return httpchunk_readwrite(data, ch, NULL, buf, blen, pconsumed);
397
1.15k
}
398
399
struct chunked_writer {
400
  struct Curl_cwriter super;
401
  struct Curl_chunker ch;
402
};
403
404
static CURLcode cw_chunked_init(struct Curl_easy *data,
405
                                struct Curl_cwriter *writer)
406
230
{
407
230
  struct chunked_writer *ctx = writer->ctx;
408
409
230
  data->req.chunk = TRUE;      /* chunks coming our way. */
410
230
  Curl_httpchunk_init(data, &ctx->ch, FALSE, FALSE);
411
230
  return CURLE_OK;
412
230
}
413
414
static void cw_chunked_close(struct Curl_easy *data,
415
                             struct Curl_cwriter *writer)
416
230
{
417
230
  struct chunked_writer *ctx = writer->ctx;
418
230
  Curl_httpchunk_free(data, &ctx->ch);
419
230
}
420
421
static CURLcode cw_chunked_write(struct Curl_easy *data,
422
                                 struct Curl_cwriter *writer, int type,
423
                                 const char *buf, size_t blen)
424
2.68k
{
425
2.68k
  struct chunked_writer *ctx = writer->ctx;
426
2.68k
  CURLcode result;
427
2.68k
  size_t consumed;
428
429
2.68k
  if(!(type & CLIENTWRITE_BODY))
430
2.21k
    return Curl_cwriter_write(data, writer->next, type, buf, blen);
431
432
468
  consumed = 0;
433
468
  result = httpchunk_readwrite(data, &ctx->ch, writer->next, buf, blen,
434
468
                               &consumed);
435
436
468
  if(result) {
437
34
    if(CHUNKE_PASSTHRU_ERROR == ctx->ch.last_code) {
438
3
      failf(data, "Failed reading the chunked-encoded stream");
439
3
    }
440
31
    else {
441
31
      failf(data, "%s in chunked-encoding",
442
31
            Curl_chunked_strerror(ctx->ch.last_code));
443
31
    }
444
34
    return result;
445
34
  }
446
447
434
  blen -= consumed;
448
434
  if(CHUNK_DONE == ctx->ch.state) {
449
    /* chunks read successfully, download is complete */
450
10
    data->req.download_done = TRUE;
451
10
    if(blen) {
452
8
      infof(data, "Leftovers after chunking: %zu bytes", blen);
453
8
    }
454
10
  }
455
424
  else if((type & CLIENTWRITE_EOS) && !data->req.no_body) {
456
153
    failf(data, "transfer closed with outstanding read data remaining");
457
153
    return CURLE_PARTIAL_FILE;
458
153
  }
459
460
281
  return CURLE_OK;
461
434
}
462
463
/* HTTP chunked Transfer-Encoding decoder */
464
const struct Curl_cwtype Curl_httpchunk_unencoder = {
465
  "chunked",
466
  NULL,
467
  0,
468
  cw_chunked_init,
469
  cw_chunked_write,
470
  Curl_cwriter_def_flush,
471
  cw_chunked_close,
472
  sizeof(struct chunked_writer)
473
};
474
475
/* max length of an HTTP chunk that we want to generate */
476
#define CURL_CHUNKED_MINLEN   1024
477
362
#define CURL_CHUNKED_MAXLEN   (64 * 1024)
478
479
struct chunked_reader {
480
  struct Curl_creader super;
481
  struct bufq chunkbuf;
482
  BIT(read_eos);  /* we read an EOS from the next reader */
483
  BIT(eos);       /* we have returned an EOS */
484
};
485
486
static CURLcode cr_chunked_init(struct Curl_easy *data,
487
                                struct Curl_creader *reader)
488
362
{
489
362
  struct chunked_reader *ctx = reader->ctx;
490
362
  (void)data;
491
362
  Curl_bufq_init2(&ctx->chunkbuf, CURL_CHUNKED_MAXLEN, 2, BUFQ_OPT_SOFT_LIMIT);
492
362
  return CURLE_OK;
493
362
}
494
495
static void cr_chunked_close(struct Curl_easy *data,
496
                             struct Curl_creader *reader)
497
362
{
498
362
  struct chunked_reader *ctx = reader->ctx;
499
362
  (void)data;
500
362
  Curl_bufq_free(&ctx->chunkbuf);
501
362
}
502
503
static CURLcode add_last_chunk(struct Curl_easy *data,
504
                               struct Curl_creader *reader)
505
158
{
506
158
  struct chunked_reader *ctx = reader->ctx;
507
158
  struct curl_slist *trailers = NULL, *tr;
508
158
  CURLcode result;
509
158
  size_t n;
510
158
  int rc;
511
512
158
  if(!data->set.trailer_callback) {
513
158
    CURL_TRC_READ(data, "http_chunk, added last, empty chunk");
514
158
    return Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("0\r\n\r\n"), &n);
515
158
  }
516
517
0
  result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("0\r\n"), &n);
518
0
  if(result)
519
0
    goto out;
520
521
0
  {
522
0
    struct Curl_mapi_guard guard;
523
0
    CURL_CBAPI_START(&guard, data, easy_trailer_callback);
524
0
    rc = data->set.trailer_callback(&trailers, data->set.trailer_data);
525
0
    CURL_CBAPI_END(&guard);
526
0
  }
527
528
0
  if(rc != CURL_TRAILERFUNC_OK) {
529
0
    failf(data, "operation aborted by trailing headers callback");
530
0
    result = CURLE_ABORTED_BY_CALLBACK;
531
0
    goto out;
532
0
  }
533
534
0
  for(tr = trailers; tr; tr = tr->next) {
535
    /* only add correctly formatted trailers */
536
0
    const char *ptr = strchr(tr->data, ':');
537
0
    if(!ptr || *(ptr + 1) != ' ') {
538
0
      infof(data, "Malformatted trailing header, skipping trailer");
539
0
      continue;
540
0
    }
541
542
0
    result = Curl_bufq_cwrite(&ctx->chunkbuf, tr->data, strlen(tr->data), &n);
543
0
    if(!result)
544
0
      result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("\r\n"), &n);
545
0
    if(result)
546
0
      goto out;
547
0
  }
548
549
0
  result = Curl_bufq_cwrite(&ctx->chunkbuf, STRCONST("\r\n"), &n);
550
551
0
out:
552
0
  curl_slist_free_all(trailers);
553
0
  CURL_TRC_READ(data, "http_chunk, added last chunk with trailers "
554
0
                "from client -> %d", (int)result);
555
0
  return result;
556
0
}
557
558
static CURLcode add_chunk(struct Curl_easy *data,
559
                          struct Curl_creader *reader,
560
                          char *buf, size_t blen)
561
703
{
562
703
  struct chunked_reader *ctx = reader->ctx;
563
703
  CURLcode result;
564
703
  char tmp[CURL_CHUNKED_MINLEN];
565
703
  size_t nread;
566
703
  bool eos;
567
568
703
  DEBUGASSERT(!ctx->read_eos);
569
703
  blen = CURLMIN(blen, CURL_CHUNKED_MAXLEN); /* respect our buffer pref */
570
703
  if(blen < sizeof(tmp)) {
571
    /* small read, make a chunk of decent size */
572
53
    buf = tmp;
573
53
    blen = sizeof(tmp);
574
53
  }
575
650
  else {
576
    /* larger read, make a chunk that will fit when read back */
577
650
    blen -= (8 + 2 + 2); /* deduct max overhead, 8 hex + 2*crlf */
578
650
  }
579
580
703
  result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos);
581
703
  if(result)
582
8
    return result;
583
695
  if(eos)
584
158
    ctx->read_eos = TRUE;
585
586
695
  if(nread) {
587
    /* actually got bytes, wrap them into the chunkbuf */
588
391
    char hd[11] = "";
589
391
    int hdlen;
590
391
    size_t n;
591
592
391
    hdlen = curl_msnprintf(hd, sizeof(hd), "%zx\r\n", nread);
593
391
    if(hdlen <= 0)
594
0
      return CURLE_READ_ERROR;
595
    /* On a soft-limited bufq, we do not need to check that all was written */
596
391
    result = Curl_bufq_cwrite(&ctx->chunkbuf, hd, hdlen, &n);
597
391
    if(!result)
598
391
      result = Curl_bufq_cwrite(&ctx->chunkbuf, buf, nread, &n);
599
391
    if(!result)
600
391
      result = Curl_bufq_cwrite(&ctx->chunkbuf, "\r\n", 2, &n);
601
391
    CURL_TRC_READ(data, "http_chunk, made chunk of %zu bytes -> %d",
602
391
                  nread, (int)result);
603
391
    if(result)
604
0
      return result;
605
391
  }
606
607
695
  if(ctx->read_eos)
608
158
    return add_last_chunk(data, reader);
609
537
  return CURLE_OK;
610
695
}
611
612
static CURLcode cr_chunked_read(struct Curl_easy *data,
613
                                struct Curl_creader *reader,
614
                                char *buf, size_t blen,
615
                                size_t *pnread, bool *peos)
616
721
{
617
721
  struct chunked_reader *ctx = reader->ctx;
618
721
  CURLcode result = CURLE_READ_ERROR;
619
620
721
  *pnread = 0;
621
721
  *peos = (bool)ctx->eos;
622
623
721
  if(!ctx->eos) {
624
721
    if(!ctx->read_eos && Curl_bufq_is_empty(&ctx->chunkbuf)) {
625
      /* Still getting data form the next reader, buffer is empty */
626
703
      result = add_chunk(data, reader, buf, blen);
627
703
      if(result)
628
8
        return result;
629
703
    }
630
631
713
    if(!Curl_bufq_is_empty(&ctx->chunkbuf)) {
632
437
      result = Curl_bufq_cread(&ctx->chunkbuf, buf, blen, pnread);
633
437
      if(!result && ctx->read_eos && Curl_bufq_is_empty(&ctx->chunkbuf)) {
634
        /* no more data, read all, done. */
635
140
        ctx->eos = TRUE;
636
140
        *peos = TRUE;
637
140
      }
638
437
      return result;
639
437
    }
640
713
  }
641
  /* We may get here, because we are done or because callbacks paused */
642
276
  DEBUGASSERT(ctx->eos || !ctx->read_eos);
643
276
  return CURLE_OK;
644
276
}
645
646
static curl_off_t cr_chunked_total_length(struct Curl_easy *data,
647
                                          struct Curl_creader *reader)
648
791
{
649
  /* this reader changes length depending on input */
650
791
  (void)data;
651
791
  (void)reader;
652
791
  return -1;
653
791
}
654
655
/* HTTP chunked Transfer-Encoding encoder */
656
const struct Curl_crtype Curl_httpchunk_encoder = {
657
  "chunked",
658
  cr_chunked_init,
659
  cr_chunked_read,
660
  cr_chunked_close,
661
  Curl_creader_def_needs_rewind,
662
  cr_chunked_total_length,
663
  Curl_creader_def_resume_from,
664
  Curl_creader_def_cntrl,
665
  Curl_creader_def_is_paused,
666
  Curl_creader_def_done,
667
  sizeof(struct chunked_reader)
668
};
669
670
CURLcode Curl_httpchunk_add_reader(struct Curl_easy *data)
671
362
{
672
362
  struct Curl_creader *reader = NULL;
673
362
  CURLcode result;
674
675
362
  result = Curl_creader_create(&reader, data, &Curl_httpchunk_encoder,
676
362
                               CURL_CR_TRANSFER_ENCODE);
677
362
  if(!result)
678
362
    result = Curl_creader_add(data, reader);
679
680
362
  if(result && reader)
681
0
    Curl_creader_free(data, reader);
682
362
  return result;
683
362
}
684
685
#endif /* CURL_DISABLE_HTTP */