Coverage Report

Created: 2026-09-14 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/content_encoding.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 "urldata.h"
27
#include "curlx/dynbuf.h"
28
29
#ifdef HAVE_LIBZ
30
#include <zlib.h>
31
#endif
32
33
#ifdef HAVE_BROTLI
34
#ifdef CURL_HAVE_DIAG
35
/* Ignore -Wvla warnings in brotli headers */
36
#pragma GCC diagnostic push
37
#pragma GCC diagnostic ignored "-Wvla"
38
#endif
39
#include <brotli/decode.h>
40
#ifdef CURL_HAVE_DIAG
41
#pragma GCC diagnostic pop
42
#endif
43
#endif
44
45
#ifdef HAVE_ZSTD
46
#include <zstd.h>
47
#endif
48
49
#include "connect.h"
50
#include "sendf.h"
51
#include "curl_trc.h"
52
#include "content_encoding.h"
53
54
11.2k
#define CONTENT_ENCODING_DEFAULT  "identity"
55
56
#ifndef CURL_DISABLE_HTTP
57
58
/* allow no more than 5 "chained" compression steps */
59
5.13k
#define MAX_ENCODE_STACK 5
60
61
#if defined(HAVE_LIBZ) || defined(HAVE_BROTLI) || defined(HAVE_ZSTD)
62
938k
#define DECOMPRESS_BUFFER_SIZE 16384 /* buffer size for decompressed data */
63
#endif
64
65
#ifdef HAVE_LIBZ
66
67
#if !defined(ZLIB_VERNUM) || (ZLIB_VERNUM < 0x1252)
68
#error "zlib 1.2.5.2 or greater required"
69
#endif
70
71
typedef enum {
72
  ZLIB_UNINIT,               /* uninitialized */
73
  ZLIB_INIT,                 /* initialized */
74
  ZLIB_INFLATING,            /* inflating started. */
75
  ZLIB_EXTERNAL_TRAILER,     /* reading external trailer */
76
  ZLIB_INIT_GZIP             /* initialized in transparent gzip mode */
77
} zlibInitState;
78
79
/* Deflate and gzip writer. */
80
struct zlib_writer {
81
  struct Curl_cwriter super;
82
  zlibInitState zlib_init;   /* zlib init state */
83
  char buffer[DECOMPRESS_BUFFER_SIZE]; /* Put the decompressed data here. */
84
  uInt trailerlen;           /* Remaining trailer byte count. */
85
  z_stream z;                /* State structure for zlib. */
86
};
87
88
static voidpf zalloc_cb(voidpf opaque, unsigned int items, unsigned int size)
89
1.91k
{
90
1.91k
  (void)opaque;
91
  /* not a typo, keep it curlx_calloc() */
92
1.91k
  return curlx_calloc(items, size);
93
1.91k
}
94
95
static void zfree_cb(voidpf opaque, voidpf ptr)
96
1.91k
{
97
1.91k
  (void)opaque;
98
1.91k
  curlx_free(ptr);
99
1.91k
}
100
101
static CURLcode process_zlib_error(struct Curl_easy *data, z_stream *z)
102
280
{
103
280
  if(z->msg)
104
279
    failf(data, "Error while processing content unencoding: %s", z->msg);
105
1
  else
106
1
    failf(data, "Error while processing content unencoding: "
107
1
          "Unknown failure within decompression software.");
108
109
280
  return CURLE_BAD_CONTENT_ENCODING;
110
280
}
111
112
static CURLcode exit_zlib(struct Curl_easy *data, z_stream *z,
113
                          zlibInitState *zlib_init, CURLcode result)
