Coverage Report

Created: 2026-10-22 06:56

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
266k
#define CONTENT_ENCODING_DEFAULT  "identity"
55
56
#ifndef CURL_DISABLE_HTTP
57
58
/* allow no more than 5 "chained" compression steps */
59
65.7k
#define MAX_ENCODE_STACK 5
60
61
#if defined(HAVE_LIBZ) || defined(HAVE_BROTLI) || defined(HAVE_ZSTD)
62
7.52M
#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
18.2k
{
90
18.2k
  (void)opaque;
91
  /* not a typo, keep it curlx_calloc() */
92
18.2k
  return curlx_calloc(items, size);
93
18.2k
}
94
95
static void zfree_cb(voidpf opaque, voidpf ptr)
96
18.2k
{
97
18.2k
  (void)opaque;
98
18.2k
  curlx_free(ptr);
99
18.2k
}
100
101
static CURLcode process_zlib_error(struct Curl_easy *data, z_stream *z)
102
2.81k
{
103
2.81k
  if(z->msg)
104
2.77k
    failf(data, "Error while processing content unencoding: %s", z->msg);
105
37
  else
106
37
    failf(data, "Error while processing content unencoding: "
107
37
          "Unknown failure within decompression software.");
108
109
2.81k
  return CURLE_BAD_CONTENT_ENCODING;
110
2.81k
}
111
112
static CURLcode exit_zlib(struct Curl_easy *data, z_stream *z,
113
                          zlibInitState *zlib_init, CURLcode result)
114
14.8k
{
115
14.8k
  if(*zlib_init != ZLIB_UNINIT) {
116
11.3k
    if(inflateEnd(z) != Z_OK && result == CURLE_OK)
117
0
      result = process_zlib_error(data, z);
118
11.3k
    *zlib_init = ZLIB_UNINIT;
119
11.3k
  }
120
121
14.8k
  return result;
122
14.8k
}
123
124
static CURLcode process_trailer(struct Curl_easy *data, struct zlib_writer *zp)
125
556
{
126
556
  z_stream *z = &zp->z;
127
556
  CURLcode result = CURLE_OK;
128
556
  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
556
  zp->trailerlen -= len;
134
556
  z->avail_in -= len;
135
556
  z->next_in += len;
136
556
  if(z->avail_in)
137
130
    result = CURLE_WRITE_ERROR;
138
556
  if(result || !zp->trailerlen)
139
231
    result = exit_zlib(data, z, &zp->zlib_init, result);
140
325
  else {
141
    /* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */
142
325
    zp->zlib_init = ZLIB_EXTERNAL_TRAILER;
143
325
  }
144
556
  return result;
145
556
}
146
147
static CURLcode inflate_stream(struct Curl_easy *data,
148
                               struct Curl_cwriter *writer, int type,
149
                               zlibInitState started)
