Coverage Report

Created: 2026-08-11 08:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/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
0
#define CONTENT_ENCODING_DEFAULT  "identity"
55
56
#ifndef CURL_DISABLE_HTTP
57
58
/* allow no more than 5 "chained" compression steps */
59
626
#define MAX_ENCODE_STACK 5
60
61
#if defined(HAVE_LIBZ) || defined(HAVE_BROTLI) || defined(HAVE_ZSTD)
62
10.4k
#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 "requires zlib 1.2.5.2 or newer"
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
944
{
90
944
  (void)opaque;
91
  /* not a typo, keep it curlx_calloc() */
92
944
  return curlx_calloc(items, size);
93
944
}
94
95
static void zfree_cb(voidpf opaque, voidpf ptr)
96
944
{
97
944
  (void)opaque;
98
944
  curlx_free(ptr);
99
944
}
100
101
static CURLcode process_zlib_error(struct Curl_easy *data, z_stream *z)
102
0
{
103
0
  if(z->msg)
104
0
    failf(data, "Error while processing content unencoding: %s", z->msg);
105
0
  else
106
0
    failf(data, "Error while processing content unencoding: "
107
0
          "Unknown failure within decompression software.");
108
109
0
  return CURLE_BAD_CONTENT_ENCODING;
110
0
}
111
112
static CURLcode exit_zlib(struct Curl_easy *data, z_stream *z,
113
                          zlibInitState *zlib_init, CURLcode result)
114
944
{
115
944
  if(*zlib_init != ZLIB_UNINIT) {
116
472
    if(inflateEnd(z) != Z_OK && result == CURLE_OK)
117
0
      result = process_zlib_error(data, z);
118
472
    *zlib_init = ZLIB_UNINIT;
119
472
  }
120
121
944
  return result;
122
944
}
123
124
static CURLcode process_trailer(struct Curl_easy *data, struct zlib_writer *zp)
125
468
{
126
468
  z_stream *z = &zp->z;
127
468
  CURLcode result = CURLE_OK;
128
468
  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
468
  zp->trailerlen -= len;
134
468
  z->avail_in -= len;
135
468
  z->next_in += len;
136
468
  if(z->avail_in)
137
0
    result = CURLE_WRITE_ERROR;
138
468
  if(result || !zp->trailerlen)
139
468
    result = exit_zlib(data, z, &zp->zlib_init, result);
140
0
  else {
141
    /* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */
142
0
    zp->zlib_init = ZLIB_EXTERNAL_TRAILER;
143
0
  }
144
468
  return result;
145
468
}
146
147
static CURLcode inflate_stream(struct Curl_easy *data,
148
                               struct Curl_cwriter *writer, int type,
149
                               zlibInitState started)