114
1.62k
{
115
1.62k
  if(*zlib_init != ZLIB_UNINIT) {
116
1.15k
    if(inflateEnd(z) != Z_OK && result == CURLE_OK)
117
0
      result = process_zlib_error(data, z);
118
1.15k
    *zlib_init = ZLIB_UNINIT;
119
1.15k
  }
120
121
1.62k
  return result;
122
1.62k
}
123
124
static CURLcode process_trailer(struct Curl_easy *data, struct zlib_writer *zp)
125
72
{
126
72
  z_stream *z = &zp->z;
127
72
  CURLcode result = CURLE_OK;
128
72
  uInt len = z->avail_in < zp->trailerlen ? z->avail_in : zp->trailerlen;
129
130
  /* Consume expected trailer bytes. Terminate stream if exhausted.
131
     Issue an error if unexpected bytes follow. */
132
133
72
  zp->trailerlen -= len;
134
72
  z->avail_in -= len;
135
72
  z->next_in += len;
136
72
  if(z->avail_in)
137
21
    result = CURLE_WRITE_ERROR;
138
72
  if(result || !zp->trailerlen)
139
35
    result = exit_zlib(data, z, &zp->zlib_init, result);
140
37
  else {
141
    /* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */
142
37
    zp->zlib_init = ZLIB_EXTERNAL_TRAILER;
143
37
  }
144
72
  return result;
145
72
}
146
147
static CURLcode inflate_stream(struct Curl_easy *data,
148
                               struct Curl_cwriter *writer, int type,
149
                               zlibInitState started)
150
6.29k
{
151
6.29k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
152
6.29k
  z_stream *z = &zp->z;         /* zlib state structure */
153
6.29k
  uInt nread = z->avail_in;
154
6.29k
  z_const Bytef *orig_in = z->next_in;
155
6.29k
  bool done = FALSE;
156
6.29k
  CURLcode result = CURLE_OK;   /* Curl_client_write status */
157
6.29k
  int i = 0;
158
159
  /* Check state. */
160
6.29k
  if(zp->zlib_init != ZLIB_INIT &&
161
5.77k
     zp->zlib_init != ZLIB_INFLATING &&
162
1.06k
     zp->zlib_init != ZLIB_INIT_GZIP)
163
1
    return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
164
165
  /* because the buffer size is fixed, iteratively decompress and transfer to
166
     the client via next_write function. */
167
317k
  while(!done) {
168
311k
    int status; /* zlib status */
169
311k
    done = TRUE;
170
171
311k
    if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
172
      /* check every MB of output if we are not exceeding time limit */
173
4.37k
      i = 0;
174
4.37k
      if(Curl_timeleft_ms(data) < 0) {
175
0
        failf(data, "Operation timed out while decoding payload");
176
0
        return exit_zlib(data, z, &zp->zlib_init, CURLE_OPERATION_TIMEDOUT);
177
0
      }
178
4.37k
    }
179
180
    /* (re)set buffer for decompressed output for every iteration */
181
311k
    z->next_out = (Bytef *)zp->buffer;
182
311k
    z->avail_out = DECOMPRESS_BUFFER_SIZE;
183
184
311k
    status = inflate(z, Z_BLOCK);
185
186
    /* Flush output data if some. */
187
311k
    if(z->avail_out != DECOMPRESS_BUFFER_SIZE) {
188
302k
      if(status == Z_OK || status == Z_STREAM_END) {
189
302k
        zp->zlib_init = started; /* Data started. */
190
302k
        result = Curl_cwriter_write(data, writer->next, type, zp->buffer,
191
302k
                                    DECOMPRESS_BUFFER_SIZE - z->avail_out);
192
302k
        if(result) {
193
146
          exit_zlib(data, z, &zp->zlib_init, result);
194
146
          break;
195
146
        }
196
302k
      }
197
302k
    }
198
199
    /* Dispatch by inflate() status. */
200
311k
    switch(status) {
201
304k
    case Z_OK:
202
      /* Always loop: there may be unflushed latched data in zlib state. */
203
304k
      done = FALSE;
204
304k
      break;
205
5.80k
    case Z_BUF_ERROR:
206
      /* No more data to flush: exit loop. */
207
5.80k
      break;
208
63
    case Z_STREAM_END:
209
63
      if((started == ZLIB_INIT_GZIP) && (z->avail_in >= 2) &&
210
3
         (z->next_in[0] == 0x1f) && (z->next_in[1] == 0x8b)) {
211
        /* a second gzip member follows; curl does not support
212
           multi-member gzip responses */
213
1
        failf(data, "Multi-member gzip response not supported");
214
1
        result = exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
215
1
        break;
216
1
      }
217
62
      result = process_trailer(data, zp);
218
62
      break;
219
793
    case Z_DATA_ERROR:
220
      /* some servers seem to not generate zlib headers, so this is an attempt
221
         to fix and continue anyway */
222
793
      if(zp->zlib_init == ZLIB_INIT) {
223
514
        if(inflateReset2(z, -MAX_WBITS) == Z_OK) {
224
514
          z->next_in = orig_in;
225
514
          z->avail_in = nread;
226
514
          zp->zlib_init = ZLIB_INFLATING;
227
514
          zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */
228
514
          done = FALSE;
229
514
          break;
230
514
        }
231
0
        zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */
232
0
      }
233
279
      result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
234
279
      break;
235
1
    default:
236
1
      result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
237
1
      break;
238
311k
    }
239
311k
  }