150
229k
{
151
229k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
152
229k
  z_stream *z = &zp->z;         /* zlib state structure */
153
229k
  uInt nread = z->avail_in;
154
229k
  z_const Bytef *orig_in = z->next_in;
155
229k
  bool done = FALSE;
156
229k
  CURLcode result = CURLE_OK;   /* Curl_client_write status */
157
229k
  int i = 0;
158
159
  /* Check state. */
160
229k
  if(zp->zlib_init != ZLIB_INIT &&
161
224k
     zp->zlib_init != ZLIB_INFLATING &&
162
43.3k
     zp->zlib_init != ZLIB_INIT_GZIP)
163
13
    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
1.74M
  while(!done) {
168
1.51M
    int status; /* zlib status */
169
1.51M
    done = TRUE;
170
171
1.51M
    if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
172
      /* check every MB of output if we are not exceeding time limit */
173
11.3k
      i = 0;
174
11.3k
      if(Curl_timeleft_ms(data) < 0) {
175
2
        failf(data, "Operation timed out while decoding payload");
176
2
        return exit_zlib(data, z, &zp->zlib_init, CURLE_OPERATION_TIMEDOUT);
177
2
      }
178
11.3k
    }
179
180
    /* (re)set buffer for decompressed output for every iteration */
181
1.51M
    z->next_out = (Bytef *)zp->buffer;
182
1.51M
    z->avail_out = DECOMPRESS_BUFFER_SIZE;
183
184
1.51M
    status = inflate(z, Z_BLOCK);
185
186
    /* Flush output data if some. */
187
1.51M
    if(z->avail_out != DECOMPRESS_BUFFER_SIZE) {
188
1.23M
      if(status == Z_OK || status == Z_STREAM_END) {
189
1.23M
        zp->zlib_init = started; /* Data started. */
190
1.23M
        result = Curl_cwriter_write(data, writer->next, type, zp->buffer,
191
1.23M
                                    DECOMPRESS_BUFFER_SIZE - z->avail_out);
192
1.23M
        if(result) {
193
434
          exit_zlib(data, z, &zp->zlib_init, result);
194
434
          break;
195
434
        }
196
1.23M
      }
197
1.23M
    }
198
199
    /* Dispatch by inflate() status. */
200
1.51M
    switch(status) {
201
1.28M
    case Z_OK:
202
      /* Always loop: there may be unflushed latched data in zlib state. */
203
1.28M
      done = FALSE;
204
1.28M
      break;
205
226k
    case Z_BUF_ERROR:
206
      /* No more data to flush: exit loop. */
207
226k
      break;
208
387
    case Z_STREAM_END:
209
387
      if((started == ZLIB_INIT_GZIP) && (z->avail_in >= 2) &&
210
21
         (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
4
        failf(data, "Multi-member gzip response not supported");
214
4
        result = exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
215
4
        break;
216
4
      }
217
383
      result = process_trailer(data, zp);
218
383
      break;
219
6.71k
    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
6.71k
      if(zp->zlib_init == ZLIB_INIT) {
223
3.93k
        if(inflateReset2(z, -MAX_WBITS) == Z_OK) {
224
3.93k
          z->next_in = orig_in;
225
3.93k
          z->avail_in = nread;
226
3.93k
          zp->zlib_init = ZLIB_INFLATING;
227
3.93k
          zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */
228
3.93k
          done = FALSE;
229
3.93k
          break;
230
3.93k
        }
231
0
        zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */
232
0
      }
233
2.77k
      result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
234
2.77k
      break;
235
23
    default:
236
23
      result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
237
23
      break;
238
1.51M
    }
239
1.51M
  }
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
229k
  if(nread && zp->zlib_init == ZLIB_INIT)
245
112
    zp->zlib_init = started; /* Cannot restart anymore. */
246
247
229k
  return result;
248
229k
}
249
250
/* Deflate handler. */
251
static CURLcode deflate_do_init(struct Curl_easy *data,
252
                                struct Curl_cwriter *writer)
253
5.97k
{
254
5.97k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
255
5.97k
  z_stream *z = &zp->z; /* zlib state structure */
256
257
  /* Initialize zlib */
258
5.97k
  z->zalloc = (alloc_func)zalloc_cb;
259
5.97k
  z->zfree = (free_func)zfree_cb;
260
261
5.97k
  if(inflateInit(z) != Z_OK)
262
7
    return process_zlib_error(data, z);
263
5.96k
  zp->zlib_init = ZLIB_INIT;
264
5.96k
  return CURLE_OK;
265
5.97k
}
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
208k
{
271
208k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
272
208k
  z_stream *z = &zp->z; /* zlib state structure */
273
274
208k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
275
22.2k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
276
277
  /* Set the compressed input when this function is called */
278
186k
  z->next_in = (z_const Bytef *)buf;
279
186k
  z->avail_in = (uInt)nbytes;
280
281
186k
  if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER)
282
173
    return process_trailer(data, zp);
283
284
  /* Now uncompress the data */
285
186k
  return inflate_stream(data, writer, type, ZLIB_INFLATING);
286
186k
}
287
288
static void deflate_do_close(struct Curl_easy *data,
289
                             struct Curl_cwriter *writer)
290
5.96k
{
291
5.96k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
292
5.96k
  z_stream *z = &zp->z; /* zlib state structure */
293
294
5.96k
  exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
295
5.96k
}
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
5.36k
{
315
5.36k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
316
5.36k
  z_stream *z = &zp->z; /* zlib state structure */
317
318
  /* Initialize zlib */
319
5.36k
  z->zalloc = (alloc_func)zalloc_cb;
320
5.36k
  z->zfree = (free_func)zfree_cb;
321
322
5.36k
  if(inflateInit2(z, MAX_WBITS + 32) != Z_OK)
323
7
    return process_zlib_error(data, z);
324
325
5.35k
  zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
326
5.35k
  return CURLE_OK;
327
5.36k
}
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
62.7k
{
333
62.7k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
334
62.7k
  z_stream *z = &zp->z; /* zlib state structure */
335
336
62.7k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
337
19.4k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
338
339
43.3k
  if(zp->zlib_init == ZLIB_INIT_GZIP) {
340
    /* Let zlib handle the gzip decompression entirely */
341
43.2k
    z->next_in = (z_const Bytef *)buf;
342
43.2k
    z->avail_in = (uInt)nbytes;
343
    /* Now uncompress the data */
344
43.2k
    return inflate_stream(data, writer, type, ZLIB_INIT_GZIP);
345
43.2k
  }
346
347
  /* We are running with an old version: return error. */
348
16
  return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
349
43.3k
}
350
351
static void gzip_do_close(struct Curl_easy *data,
352
                          struct Curl_cwriter *writer)