150
1.52k
{
151
1.52k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
152
1.52k
  z_stream *z = &zp->z;         /* zlib state structure */
153
1.52k
  uInt nread = z->avail_in;
154
1.52k
  z_const Bytef *orig_in = z->next_in;
155
1.52k
  bool done = FALSE;
156
1.52k
  CURLcode result = CURLE_OK;   /* Curl_client_write status */
157
1.52k
  int i = 0;
158
159
  /* Check state. */
160
1.52k
  if(zp->zlib_init != ZLIB_INIT &&
161
1.52k
     zp->zlib_init != ZLIB_INFLATING &&
162
1.52k
     zp->zlib_init != ZLIB_INIT_GZIP)
163
0
    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
5.01k
  while(!done) {
168
3.49k
    int status; /* zlib status */
169
3.49k
    done = TRUE;
170
171
3.49k
    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
3.49k
    z->next_out = (Bytef *)zp->buffer;
182
3.49k
    z->avail_out = DECOMPRESS_BUFFER_SIZE;
183
184
3.49k
    status = inflate(z, Z_BLOCK);
185
186
    /* Flush output data if some. */
187
3.49k
    if(z->avail_out != DECOMPRESS_BUFFER_SIZE) {
188
811
      if(status == Z_OK || status == Z_STREAM_END) {
189
811
        zp->zlib_init = started; /* Data started. */
190
811
        result = Curl_cwriter_write(data, writer->next, type, zp->buffer,
191
811
                                    DECOMPRESS_BUFFER_SIZE - z->avail_out);
192
811
        if(result) {
193
4
          exit_zlib(data, z, &zp->zlib_init, result);
194
4
          break;
195
4
        }
196
811
      }
197
811
    }
198
199
    /* Dispatch by inflate() status. */
200
3.48k
    switch(status) {
201
1.96k
    case Z_OK:
202
      /* Always loop: there may be unflushed latched data in zlib state. */
203
1.96k
      done = FALSE;
204
1.96k
      break;
205
1.05k
    case Z_BUF_ERROR:
206
      /* No more data to flush: exit loop. */
207
1.05k
      break;
208
468
    case Z_STREAM_END:
209
468
      if((started == ZLIB_INIT_GZIP) && (z->avail_in >= 2) &&
210
0
         (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
468
      result = process_trailer(data, zp);
218
468
      break;
219
0
    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
0
      if(zp->zlib_init == ZLIB_INIT) {
223
0
        if(inflateReset2(z, -MAX_WBITS) == Z_OK) {
224
0
          z->next_in = orig_in;
225
0
          z->avail_in = nread;
226
0
          zp->zlib_init = ZLIB_INFLATING;
227
0
          zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */
228
0
          done = FALSE;
229
0
          break;
230
0
        }
231
0
        zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */
232
0
      }
233
0
      result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
234
0
      break;
235
0
    default:
236
0
      result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
237
0
      break;
238
3.48k
    }
239
3.48k
  }
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
1.52k
  if(nread && zp->zlib_init == ZLIB_INIT)
245
0
    zp->zlib_init = started; /* Cannot restart anymore. */
246
247
1.52k
  return result;
248
1.52k
}
249
250
/* Deflate handler. */
251
static CURLcode deflate_do_init(struct Curl_easy *data,
252
                                struct Curl_cwriter *writer)
253
0
{
254
0
  struct zlib_writer *zp = (struct zlib_writer *)writer;
255
0
  z_stream *z = &zp->z; /* zlib state structure */
256
257
  /* Initialize zlib */
258
0
  z->zalloc = (alloc_func)zalloc_cb;
259
0
  z->zfree = (free_func)zfree_cb;
260
261
0
  if(inflateInit(z) != Z_OK)
262
0
    return process_zlib_error(data, z);
263
0
  zp->zlib_init = ZLIB_INIT;
264
0
  return CURLE_OK;
265
0
}
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
0
{
271
0
  struct zlib_writer *zp = (struct zlib_writer *)writer;
272
0
  z_stream *z = &zp->z; /* zlib state structure */
273
274
0
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
275
0
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
276
277
  /* Set the compressed input when this function is called */
278
0
  z->next_in = (z_const Bytef *)buf;
279
0
  z->avail_in = (uInt)nbytes;
280
281
0
  if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER)
282
0
    return process_trailer(data, zp);
283
284
  /* Now uncompress the data */
285
0
  return inflate_stream(data, writer, type, ZLIB_INFLATING);
286
0
}
287
288
static void deflate_do_close(struct Curl_easy *data,
289
                             struct Curl_cwriter *writer)
290
0
{
291
0
  struct zlib_writer *zp = (struct zlib_writer *)writer;
292
0
  z_stream *z = &zp->z; /* zlib state structure */
293
294
0
  exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
295
0
}
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
472
{
315
472
  struct zlib_writer *zp = (struct zlib_writer *)writer;
316
472
  z_stream *z = &zp->z; /* zlib state structure */
317
318
  /* Initialize zlib */
319
472
  z->zalloc = (alloc_func)zalloc_cb;
320
472
  z->zfree = (free_func)zfree_cb;
321
322
472
  if(inflateInit2(z, MAX_WBITS + 32) != Z_OK)
323
0
    return process_zlib_error(data, z);
324
325
472
  zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
326
472
  return CURLE_OK;
327
472
}
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.35k
{
333
4.35k
  struct zlib_writer *zp = (struct zlib_writer *)writer;
334
4.35k
  z_stream *z = &zp->z; /* zlib state structure */
335
336
4.35k
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
337
2.82k
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
338
339
1.52k
  if(zp->zlib_init == ZLIB_INIT_GZIP) {
340
    /* Let zlib handle the gzip decompression entirely */
341
1.52k
    z->next_in = (z_const Bytef *)buf;
342
1.52k
    z->avail_in = (uInt)nbytes;
343
    /* Now uncompress the data */
344
1.52k
    return inflate_stream(data, writer, type, ZLIB_INIT_GZIP);
345
1.52k
  }
346
347
  /* We are running with an old version: return error. */
348
0
  return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
349
1.52k
}
350
351
static void gzip_do_close(struct Curl_easy *data,
352
                          struct Curl_cwriter *writer)
353
472
{
354
472
  struct zlib_writer *zp = (struct zlib_writer *)writer;
355
472
  z_stream *z = &zp->z; /* zlib state structure */
356
357
472
  exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
358
472
}
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
0
{
383
0
  switch(be) {
384
0
  case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:
385
0
  case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:
386
0
  case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:
387
0
  case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:
388
0
  case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:
389
0
  case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:
390
0
  case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:
391
0
  case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:
392
0
  case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:
393
0
  case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:
394
0
  case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:
395
0
  case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:
396
0
  case BROTLI_DECODER_ERROR_FORMAT_PADDING_1:
397
0
  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
0
  case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:
402
0
  case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:
403
0
    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
0
  default:
412
0
    break;
413
0
  }
414
0
  return CURLE_WRITE_ERROR;
415
0
}
416
417
static CURLcode brotli_do_init(struct Curl_easy *data,
418
                               struct Curl_cwriter *writer)
419
0
{
420
0
  struct brotli_writer *bp = (struct brotli_writer *)writer;
421
0
  (void)data;
422
423
0
  bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL);
424
0
  return bp->br ? CURLE_OK : CURLE_OUT_OF_MEMORY;
425
0
}
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
0
{
431
0
  struct brotli_writer *bp = (struct brotli_writer *)writer;
432
0
  const uint8_t *src = (const uint8_t *)buf;
433
0
  uint8_t *dst;
434
0
  size_t dstleft;
435
0
  CURLcode result = CURLE_OK;
436
0
  BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
437
0
  int i = 0;
438
439
0
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
440
0
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
441
442
0
  if(!bp->br)
443
0
    return CURLE_WRITE_ERROR; /* Stream already ended. */
444
445
0
  while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) &&