240
241
  /* We are about to leave this call so the `nread' data bytes will not be seen
242
     again. If we are in a state that would wrongly allow restart in raw mode
243
     at the next call, assume output has already started. */
244
6.28k
  if(nread && zp->zlib_init == ZLIB_INIT)
245
6
    zp->zlib_init = started; /* Cannot restart anymore. */
246
247
6.28k
  return result;
248
6.28k
}
249
250
/* Deflate handler. */
251
static CURLcode deflate_do_init(struct Curl_easy *data,
252
                                struct Curl_cwriter *writer)
253
539
{
254
539
  struct zlib_writer *zp = (struct zlib_writer *)writer;
255
539
  z_stream *z = &zp->z; /* zlib state structure */
256
257
  /* Initialize zlib */
258
539
  z->zalloc = (alloc_func)zalloc_cb;
259
539
  z->zfree = (free_func)zfree_cb;
260
261
539
  if(inflateInit(z) != Z_OK)
262
0
    return process_zlib_error(data, z);
263
539
  zp->zlib_init = ZLIB_INIT;
264
539
  return CURLE_OK;
265
539
}
266
267
static CURLcode deflate_do_write(struct Curl_easy *data,
268
                                 struct Curl_cwriter *writer, int type,
269
                                 const char *buf, size_t nbytes)
270
6.80k
{
271
6.80k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
272
6.80k
  z_stream *z = &zp->z; /* zlib state structure */
273
274
6.80k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
275
1.57k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
276
277
  /* Set the compressed input when this function is called */
278
5.23k
  z->next_in = (z_const Bytef *)buf;
279
5.23k
  z->avail_in = (uInt)nbytes;
280
281
5.23k
  if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER)
282
10
    return process_trailer(data, zp);
283
284
  /* Now uncompress the data */
285
5.22k
  return inflate_stream(data, writer, type, ZLIB_INFLATING);
286
5.23k
}
287
288
static void deflate_do_close(struct Curl_easy *data,
289
                             struct Curl_cwriter *writer)
290
539
{
291
539
  struct zlib_writer *zp = (struct zlib_writer *)writer;
292
539
  z_stream *z = &zp->z; /* zlib state structure */
293
294
539
  exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
295
539
}
296
297
static const struct Curl_cwtype deflate_encoding = {
298
  "deflate",
299
  NULL,
300
  CURL_CW_FLAG_BLOWUP,
301
  deflate_do_init,
302
  deflate_do_write,
303
  Curl_cwriter_def_flush,
304
  deflate_do_close,
305
  sizeof(struct zlib_writer)
306
};
307
308
/*
309
 * Gzip handler.
310
 */
311
312
static CURLcode gzip_do_init(struct Curl_easy *data,
313
                             struct Curl_cwriter *writer)
314
619
{
315
619
  struct zlib_writer *zp = (struct zlib_writer *)writer;
316
619
  z_stream *z = &zp->z; /* zlib state structure */
317
318
  /* Initialize zlib */
319
619
  z->zalloc = (alloc_func)zalloc_cb;
320
619
  z->zfree = (free_func)zfree_cb;
321
322
619
  if(inflateInit2(z, MAX_WBITS + 32) != Z_OK)
323
0
    return process_zlib_error(data, z);
324
325
619
  zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
326
619
  return CURLE_OK;
327
619
}
328
329
static CURLcode gzip_do_write(struct Curl_easy *data,
330
                              struct Curl_cwriter *writer, int type,
331
                              const char *buf, size_t nbytes)