353
5.35k
{
354
5.35k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
355
5.35k
  z_stream *z = &zp->z; /* zlib state structure */
356
357
5.35k
  exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
358
5.35k
}
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
7.65k
{
383
7.65k
  switch(be) {
384
79
  case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:
385
103
  case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:
386
257
  case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:
387
382
  case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:
388
1.44k
  case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:
389
2.85k
  case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:
390
3.03k
  case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:
391
4.09k
  case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:
392
5.46k
  case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:
393
6.20k
  case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:
394
6.96k
  case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:
395
6.97k
  case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:
396
7.18k
  case BROTLI_DECODER_ERROR_FORMAT_PADDING_1:
397
7.35k
  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
7.35k
  case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:
402
7.35k
  case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:
403
7.35k
    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
308
  default:
412
308
    break;
413
7.65k
  }
414
308
  return CURLE_WRITE_ERROR;
415
7.65k
}
416
417
static CURLcode brotli_do_init(struct Curl_easy *data,
418
                               struct Curl_cwriter *writer)
419
28.8k
{
420
28.8k
  struct brotli_writer *bp = (struct brotli_writer *)writer;
421
28.8k
  (void)data;
422
423
28.8k
  bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL);
424
28.8k
  return bp->br ? CURLE_OK : CURLE_OUT_OF_MEMORY;
425
28.8k
}
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
232k
{
431
232k
  struct brotli_writer *bp = (struct brotli_writer *)writer;
432
232k
  const uint8_t *src = (const uint8_t *)buf;
433
232k
  uint8_t *dst;
434
232k
  size_t dstleft;
435
232k
  CURLcode result = CURLE_OK;
436
232k
  BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
437
232k
  int i = 0;
438
439
232k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
440
87.9k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
441
442
144k
  if(!bp->br)
443
13
    return CURLE_WRITE_ERROR; /* Stream already ended. */
444
445
778k
  while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) &&
446
642k
        result == CURLE_OK) {
447
448
635k
    if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
449
      /* check every MB of output if we are not exceeding time limit */
450
6.22k
      i = 0;
451
6.22k
      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
6.22k
    }
456
457
635k
    dst = (uint8_t *)bp->buffer;
458
635k
    dstleft = DECOMPRESS_BUFFER_SIZE;
459
635k
    r = BrotliDecoderDecompressStream(bp->br,
460
635k
                                      &nbytes, &src, &dstleft, &dst, NULL);
461
635k
    result = Curl_cwriter_write(data, writer->next, type,
462
635k
                                bp->buffer, DECOMPRESS_BUFFER_SIZE - dstleft);
463
635k
    if(result)
464
1.28k
      break;
465
634k
    switch(r) {
466
491k
    case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
467
626k
    case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
468
626k
      break;
469
246
    case BROTLI_DECODER_RESULT_SUCCESS:
470
246
      BrotliDecoderDestroyInstance(bp->br);
471
246
      bp->br = NULL;
472
246
      if(nbytes)
473
194
        result = CURLE_WRITE_ERROR;
474
246
      break;
475
7.65k
    default:
476
7.65k
      result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br));
477
7.65k
      break;
478
634k
    }
479
634k
  }
480
144k
  return result;
481
144k
}
482
483
static void brotli_do_close(struct Curl_easy *data,
484
                            struct Curl_cwriter *writer)
