Coverage Report

Created: 2026-10-15 06:18

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