332
4.23k
{
333
4.23k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
334
4.23k
  z_stream *z = &zp->z; /* zlib state structure */
335
336
4.23k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
337
3.17k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
338
339
1.06k
  if(zp->zlib_init == ZLIB_INIT_GZIP) {
340
    /* Let zlib handle the gzip decompression entirely */
341
1.06k
    z->next_in = (z_const Bytef *)buf;
342
1.06k
    z->avail_in = (uInt)nbytes;
343
    /* Now uncompress the data */
344
1.06k
    return inflate_stream(data, writer, type, ZLIB_INIT_GZIP);
345
1.06k
  }
346
347
  /* We are running with an old version: return error. */
348
1
  return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
349
1.06k
}
350
351
static void gzip_do_close(struct Curl_easy *data,
352
                          struct Curl_cwriter *writer)
353
619
{
354
619
  struct zlib_writer *zp = (struct zlib_writer *)writer;
355
619
  z_stream *z = &zp->z; /* zlib state structure */
356
357
619
  exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
358
619
}
359
360
static const struct Curl_cwtype gzip_encoding = {
361
  "gzip",
362
  "x-gzip",
363
  CURL_CW_FLAG_BLOWUP,
364
  gzip_do_init,
365
  gzip_do_write,
366
  Curl_cwriter_def_flush,
367
  gzip_do_close,
368
  sizeof(struct zlib_writer)
369
};
370
371
#endif /* HAVE_LIBZ */
372
373
#ifdef HAVE_BROTLI
374
/* Brotli writer. */
375
struct brotli_writer {
376
  struct Curl_cwriter super;
377
  char buffer[DECOMPRESS_BUFFER_SIZE];
378
  BrotliDecoderState *br; /* State structure for brotli. */
379
};
380
381
static CURLcode brotli_map_error(BrotliDecoderErrorCode be)
382
470
{
383
470
  switch(be) {
384
2
  case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:
385
3
  case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:
386
12
  case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:
387
20
  case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:
388
97
  case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:
389
209
  case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:
390
218
  case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:
391
264
  case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:
392
327
  case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:
393
397
  case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:
394
428
  case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:
395
429
  case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:
396
438
  case BROTLI_DECODER_ERROR_FORMAT_PADDING_1:
397
441
  case BROTLI_DECODER_ERROR_FORMAT_PADDING_2:
398
#ifdef BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY  /* brotli v1.1.0+ */
399
  case BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY:
400
#endif
401
441
  case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:
402
441
  case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:
403
441
    return CURLE_BAD_CONTENT_ENCODING;
404
0
  case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:
405
0
  case BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:
406
0
  case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:
407
0
  case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:
408
0
  case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:
409
0
  case BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:
410
0
    return CURLE_OUT_OF_MEMORY;
411
29
  default:
412
29
    break;
413
470
  }
414
29
  return CURLE_WRITE_ERROR;
415
470
}
416
417
static CURLcode brotli_do_init(struct Curl_easy *data,
418
                               struct Curl_cwriter *writer)
419
1.41k
{
420
1.41k
  struct brotli_writer *bp = (struct brotli_writer *)writer;
421
1.41k
  (void)data;
422
423
1.41k
  bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL);
424
1.41k
  return bp->br ? CURLE_OK : CURLE_OUT_OF_MEMORY;
425
1.41k
}
426
427
static CURLcode brotli_do_write(struct Curl_easy *data,
428
                                struct Curl_cwriter *writer, int type,
429
                                const char *buf, size_t nbytes)
430
5.64k
{
431
5.64k
  struct brotli_writer *bp = (struct brotli_writer *)writer;
432
5.64k
  const uint8_t *src = (const uint8_t *)buf;
433
5.64k
  uint8_t *dst;
434
5.64k
  size_t dstleft;
435
5.64k
  CURLcode result = CURLE_OK;
436
5.64k
  BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
437
5.64k
  int i = 0;
438
439
5.64k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
440
3.41k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
441
442
2.23k
  if(!bp->br)
443
1
    return CURLE_WRITE_ERROR; /* Stream already ended. */
444
445
4.42k
  while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) &&
446
3.12k
        result == CURLE_OK) {
447
448
2.67k
    if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
449
      /* check every MB of output if we are not exceeding time limit */
450
5
      i = 0;
451
5
      if(Curl_timeleft_ms(data) < 0) {
452
0
        failf(data, "Operation timed out while decoding payload");
453
0
        return CURLE_OPERATION_TIMEDOUT;
454
0
      }
455
5
    }