446
0
        result == CURLE_OK) {
447
448
0
    if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
449
      /* check every MB of output if we are not exceeding time limit */
450
0
      i = 0;
451
0
      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
0
    }
456
457
0
    dst = (uint8_t *)bp->buffer;
458
0
    dstleft = DECOMPRESS_BUFFER_SIZE;
459
0
    r = BrotliDecoderDecompressStream(bp->br,
460
0
                                      &nbytes, &src, &dstleft, &dst, NULL);
461
0
    result = Curl_cwriter_write(data, writer->next, type,
462
0
                                bp->buffer, DECOMPRESS_BUFFER_SIZE - dstleft);
463
0
    if(result)
464
0
      break;
465
0
    switch(r) {
466
0
    case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
467
0
    case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
468
0
      break;
469
0
    case BROTLI_DECODER_RESULT_SUCCESS:
470
0
      BrotliDecoderDestroyInstance(bp->br);
471
0
      bp->br = NULL;
472
0
      if(nbytes)
473
0
        result = CURLE_WRITE_ERROR;
474
0
      break;
475
0
    default:
476
0
      result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br));
477
0
      break;
478
0
    }
479
0
  }
480
0
  return result;
481
0
}
482
483
static void brotli_do_close(struct Curl_easy *data,
484
                            struct Curl_cwriter *writer)