485
28.8k
{
486
28.8k
  struct brotli_writer *bp = (struct brotli_writer *)writer;
487
28.8k
  (void)data;
488
489
28.8k
  if(bp->br) {
490
28.6k
    BrotliDecoderDestroyInstance(bp->br);
491
28.6k
    bp->br = NULL;
492
28.6k
  }
493
28.8k
}
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
11.4k
{
532
11.4k
  struct zstd_writer *zp = (struct zstd_writer *)writer;
533
534
11.4k
  (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
11.4k
  zp->zds = ZSTD_createDStream();
544
11.4k
#endif
545
546
11.4k
  return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY;
547
11.4k
}
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
84.6k
{
553
84.6k
  CURLcode result = CURLE_OK;
554
84.6k
  struct zstd_writer *zp = (struct zstd_writer *)writer;
555
84.6k
  ZSTD_inBuffer in;
556
84.6k
  ZSTD_outBuffer out;
557
84.6k
  size_t errorCode;
558
84.6k
  int i = 0;
559
560
84.6k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
561
27.7k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
562
563
56.8k
  in.pos = 0;
564
56.8k
  in.src = buf;
565
56.8k
  in.size = nbytes;
566
567
852k
  for(;;) {
568
852k
    if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
569
      /* check every MB of output if we are not exceeding time limit */
570
11.2k
      i = 0;
571
11.2k
      if(Curl_timeleft_ms(data) < 0) {
572
1
        failf(data, "Operation timed out while decoding payload");
573
1
        return CURLE_OPERATION_TIMEDOUT;
574
1
      }
575
11.2k
    }
576
577
852k
    out.pos = 0;
578
852k
    out.dst = zp->buffer;
579
852k
    out.size = DECOMPRESS_BUFFER_SIZE;
580
581
852k
    errorCode = ZSTD_decompressStream(zp->zds, &out, &in);
582
852k
    if(ZSTD_isError(errorCode)) {
583
9.01k
      return CURLE_BAD_CONTENT_ENCODING;
584
9.01k
    }
585
843k
    if(out.pos > 0) {
586
803k
      result = Curl_cwriter_write(data, writer->next, type,
587
803k
                                  zp->buffer, out.pos);
588
803k
      if(result)
589
60
        break;
590
803k
    }
591
843k
    if((in.pos == nbytes) && (out.pos < out.size))
592
47.7k
      break;
593
843k
  }
594
595
47.8k
  return result;
596
56.8k
}
597
598
static void zstd_do_close(struct Curl_easy *data,
599
                          struct Curl_cwriter *writer)
600
11.4k
{
601
11.4k
  struct zstd_writer *zp = (struct zstd_writer *)writer;
602
11.4k
  (void)data;
603
604
11.4k
  if(zp->zds) {
605
11.4k
    ZSTD_freeDStream(zp->zds);
606
11.4k
    zp->zds = NULL;
607
11.4k
  }
608
11.4k
}
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
53.3k
{
660
53.3k
  struct dynbuf enc;
661
53.3k
  const struct Curl_cwtype * const *cep;
662
53.3k
  CURLcode result = CURLE_OK;
663
53.3k
  curlx_dyn_init(&enc, 255);
664
665
319k
  for(cep = general_unencoders; *cep && !result; cep++) {
666
266k
    const struct Curl_cwtype *ce = *cep;
667
266k
    if(!curl_strequal(ce->name, CONTENT_ENCODING_DEFAULT)) {
668
213k
      if(curlx_dyn_len(&enc))
669
159k
        result = curlx_dyn_addn(&enc, ", ", 2);
670
213k
      if(!result)
671
213k
        result = curlx_dyn_add(&enc, ce->name);
672
213k
    }
673
266k
  }
674
53.3k
  if(!result && !curlx_dyn_len(&enc))
675
0
    result = curlx_dyn_add(&enc, CONTENT_ENCODING_DEFAULT);
676
677
53.3k
  if(!result)
678
53.2k
    return curlx_dyn_ptr(&enc);
679
132
  return NULL;
680
53.3k
}
681
682
/* Deferred error dummy writer. */
683
static CURLcode error_do_init(struct Curl_easy *data,
684
                              struct Curl_cwriter *writer)
685
5.47k
{
686
5.47k
  (void)data;
687
5.47k
  (void)writer;
688
5.47k
  return CURLE_OK;
689
5.47k
}
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
40.7k
{
695
40.7k
  (void)writer;
696
40.7k
  (void)buf;
697
40.7k
  (void)nbytes;
698
699
40.7k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
700
39.8k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
701
817
  failf(data, "Unrecognized content encoding type");
702
817
  return CURLE_BAD_CONTENT_ENCODING;
703
40.7k
}
704
705
static void error_do_close(struct Curl_easy *data,
706
                           struct Curl_cwriter *writer)
707
5.47k
{
708
5.47k
  (void)data;
709
5.47k
  (void)writer;
710
5.47k
}
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
65.5k
{
728
65.5k
  const struct Curl_cwtype * const *cep;
729
730
65.5k
  if(phase == CURL_CW_TRANSFER_DECODE) {
731
28.6k
    for(cep = transfer_unencoders; *cep; cep++) {
732
18.4k
      const struct Curl_cwtype *ce = *cep;
733
18.4k
      if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
734
10.1k
         (ce->alias && curl_strnequal(name, ce->alias, len) &&
735
0
          !ce->alias[len]))
736
8.25k
        return ce;
737
18.4k
    }
738
18.4k
  }
739
  /* look among the general decoders */