456
457
2.67k
    dst = (uint8_t *)bp->buffer;
458
2.67k
    dstleft = DECOMPRESS_BUFFER_SIZE;
459
2.67k
    r = BrotliDecoderDecompressStream(bp->br,
460
2.67k
                                      &nbytes, &src, &dstleft, &dst, NULL);
461
2.67k
    result = Curl_cwriter_write(data, writer->next, type,
462
2.67k
                                bp->buffer, DECOMPRESS_BUFFER_SIZE - dstleft);
463
2.67k
    if(result)
464
483
      break;
465
2.18k
    switch(r) {
466
441
    case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
467
1.71k
    case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
468
1.71k
      break;
469
8
    case BROTLI_DECODER_RESULT_SUCCESS:
470
8
      BrotliDecoderDestroyInstance(bp->br);
471
8
      bp->br = NULL;
472
8
      if(nbytes)
473
5
        result = CURLE_WRITE_ERROR;
474
8
      break;
475
470
    default:
476
470
      result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br));
477
470
      break;
478
2.18k
    }
479
2.18k
  }
480
2.23k
  return result;
481
2.23k
}
482
483
static void brotli_do_close(struct Curl_easy *data,
484
                            struct Curl_cwriter *writer)
485
1.41k
{
486
1.41k
  struct brotli_writer *bp = (struct brotli_writer *)writer;
487
1.41k
  (void)data;
488
489
1.41k
  if(bp->br) {
490
1.40k
    BrotliDecoderDestroyInstance(bp->br);
491
1.40k
    bp->br = NULL;
492
1.40k
  }
493
1.41k
}
494
495
static const struct Curl_cwtype brotli_encoding = {
496
  "br",
497
  NULL,
498
  CURL_CW_FLAG_BLOWUP,
499
  brotli_do_init,
500
  brotli_do_write,
501
  Curl_cwriter_def_flush,
502
  brotli_do_close,
503
  sizeof(struct brotli_writer)
504
};
505
#endif
506
507
#ifdef HAVE_ZSTD
508
/* Zstd writer. */
509
struct zstd_writer {
510
  struct Curl_cwriter super;
511
  ZSTD_DStream *zds; /* State structure for zstd. */
512
  char buffer[DECOMPRESS_BUFFER_SIZE];
513
};
514
515
#ifdef ZSTD_STATIC_LINKING_ONLY
516
static void *Curl_zstd_alloc(void *opaque, size_t size)
517
{
518
  (void)opaque;
519
  return Curl_cmalloc(size);
520
}
521
522
static void Curl_zstd_free(void *opaque, void *address)
523
{
524
  (void)opaque;
525
  Curl_cfree(address);
526
}
527
#endif
528
529
static CURLcode zstd_do_init(struct Curl_easy *data,
530
                             struct Curl_cwriter *writer)
531
0
{
532
0
  struct zstd_writer *zp = (struct zstd_writer *)writer;
533
534
0
  (void)data;
535
536
#ifdef ZSTD_STATIC_LINKING_ONLY
537
  zp->zds = ZSTD_createDStream_advanced((ZSTD_customMem) {
538
    .customAlloc = Curl_zstd_alloc,
539
    .customFree  = Curl_zstd_free,
540
    .opaque      = NULL
541
  });
542
#else
543
0
  zp->zds = ZSTD_createDStream();
544
0
#endif
545
546
0
  return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY;
547
0
}
548
549
static CURLcode zstd_do_write(struct Curl_easy *data,
550
                              struct Curl_cwriter *writer, int type,
551
                              const char *buf, size_t nbytes)