485
0
{
486
0
  struct brotli_writer *bp = (struct brotli_writer *)writer;
487
0
  (void)data;
488
489
0
  if(bp->br) {
490
0
    BrotliDecoderDestroyInstance(bp->br);
491
0
    bp->br = NULL;
492
0
  }
493
0
}
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
0
{
660
0
  struct dynbuf enc;
661
0
  const struct Curl_cwtype * const *cep;
662
0
  CURLcode result = CURLE_OK;
663
0
  curlx_dyn_init(&enc, 255);
664
665
0
  for(cep = general_unencoders; *cep && !result; cep++) {
666
0
    const struct Curl_cwtype *ce = *cep;
667
0
    if(!curl_strequal(ce->name, CONTENT_ENCODING_DEFAULT)) {
668
0
      if(curlx_dyn_len(&enc))
669
0
        result = curlx_dyn_addn(&enc, ", ", 2);
670
0
      if(!result)
671
0
        result = curlx_dyn_add(&enc, ce->name);
672
0
    }
673
0
  }
674
0
  if(!result && !curlx_dyn_len(&enc))
675
0
    result = curlx_dyn_add(&enc, CONTENT_ENCODING_DEFAULT);
676
677
0
  if(!result)
678
0
    return curlx_dyn_ptr(&enc);
679
0
  return NULL;
680
0
}
681
682
/* Deferred error dummy writer. */
683
static CURLcode error_do_init(struct Curl_easy *data,
684
                              struct Curl_cwriter *writer)
685
0
{
686
0
  (void)data;
687
0
  (void)writer;
688
0
  return CURLE_OK;
689
0
}
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
0
{
695
0
  (void)writer;
696
0
  (void)buf;
697
0
  (void)nbytes;
698
699
0
  if(!(type & CLIENTWRITE_BODY) || !nbytes)
700
0
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
701
0
  failf(data, "Unrecognized content encoding type");
702
0
  return CURLE_BAD_CONTENT_ENCODING;
703
0
}
704
705
static void error_do_close(struct Curl_easy *data,
706
                           struct Curl_cwriter *writer)
707
0
{
708
0
  (void)data;
709
0
  (void)writer;
710
0
}
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
626
{
728
626
  const struct Curl_cwtype * const *cep;
729
730
626
  if(phase == CURL_CW_TRANSFER_DECODE) {
731
154
    for(cep = transfer_unencoders; *cep; cep++) {
732
154
      const struct Curl_cwtype *ce = *cep;
733
154
      if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
734
0
         (ce->alias && curl_strnequal(name, ce->alias, len) &&
735
0
          !ce->alias[len]))
736
154
        return ce;
737
154
    }
738
154
  }
739
  /* look among the general decoders */
740
1.41k
  for(cep = general_unencoders; *cep; cep++) {
741
1.41k
    const struct Curl_cwtype *ce = *cep;
742
1.41k
    if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
743
944
       (ce->alias && curl_strnequal(name, ce->alias, len) && !ce->alias[len]))
744
472
      return ce;
745
1.41k
  }
746
0
  return NULL;