740
234k
  for(cep = general_unencoders; *cep; cep++) {
741
228k
    const struct Curl_cwtype *ce = *cep;
742
228k
    if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
743
176k
       (ce->alias && curl_strnequal(name, ce->alias, len) && !ce->alias[len]))
744
51.7k
      return ce;
745
228k
  }
746
5.51k
  return NULL;
747
57.2k
}
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
73.8k
{
754
73.8k
  Curl_cwriter_phase phase = is_transfer ?
755
54.5k
    CURL_CW_TRANSFER_DECODE : CURL_CW_CONTENT_DECODE;
756
73.8k
  CURLcode result;
757
73.8k
  bool has_chunked = FALSE;
758
759
93.9k
  do {
760
93.9k
    const char *name;
761
93.9k
    size_t namelen;
762
93.9k
    bool is_chunked = FALSE;
763
764
    /* Parse a single encoding name. */
765
210k
    while(ISBLANK(*enclist) || *enclist == ',')
766
116k
      enclist++;
767
768
93.9k
    name = enclist;
769
770
741k
    for(namelen = 0; *enclist && *enclist != ','; enclist++)
771
647k
      if(*enclist > ' ')
772
355k
        namelen = enclist - name + 1;
773
774
93.9k
    if(namelen) {
775
72.9k
      const struct Curl_cwtype *cwt;
776
72.9k
      struct Curl_cwriter *writer;
777
778
72.9k
      CURL_TRC_WRITE(data, "looking for %s decoder: %.*s",
779
72.9k
                     is_transfer ? "transfer" : "content", (int)namelen, name);
780
72.9k
      is_chunked = (is_transfer && (namelen == 7) &&
781
9.18k
                    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
72.9k
      if((is_transfer && !data->set.http_transfer_encoding && !is_chunked) ||
785
69.5k
         (!is_transfer && data->set.http_ce_skip)) {
786
7.29k
        bool is_identity = (namelen == 8) &&
787
2.95k
                           curl_strnequal(name, "identity", 8);
788
        /* not requested, ignore */
789
7.29k
        CURL_TRC_WRITE(data, "decoder not requested, ignored: %.*s",
790
7.29k
                       (int)namelen, name);
791
7.29k
        if(is_transfer && !data->set.http_te_skip) {
792
731
          if(has_chunked)
793
37
            failf(data, "A Transfer-Encoding (%.*s) was listed after chunked",
794
37
                  (int)namelen, name);
795
694
          else if(is_identity)
796
471
            continue;
797
223
          else
798
223
            failf(data, "Unsolicited Transfer-Encoding (%.*s) found",
799
223
                  (int)namelen, name);
800
260
          return CURLE_BAD_CONTENT_ENCODING;
801
731
        }
802
6.56k
        return CURLE_OK;
803
7.29k
      }
804
805
65.6k
      if(Curl_cwriter_count(data, phase) >= MAX_ENCODE_STACK) {
806
102
        failf(data, "Reject response exceeding limit of %d %s encodings",
807
102
              MAX_ENCODE_STACK,
808
102
              is_transfer ? "transfer" : "content");
809
102
        return CURLE_BAD_CONTENT_ENCODING;
810
102
      }
811
812
65.5k
      cwt = find_unencode_writer(name, namelen, phase);
813
65.5k
      if(is_transfer && !is_chunked &&
814
10.1k
         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
38
        failf(data, "Reject response due to 'chunked' not being the last "
824
38
              "Transfer-Encoding");
825
38
        return CURLE_BAD_CONTENT_ENCODING;
826
38
      }
827
65.4k
      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
4.74k
        CURL_TRC_WRITE(data, "ignoring duplicate 'chunked' decoder");
835
4.74k
      }
836
60.7k
      else {
837
60.7k
        if(!cwt)
838
5.47k
          cwt = &error_writer; /* Defer error at use. */
839
840
60.7k
        result = Curl_cwriter_create(&writer, data, cwt, phase);
841
60.7k
        CURL_TRC_WRITE(data, "added %s decoder %s -> %d",
842
60.7k
                       is_transfer ? "transfer" : "content", cwt->name,
843
60.7k
                       (int)result);
844
60.7k
        if(result)
845
24
          return result;
846
847
60.7k
        result = Curl_cwriter_add(data, writer);
848
60.7k
        if(result) {
849
21
          Curl_cwriter_free(data, writer);
850
21
          return result;
851
21
        }
852
60.7k
      }
853
65.4k
      if(is_chunked)
854
8.25k
        has_chunked = TRUE;
855
65.4k
    }
856
93.9k
  } while(*enclist);
857
858
66.8k
  return CURLE_OK;
859
73.8k
}
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 */