552
0
{
553
0
  CURLcode result = CURLE_OK;
554
0
  struct zstd_writer *zp = (struct zstd_writer *)writer;
555
0
  ZSTD_inBuffer in;
556
0
  ZSTD_outBuffer out;
557
0
  size_t errorCode;
558
0
  int i = 0;
559
560
0
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
561
0
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
562
563
0
  in.pos = 0;
564
0
  in.src = buf;
565
0
  in.size = nbytes;
566
567
0
  for(;;) {
568
0
    if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
569
      /* check every MB of output if we are not exceeding time limit */
570
0
      i = 0;
571
0
      if(Curl_timeleft_ms(data) < 0) {
572
0
        failf(data, "Operation timed out while decoding payload");
573
0
        return CURLE_OPERATION_TIMEDOUT;
574
0
      }
575
0
    }
576
577
0
    out.pos = 0;
578
0
    out.dst = zp->buffer;
579
0
    out.size = DECOMPRESS_BUFFER_SIZE;
580
581
0
    errorCode = ZSTD_decompressStream(zp->zds, &out, &in);
582
0
    if(ZSTD_isError(errorCode)) {
583
0
      return CURLE_BAD_CONTENT_ENCODING;
584
0
    }
585
0
    if(out.pos > 0) {
586
0
      result = Curl_cwriter_write(data, writer->next, type,
587
0
                                  zp->buffer, out.pos);
588
0
      if(result)
589
0
        break;
590
0
    }
591
0
    if((in.pos == nbytes) && (out.pos < out.size))
592
0
      break;
593
0
  }
594
595
0
  return result;
596
0
}
597
598
static void zstd_do_close(struct Curl_easy *data,
599
                          struct Curl_cwriter *writer)
600
0
{
601
0
  struct zstd_writer *zp = (struct zstd_writer *)writer;
602
0
  (void)data;
603
604
0
  if(zp->zds) {
605
0
    ZSTD_freeDStream(zp->zds);
606
0
    zp->zds = NULL;
607
0
  }
608
0
}
609
610
static const struct Curl_cwtype zstd_encoding = {
611
  "zstd",
612
  NULL,
613
  CURL_CW_FLAG_BLOWUP,
614
  zstd_do_init,
615
  zstd_do_write,
616
  Curl_cwriter_def_flush,
617
  zstd_do_close,
618
  sizeof(struct zstd_writer)
619
};
620
#endif
621
622
/* Identity handler. */
623
static const struct Curl_cwtype identity_encoding = {
624
  "identity",
625
  "none",
626
  0,
627
  Curl_cwriter_def_init,
628
  Curl_cwriter_def_write,
629
  Curl_cwriter_def_flush,
630
  Curl_cwriter_def_close,
631
  sizeof(struct Curl_cwriter)
632
};
633
634
/* supported general content decoders. */
635
static const struct Curl_cwtype * const general_unencoders[] = {
636
  &identity_encoding,
637
#ifdef HAVE_LIBZ
638
  &deflate_encoding,
639
  &gzip_encoding,
640
#endif
641
#ifdef HAVE_BROTLI
642
  &brotli_encoding,
643
#endif
644
#ifdef HAVE_ZSTD
645
  &zstd_encoding,
646
#endif
647
  NULL
648
};
649
650
/* supported content decoders only for transfer encodings */
651
static const struct Curl_cwtype * const transfer_unencoders[] = {
652
  &Curl_httpchunk_unencoder,
653
  NULL
654
};
655
656
/* Return the list of comma-separated names of supported encodings.
657
 */
658
char *Curl_get_content_encodings(void)
659
2.24k
{
660
2.24k
  struct dynbuf enc;
661
2.24k
  const struct Curl_cwtype * const *cep;
662
2.24k
  CURLcode result = CURLE_OK;
663
2.24k
  curlx_dyn_init(&enc, 255);
664
665
13.4k
  for(cep = general_unencoders; *cep && !result; cep++) {
666
11.2k
    const struct Curl_cwtype *ce = *cep;
667
11.2k
    if(!curl_strequal(ce->name, CONTENT_ENCODING_DEFAULT)) {
668
8.99k
      if(curlx_dyn_len(&enc))
669
6.74k
        result = curlx_dyn_addn(&enc, ", ", 2);
670
8.99k
      if(!result)
671
8.99k
        result = curlx_dyn_add(&enc, ce->name);
672
8.99k
    }
673
11.2k
  }
674
2.24k
  if(!result && !curlx_dyn_len(&enc))
675
0
    result = curlx_dyn_add(&enc, CONTENT_ENCODING_DEFAULT);
676
677
2.24k
  if(!result)
678
2.24k
    return curlx_dyn_ptr(&enc);
679
0
  return NULL;
680
2.24k
}
681
682
/* Deferred error dummy writer. */
683
static CURLcode error_do_init(struct Curl_easy *data,
684
                              struct Curl_cwriter *writer)