747
472
}
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
626
{
754
626
  Curl_cwriter_phase phase = is_transfer ?
755
472
    CURL_CW_TRANSFER_DECODE : CURL_CW_CONTENT_DECODE;
756
626
  CURLcode result;
757
626
  bool has_chunked = FALSE;
758
759
626
  do {
760
626
    const char *name;
761
626
    size_t namelen;
762
626
    bool is_chunked = FALSE;
763
764
    /* Parse a single encoding name. */
765
1.25k
    while(ISBLANK(*enclist) || *enclist == ',')
766
626
      enclist++;
767
768
626
    name = enclist;
769
770
4.84k
    for(namelen = 0; *enclist && *enclist != ','; enclist++)
771
4.21k
      if(*enclist > ' ')
772
2.96k
        namelen = enclist - name + 1;
773
774
626
    if(namelen) {
775
626
      const struct Curl_cwtype *cwt;
776
626
      struct Curl_cwriter *writer;
777
778
626
      CURL_TRC_WRITE(data, "looking for %s decoder: %.*s",
779
626
                     is_transfer ? "transfer" : "content", (int)namelen, name);
780
626
      is_chunked = (is_transfer && (namelen == 7) &&
781
154
                    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
626
      if((is_transfer && !data->set.http_transfer_encoding && !is_chunked) ||
785
626
         (!is_transfer && data->set.http_ce_skip)) {
786
0
        bool is_identity = curl_strnequal(name, "identity", 8);
787
        /* not requested, ignore */
788
0
        CURL_TRC_WRITE(data, "decoder not requested, ignored: %.*s",
789
0
                       (int)namelen, name);
790
0
        if(is_transfer && !data->set.http_te_skip) {
791
0
          if(has_chunked)
792
0
            failf(data, "A Transfer-Encoding (%.*s) was listed after chunked",
793
0
                  (int)namelen, name);
794
0
          else if(is_identity)
795
0
            continue;
796
0
          else
797
0
            failf(data, "Unsolicited Transfer-Encoding (%.*s) found",
798
0
                  (int)namelen, name);
799
0
          return CURLE_BAD_CONTENT_ENCODING;
800
0
        }
801
0
        return CURLE_OK;
802
0
      }
803
804
626
      if(Curl_cwriter_count(data, phase) >= MAX_ENCODE_STACK) {
805
0
        failf(data, "Reject response exceeding limit of %d %s encodings",
806
0
              MAX_ENCODE_STACK,
807
0
              is_transfer ? "transfer" : "content");
808
0
        return CURLE_BAD_CONTENT_ENCODING;
809
0
      }
810
811
626
      cwt = find_unencode_writer(name, namelen, phase);
812
626
      if(is_transfer && !is_chunked &&
813
0
         Curl_cwriter_get_by_name(data, "chunked")) {
814
        /* RFC 9112, ch. 6.1:
815
         * "If any transfer coding other than chunked is applied to a
816
         *  response's content, the sender MUST either apply chunked as the
817
         *  final transfer coding or terminate the message by closing the
818
         *  connection."
819
         * "chunked" must be the last added to be the first in its phase,
820
         *  reject this.
821
         */
822
0
        failf(data, "Reject response due to 'chunked' not being the last "
823
0
              "Transfer-Encoding");
824
0
        return CURLE_BAD_CONTENT_ENCODING;
825
0
      }
826
626
      if(cwt && is_chunked && Curl_cwriter_get_by_type(data, cwt)) {
827
        /* A 'chunked' transfer encoding has already been added.
828
         * Ignore duplicates. See #13451.
829
         * Also RFC 9112, ch. 6.1:
830
         * "A sender MUST NOT apply the chunked transfer coding more than
831
         *  once to a message body."
832
         */
833
0
        CURL_TRC_WRITE(data, "ignoring duplicate 'chunked' decoder");
834
0
      }
835
626
      else {
836
626
        if(!cwt)
837
0
          cwt = &error_writer; /* Defer error at use. */
838
839
626
        result = Curl_cwriter_create(&writer, data, cwt, phase);
840
626
        CURL_TRC_WRITE(data, "added %s decoder %s -> %d",
841
626
                       is_transfer ? "transfer" : "content", cwt->name,
842
626
                       (int)result);
843
626
        if(result)
844
0
          return result;
845
846
626
        result = Curl_cwriter_add(data, writer);
847
626
        if(result) {
848
0
          Curl_cwriter_free(data, writer);
849
0
          return result;
850
0
        }
851
626
      }
852
626
      if(is_chunked)
853
154
        has_chunked = TRUE;
854
626
    }
855
626
  } while(*enclist);
856
857
626
  return CURLE_OK;
858
626
}
859
860
#else
861
/* Stubs for builds without HTTP. */
862
CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
863
                                     const char *enclist, int is_transfer)
864
{
865
  (void)data;
866
  (void)enclist;
867
  (void)is_transfer;
868
  return CURLE_NOT_BUILT_IN;
869
}
870
871
char *Curl_get_content_encodings(void)
872
{
873
  return curlx_strdup(CONTENT_ENCODING_DEFAULT);
874
}
875
876
#endif /* CURL_DISABLE_HTTP */