685
1.43k
{
686
1.43k
  (void)data;
687
1.43k
  (void)writer;
688
1.43k
  return CURLE_OK;
689
1.43k
}
690
691
static CURLcode error_do_write(struct Curl_easy *data,
692
                               struct Curl_cwriter *writer, int type,
693
                               const char *buf, size_t nbytes)
694
7.85k
{
695
7.85k
  (void)writer;
696
7.85k
  (void)buf;
697
7.85k
  (void)nbytes;
698
699
7.85k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
700
7.35k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
701
505
  failf(data, "Unrecognized content encoding type");
702
505
  return CURLE_BAD_CONTENT_ENCODING;
703
7.85k
}
704
705
static void error_do_close(struct Curl_easy *data,
706
                           struct Curl_cwriter *writer)
707
1.43k
{
708
1.43k
  (void)data;
709
1.43k
  (void)writer;
710
1.43k
}
711
712
static const struct Curl_cwtype error_writer = {
713
  "ce-error",
714
  NULL,
715
  0,
716
  error_do_init,
717
  error_do_write,
718
  Curl_cwriter_def_flush,
719
  error_do_close,
720
  sizeof(struct Curl_cwriter)
721
};
722
723
/* Find the content encoding by name. */
724
static const struct Curl_cwtype *find_unencode_writer(const char *name,
725
                                                      size_t len,
726
                                                      Curl_cwriter_phase phase)
727
5.12k
{
728
5.12k
  const struct Curl_cwtype * const *cep;
729
730
5.12k
  if(phase == CURL_CW_TRANSFER_DECODE) {
731
1.25k
    for(cep = transfer_unencoders; *cep; cep++) {
732
1.17k
      const struct Curl_cwtype *ce = *cep;
733
1.17k
      if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
734
75
         (ce->alias && curl_strnequal(name, ce->alias, len) &&
735
0
          !ce->alias[len]))
736
1.10k
        return ce;
737
1.17k
    }
738
1.17k
  }
739
  /* look among the general decoders */
740
17.2k
  for(cep = general_unencoders; *cep; cep++) {
741
15.7k
    const struct Curl_cwtype *ce = *cep;
742
15.7k
    if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
743
13.1k
       (ce->alias && curl_strnequal(name, ce->alias, len) && !ce->alias[len]))
744
2.59k
      return ce;
745
15.7k
  }
746
1.43k
  return NULL;
747
4.02k
}
748
749
/* Setup the unencoding stack from the Content-Encoding header value.
750
 * See RFC 7231 section 3.1.2.2. */
751
CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
752
                                     const char *enclist, int is_transfer)
753
4.10k
{
754
4.10k
  Curl_cwriter_phase phase = is_transfer ?
755
2.65k
    CURL_CW_TRANSFER_DECODE : CURL_CW_CONTENT_DECODE;
756
4.10k
  CURLcode result;
757
4.10k
  bool has_chunked = FALSE;
758
759
6.45k
  do {
760
6.45k
    const char *name;
761
6.45k
    size_t namelen;
762
6.45k
    bool is_chunked = FALSE;
763
764
    /* Parse a single encoding name. */
765
11.8k
    while(ISBLANK(*enclist) || *enclist == ',')
766
5.41k
      enclist++;
767
768
6.45k
    name = enclist;
769
770
38.7k
    for(namelen = 0; *enclist && *enclist != ','; enclist++)
771
32.3k
      if(*enclist > ' ')
772
22.8k
        namelen = enclist - name + 1;
773
774
6.45k
    if(namelen) {
775
5.35k
      const struct Curl_cwtype *cwt;
776
5.35k
      struct Curl_cwriter *writer;
777
778
5.35k
      CURL_TRC_WRITE(data, "looking for %s decoder: %.*s",
779
5.35k
                     is_transfer ? "transfer" : "content", (int)namelen, name);
780
5.35k
      is_chunked = (is_transfer && (namelen == 7) &&
781
1.14k
                    curl_strnequal(name, "chunked", 7));
782
      /* if we skip the decoding in this phase, do not look further.
783
       * Exception is "chunked" transfer-encoding which always must happen */
784
5.35k
      if((is_transfer && !data->set.http_transfer_encoding && !is_chunked) ||
785
5.18k
         (!is_transfer && data->set.http_ce_skip)) {
786
226
        bool is_identity = (namelen == 8) &&
787
80
                           curl_strnequal(name, "identity", 8);
788
        /* not requested, ignore */
789
226
        CURL_TRC_WRITE(data, "decoder not requested, ignored: %.*s",
790
226
                       (int)namelen, name);
791
226
        if(is_transfer && !data->set.http_te_skip) {
792
94
          if(has_chunked)
793
3
            failf(data, "A Transfer-Encoding (%.*s) was listed after chunked",
794
3
                  (int)namelen, name);
795
91
          else if(is_identity)
796
70
            continue;
797
21
          else
798
21
            failf(data, "Unsolicited Transfer-Encoding (%.*s) found",
799
21
                  (int)namelen, name);
800
24
          return CURLE_BAD_CONTENT_ENCODING;
801
94
        }
802
132
        return CURLE_OK;
803
226
      }
804
805
5.12k
      if(Curl_cwriter_count(data, phase) >= MAX_ENCODE_STACK) {
806
3
        failf(data, "Reject response exceeding limit of %d %s encodings",
807
3
              MAX_ENCODE_STACK,
808
3
              is_transfer ? "transfer" : "content");
809
3
        return CURLE_BAD_CONTENT_ENCODING;
810
3
      }
811
812
5.12k
      cwt = find_unencode_writer(name, namelen, phase);
813
5.12k
      if(is_transfer && !is_chunked &&
814
75
         Curl_cwriter_get_by_name(data, "chunked")) {
815
        /* RFC 9112, ch. 6.1:
816
         * "If any transfer coding other than chunked is applied to a
817
         *  response's content, the sender MUST either apply chunked as the
818
         *  final transfer coding or terminate the message by closing the
819
         *  connection."
820
         * "chunked" must be the last added to be the first in its phase,
821
         *  reject this.
822
         */
823
3
        failf(data, "Reject response due to 'chunked' not being the last "
824
3
              "Transfer-Encoding");
825
3
        return CURLE_BAD_CONTENT_ENCODING;
826
3
      }
827
5.12k
      if(cwt && is_chunked && Curl_cwriter_get_by_type(data, cwt)) {
828
        /* A 'chunked' transfer encoding has already been added.
829
         * Ignore duplicates. See #13451.
830
         * Also RFC 9112, ch. 6.1:
831
         * "A sender MUST NOT apply the chunked transfer coding more than
832
         *  once to a message body."
833
         */
834
842
        CURL_TRC_WRITE(data, "ignoring duplicate 'chunked' decoder");
835
842
      }
836
4.28k
      else {
837
4.28k
        if(!cwt)
838
1.43k
          cwt = &error_writer; /* Defer error at use. */
839
840
4.28k
        result = Curl_cwriter_create(&writer, data, cwt, phase);
841
4.28k
        CURL_TRC_WRITE(data, "added %s decoder %s -> %d",
842
4.28k
                       is_transfer ? "transfer" : "content", cwt->name,
843
4.28k
                       (int)result);
844
4.28k
        if(result)
845
0
          return result;
846
847
4.28k
        result = Curl_cwriter_add(data, writer);
848
4.28k
        if(result) {
849
0
          Curl_cwriter_free(data, writer);
850
0
          return result;
851
0
        }
852
4.28k
      }
853
5.12k
      if(is_chunked)
854
1.10k
        has_chunked = TRUE;
855
5.12k
    }
856
6.45k
  } while(*enclist);
857
858
3.94k
  return CURLE_OK;
859
4.10k
}
860
861
#else
862
/* Stubs for builds without HTTP. */
863
CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
864
                                     const char *enclist, int is_transfer)
865
{
866
  (void)data;
867
  (void)enclist;
868
  (void)is_transfer;
869
  return CURLE_NOT_BUILT_IN;
870
}
871
872
char *Curl_get_content_encodings(void)
873
{
874
  return curlx_strdup(CONTENT_ENCODING_DEFAULT);
875
}
876
877
#endif /* CURL_DISABLE_HTTP */