• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
25 #include "curl_setup.h"
26 
27 #include "urldata.h"
28 #include <curl/curl.h>
29 #include <stddef.h>
30 
31 #ifdef HAVE_LIBZ
32 #include <zlib.h>
33 #endif
34 
35 #ifdef HAVE_BROTLI
36 #if defined(__GNUC__)
37 /* Ignore -Wvla warnings in brotli headers */
38 #pragma GCC diagnostic push
39 #pragma GCC diagnostic ignored "-Wvla"
40 #endif
41 #include <brotli/decode.h>
42 #if defined(__GNUC__)
43 #pragma GCC diagnostic pop
44 #endif
45 #endif
46 
47 #ifdef HAVE_ZSTD
48 #include <zstd.h>
49 #endif
50 
51 #include "sendf.h"
52 #include "http.h"
53 #include "content_encoding.h"
54 #include "strdup.h"
55 #include "strcase.h"
56 #include "curl_memory.h"
57 #include "memdebug.h"
58 
59 #define CONTENT_ENCODING_DEFAULT  "identity"
60 
61 #ifndef CURL_DISABLE_HTTP
62 
63 #define DSIZ CURL_MAX_WRITE_SIZE /* buffer size for decompressed data */
64 
65 
66 #ifdef HAVE_LIBZ
67 
68 /* Comment this out if zlib is always going to be at least ver. 1.2.0.4
69    (doing so will reduce code size slightly). */
70 #define OLD_ZLIB_SUPPORT 1
71 
72 #define GZIP_MAGIC_0 0x1f
73 #define GZIP_MAGIC_1 0x8b
74 
75 /* gzip flag byte */
76 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
77 #define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
78 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
79 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
80 #define COMMENT      0x10 /* bit 4 set: file comment present */
81 #define RESERVED     0xE0 /* bits 5..7: reserved */
82 
83 typedef enum {
84   ZLIB_UNINIT,               /* uninitialized */
85   ZLIB_INIT,                 /* initialized */
86   ZLIB_INFLATING,            /* inflating started. */
87   ZLIB_EXTERNAL_TRAILER,     /* reading external trailer */
88   ZLIB_GZIP_HEADER,          /* reading gzip header */
89   ZLIB_GZIP_INFLATING,       /* inflating gzip stream */
90   ZLIB_INIT_GZIP             /* initialized in transparent gzip mode */
91 } zlibInitState;
92 
93 /* Deflate and gzip writer. */
94 struct zlib_writer {
95   struct contenc_writer super;
96   zlibInitState zlib_init;   /* zlib init state */
97   uInt trailerlen;           /* Remaining trailer byte count. */
98   z_stream z;                /* State structure for zlib. */
99 };
100 
101 
102 static voidpf
zalloc_cb(voidpf opaque,unsigned int items,unsigned int size)103 zalloc_cb(voidpf opaque, unsigned int items, unsigned int size)
104 {
105   (void) opaque;
106   /* not a typo, keep it calloc() */
107   return (voidpf) calloc(items, size);
108 }
109 
110 static void
zfree_cb(voidpf opaque,voidpf ptr)111 zfree_cb(voidpf opaque, voidpf ptr)
112 {
113   (void) opaque;
114   free(ptr);
115 }
116 
117 static CURLcode
process_zlib_error(struct Curl_easy * data,z_stream * z)118 process_zlib_error(struct Curl_easy *data, z_stream *z)
119 {
120   if(z->msg)
121     failf(data, "Error while processing content unencoding: %s",
122           z->msg);
123   else
124     failf(data, "Error while processing content unencoding: "
125           "Unknown failure within decompression software.");
126 
127   return CURLE_BAD_CONTENT_ENCODING;
128 }
129 
130 static CURLcode
exit_zlib(struct Curl_easy * data,z_stream * z,zlibInitState * zlib_init,CURLcode result)131 exit_zlib(struct Curl_easy *data,
132           z_stream *z, zlibInitState *zlib_init, CURLcode result)
133 {
134   if(*zlib_init == ZLIB_GZIP_HEADER)
135     Curl_safefree(z->next_in);
136 
137   if(*zlib_init != ZLIB_UNINIT) {
138     if(inflateEnd(z) != Z_OK && result == CURLE_OK)
139       result = process_zlib_error(data, z);
140     *zlib_init = ZLIB_UNINIT;
141   }
142 
143   return result;
144 }
145 
process_trailer(struct Curl_easy * data,struct zlib_writer * zp)146 static CURLcode process_trailer(struct Curl_easy *data,
147                                 struct zlib_writer *zp)
148 {
149   z_stream *z = &zp->z;
150   CURLcode result = CURLE_OK;
151   uInt len = z->avail_in < zp->trailerlen? z->avail_in: zp->trailerlen;
152 
153   /* Consume expected trailer bytes. Terminate stream if exhausted.
154      Issue an error if unexpected bytes follow. */
155 
156   zp->trailerlen -= len;
157   z->avail_in -= len;
158   z->next_in += len;
159   if(z->avail_in)
160     result = CURLE_WRITE_ERROR;
161   if(result || !zp->trailerlen)
162     result = exit_zlib(data, z, &zp->zlib_init, result);
163   else {
164     /* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */
165     zp->zlib_init = ZLIB_EXTERNAL_TRAILER;
166   }
167   return result;
168 }
169 
inflate_stream(struct Curl_easy * data,struct contenc_writer * writer,zlibInitState started)170 static CURLcode inflate_stream(struct Curl_easy *data,
171                                struct contenc_writer *writer,
172                                zlibInitState started)
173 {
174   struct zlib_writer *zp = (struct zlib_writer *) writer;
175   z_stream *z = &zp->z;         /* zlib state structure */
176   uInt nread = z->avail_in;
177   Bytef *orig_in = z->next_in;
178   bool done = FALSE;
179   CURLcode result = CURLE_OK;   /* Curl_client_write status */
180   char *decomp;                 /* Put the decompressed data here. */
181 
182   /* Check state. */
183   if(zp->zlib_init != ZLIB_INIT &&
184      zp->zlib_init != ZLIB_INFLATING &&
185      zp->zlib_init != ZLIB_INIT_GZIP &&
186      zp->zlib_init != ZLIB_GZIP_INFLATING)
187     return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
188 
189   /* Dynamically allocate a buffer for decompression because it's uncommonly
190      large to hold on the stack */
191   decomp = malloc(DSIZ);
192   if(!decomp)
193     return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);
194 
195   /* because the buffer size is fixed, iteratively decompress and transfer to
196      the client via downstream_write function. */
197   while(!done) {
198     int status;                   /* zlib status */
199     done = TRUE;
200 
201     /* (re)set buffer for decompressed output for every iteration */
202     z->next_out = (Bytef *) decomp;
203     z->avail_out = DSIZ;
204 
205 #ifdef Z_BLOCK
206     /* Z_BLOCK is only available in zlib ver. >= 1.2.0.5 */
207     status = inflate(z, Z_BLOCK);
208 #else
209     /* fallback for zlib ver. < 1.2.0.5 */
210     status = inflate(z, Z_SYNC_FLUSH);
211 #endif
212 
213     /* Flush output data if some. */
214     if(z->avail_out != DSIZ) {
215       if(status == Z_OK || status == Z_STREAM_END) {
216         zp->zlib_init = started;      /* Data started. */
217         result = Curl_unencode_write(data, writer->downstream, decomp,
218                                      DSIZ - z->avail_out);
219         if(result) {
220           exit_zlib(data, z, &zp->zlib_init, result);
221           break;
222         }
223       }
224     }
225 
226     /* Dispatch by inflate() status. */
227     switch(status) {
228     case Z_OK:
229       /* Always loop: there may be unflushed latched data in zlib state. */
230       done = FALSE;
231       break;
232     case Z_BUF_ERROR:
233       /* No more data to flush: just exit loop. */
234       break;
235     case Z_STREAM_END:
236       result = process_trailer(data, zp);
237       break;
238     case Z_DATA_ERROR:
239       /* some servers seem to not generate zlib headers, so this is an attempt
240          to fix and continue anyway */
241       if(zp->zlib_init == ZLIB_INIT) {
242         /* Do not use inflateReset2(): only available since zlib 1.2.3.4. */
243         (void) inflateEnd(z);     /* don't care about the return code */
244         if(inflateInit2(z, -MAX_WBITS) == Z_OK) {
245           z->next_in = orig_in;
246           z->avail_in = nread;
247           zp->zlib_init = ZLIB_INFLATING;
248           zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */
249           done = FALSE;
250           break;
251         }
252         zp->zlib_init = ZLIB_UNINIT;    /* inflateEnd() already called. */
253       }
254       result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
255       break;
256     default:
257       result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
258       break;
259     }
260   }
261   free(decomp);
262 
263   /* We're about to leave this call so the `nread' data bytes won't be seen
264      again. If we are in a state that would wrongly allow restart in raw mode
265      at the next call, assume output has already started. */
266   if(nread && zp->zlib_init == ZLIB_INIT)
267     zp->zlib_init = started;      /* Cannot restart anymore. */
268 
269   return result;
270 }
271 
272 
273 /* Deflate handler. */
deflate_init_writer(struct Curl_easy * data,struct contenc_writer * writer)274 static CURLcode deflate_init_writer(struct Curl_easy *data,
275                                     struct contenc_writer *writer)
276 {
277   struct zlib_writer *zp = (struct zlib_writer *) writer;
278   z_stream *z = &zp->z;     /* zlib state structure */
279 
280   if(!writer->downstream)
281     return CURLE_WRITE_ERROR;
282 
283   /* Initialize zlib */
284   z->zalloc = (alloc_func) zalloc_cb;
285   z->zfree = (free_func) zfree_cb;
286 
287   if(inflateInit(z) != Z_OK)
288     return process_zlib_error(data, z);
289   zp->zlib_init = ZLIB_INIT;
290   return CURLE_OK;
291 }
292 
deflate_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)293 static CURLcode deflate_unencode_write(struct Curl_easy *data,
294                                        struct contenc_writer *writer,
295                                        const char *buf, size_t nbytes)
296 {
297   struct zlib_writer *zp = (struct zlib_writer *) writer;
298   z_stream *z = &zp->z;     /* zlib state structure */
299 
300   /* Set the compressed input when this function is called */
301   z->next_in = (Bytef *) buf;
302   z->avail_in = (uInt) nbytes;
303 
304   if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER)
305     return process_trailer(data, zp);
306 
307   /* Now uncompress the data */
308   return inflate_stream(data, writer, ZLIB_INFLATING);
309 }
310 
deflate_close_writer(struct Curl_easy * data,struct contenc_writer * writer)311 static void deflate_close_writer(struct Curl_easy *data,
312                                  struct contenc_writer *writer)
313 {
314   struct zlib_writer *zp = (struct zlib_writer *) writer;
315   z_stream *z = &zp->z;     /* zlib state structure */
316 
317   exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
318 }
319 
320 static const struct content_encoding deflate_encoding = {
321   "deflate",
322   NULL,
323   deflate_init_writer,
324   deflate_unencode_write,
325   deflate_close_writer,
326   sizeof(struct zlib_writer)
327 };
328 
329 
330 /* Gzip handler. */
gzip_init_writer(struct Curl_easy * data,struct contenc_writer * writer)331 static CURLcode gzip_init_writer(struct Curl_easy *data,
332                                  struct contenc_writer *writer)
333 {
334   struct zlib_writer *zp = (struct zlib_writer *) writer;
335   z_stream *z = &zp->z;     /* zlib state structure */
336 
337   if(!writer->downstream)
338     return CURLE_WRITE_ERROR;
339 
340   /* Initialize zlib */
341   z->zalloc = (alloc_func) zalloc_cb;
342   z->zfree = (free_func) zfree_cb;
343 
344   if(strcmp(zlibVersion(), "1.2.0.4") >= 0) {
345     /* zlib ver. >= 1.2.0.4 supports transparent gzip decompressing */
346     if(inflateInit2(z, MAX_WBITS + 32) != Z_OK) {
347       return process_zlib_error(data, z);
348     }
349     zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
350   }
351   else {
352     /* we must parse the gzip header and trailer ourselves */
353     if(inflateInit2(z, -MAX_WBITS) != Z_OK) {
354       return process_zlib_error(data, z);
355     }
356     zp->trailerlen = 8; /* A CRC-32 and a 32-bit input size (RFC 1952, 2.2) */
357     zp->zlib_init = ZLIB_INIT; /* Initial call state */
358   }
359 
360   return CURLE_OK;
361 }
362 
363 #ifdef OLD_ZLIB_SUPPORT
364 /* Skip over the gzip header */
365 static enum {
366   GZIP_OK,
367   GZIP_BAD,
368   GZIP_UNDERFLOW
check_gzip_header(unsigned char const * data,ssize_t len,ssize_t * headerlen)369 } check_gzip_header(unsigned char const *data, ssize_t len, ssize_t *headerlen)
370 {
371   int method, flags;
372   const ssize_t totallen = len;
373 
374   /* The shortest header is 10 bytes */
375   if(len < 10)
376     return GZIP_UNDERFLOW;
377 
378   if((data[0] != GZIP_MAGIC_0) || (data[1] != GZIP_MAGIC_1))
379     return GZIP_BAD;
380 
381   method = data[2];
382   flags = data[3];
383 
384   if(method != Z_DEFLATED || (flags & RESERVED) != 0) {
385     /* Can't handle this compression method or unknown flag */
386     return GZIP_BAD;
387   }
388 
389   /* Skip over time, xflags, OS code and all previous bytes */
390   len -= 10;
391   data += 10;
392 
393   if(flags & EXTRA_FIELD) {
394     ssize_t extra_len;
395 
396     if(len < 2)
397       return GZIP_UNDERFLOW;
398 
399     extra_len = (data[1] << 8) | data[0];
400 
401     if(len < (extra_len + 2))
402       return GZIP_UNDERFLOW;
403 
404     len -= (extra_len + 2);
405     data += (extra_len + 2);
406   }
407 
408   if(flags & ORIG_NAME) {
409     /* Skip over NUL-terminated file name */
410     while(len && *data) {
411       --len;
412       ++data;
413     }
414     if(!len || *data)
415       return GZIP_UNDERFLOW;
416 
417     /* Skip over the NUL */
418     --len;
419     ++data;
420   }
421 
422   if(flags & COMMENT) {
423     /* Skip over NUL-terminated comment */
424     while(len && *data) {
425       --len;
426       ++data;
427     }
428     if(!len || *data)
429       return GZIP_UNDERFLOW;
430 
431     /* Skip over the NUL */
432     --len;
433   }
434 
435   if(flags & HEAD_CRC) {
436     if(len < 2)
437       return GZIP_UNDERFLOW;
438 
439     len -= 2;
440   }
441 
442   *headerlen = totallen - len;
443   return GZIP_OK;
444 }
445 #endif
446 
gzip_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)447 static CURLcode gzip_unencode_write(struct Curl_easy *data,
448                                     struct contenc_writer *writer,
449                                     const char *buf, size_t nbytes)
450 {
451   struct zlib_writer *zp = (struct zlib_writer *) writer;
452   z_stream *z = &zp->z;     /* zlib state structure */
453 
454   if(zp->zlib_init == ZLIB_INIT_GZIP) {
455     /* Let zlib handle the gzip decompression entirely */
456     z->next_in = (Bytef *) buf;
457     z->avail_in = (uInt) nbytes;
458     /* Now uncompress the data */
459     return inflate_stream(data, writer, ZLIB_INIT_GZIP);
460   }
461 
462 #ifndef OLD_ZLIB_SUPPORT
463   /* Support for old zlib versions is compiled away and we are running with
464      an old version, so return an error. */
465   return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
466 
467 #else
468   /* This next mess is to get around the potential case where there isn't
469    * enough data passed in to skip over the gzip header.  If that happens, we
470    * malloc a block and copy what we have then wait for the next call.  If
471    * there still isn't enough (this is definitely a worst-case scenario), we
472    * make the block bigger, copy the next part in and keep waiting.
473    *
474    * This is only required with zlib versions < 1.2.0.4 as newer versions
475    * can handle the gzip header themselves.
476    */
477 
478   switch(zp->zlib_init) {
479   /* Skip over gzip header? */
480   case ZLIB_INIT:
481   {
482     /* Initial call state */
483     ssize_t hlen;
484 
485     switch(check_gzip_header((unsigned char *) buf, nbytes, &hlen)) {
486     case GZIP_OK:
487       z->next_in = (Bytef *) buf + hlen;
488       z->avail_in = (uInt) (nbytes - hlen);
489       zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */
490       break;
491 
492     case GZIP_UNDERFLOW:
493       /* We need more data so we can find the end of the gzip header.  It's
494        * possible that the memory block we malloc here will never be freed if
495        * the transfer abruptly aborts after this point.  Since it's unlikely
496        * that circumstances will be right for this code path to be followed in
497        * the first place, and it's even more unlikely for a transfer to fail
498        * immediately afterwards, it should seldom be a problem.
499        */
500       z->avail_in = (uInt) nbytes;
501       z->next_in = malloc(z->avail_in);
502       if(!z->next_in) {
503         return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);
504       }
505       memcpy(z->next_in, buf, z->avail_in);
506       zp->zlib_init = ZLIB_GZIP_HEADER;  /* Need more gzip header data state */
507       /* We don't have any data to inflate yet */
508       return CURLE_OK;
509 
510     case GZIP_BAD:
511     default:
512       return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
513     }
514 
515   }
516   break;
517 
518   case ZLIB_GZIP_HEADER:
519   {
520     /* Need more gzip header data state */
521     ssize_t hlen;
522     z->avail_in += (uInt) nbytes;
523     z->next_in = Curl_saferealloc(z->next_in, z->avail_in);
524     if(!z->next_in) {
525       return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);
526     }
527     /* Append the new block of data to the previous one */
528     memcpy(z->next_in + z->avail_in - nbytes, buf, nbytes);
529 
530     switch(check_gzip_header(z->next_in, z->avail_in, &hlen)) {
531     case GZIP_OK:
532       /* This is the zlib stream data */
533       free(z->next_in);
534       /* Don't point into the malloced block since we just freed it */
535       z->next_in = (Bytef *) buf + hlen + nbytes - z->avail_in;
536       z->avail_in = (uInt) (z->avail_in - hlen);
537       zp->zlib_init = ZLIB_GZIP_INFLATING;   /* Inflating stream state */
538       break;
539 
540     case GZIP_UNDERFLOW:
541       /* We still don't have any data to inflate! */
542       return CURLE_OK;
543 
544     case GZIP_BAD:
545     default:
546       return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
547     }
548 
549   }
550   break;
551 
552   case ZLIB_EXTERNAL_TRAILER:
553     z->next_in = (Bytef *) buf;
554     z->avail_in = (uInt) nbytes;
555     return process_trailer(data, zp);
556 
557   case ZLIB_GZIP_INFLATING:
558   default:
559     /* Inflating stream state */
560     z->next_in = (Bytef *) buf;
561     z->avail_in = (uInt) nbytes;
562     break;
563   }
564 
565   if(z->avail_in == 0) {
566     /* We don't have any data to inflate; wait until next time */
567     return CURLE_OK;
568   }
569 
570   /* We've parsed the header, now uncompress the data */
571   return inflate_stream(data, writer, ZLIB_GZIP_INFLATING);
572 #endif
573 }
574 
gzip_close_writer(struct Curl_easy * data,struct contenc_writer * writer)575 static void gzip_close_writer(struct Curl_easy *data,
576                               struct contenc_writer *writer)
577 {
578   struct zlib_writer *zp = (struct zlib_writer *) writer;
579   z_stream *z = &zp->z;     /* zlib state structure */
580 
581   exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
582 }
583 
584 static const struct content_encoding gzip_encoding = {
585   "gzip",
586   "x-gzip",
587   gzip_init_writer,
588   gzip_unencode_write,
589   gzip_close_writer,
590   sizeof(struct zlib_writer)
591 };
592 
593 #endif /* HAVE_LIBZ */
594 
595 
596 #ifdef HAVE_BROTLI
597 /* Brotli writer. */
598 struct brotli_writer {
599   struct contenc_writer super;
600   BrotliDecoderState *br;    /* State structure for brotli. */
601 };
602 
brotli_map_error(BrotliDecoderErrorCode be)603 static CURLcode brotli_map_error(BrotliDecoderErrorCode be)
604 {
605   switch(be) {
606   case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:
607   case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:
608   case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:
609   case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:
610   case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:
611   case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:
612   case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:
613   case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:
614   case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:
615   case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:
616   case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:
617   case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:
618   case BROTLI_DECODER_ERROR_FORMAT_PADDING_1:
619   case BROTLI_DECODER_ERROR_FORMAT_PADDING_2:
620 #ifdef BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY
621   case BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY:
622 #endif
623 #ifdef BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET
624   case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:
625 #endif
626   case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:
627     return CURLE_BAD_CONTENT_ENCODING;
628   case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:
629   case BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:
630   case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:
631   case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:
632   case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:
633   case BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:
634     return CURLE_OUT_OF_MEMORY;
635   default:
636     break;
637   }
638   return CURLE_WRITE_ERROR;
639 }
640 
brotli_init_writer(struct Curl_easy * data,struct contenc_writer * writer)641 static CURLcode brotli_init_writer(struct Curl_easy *data,
642                                    struct contenc_writer *writer)
643 {
644   struct brotli_writer *bp = (struct brotli_writer *) writer;
645   (void) data;
646 
647   if(!writer->downstream)
648     return CURLE_WRITE_ERROR;
649 
650   bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL);
651   return bp->br? CURLE_OK: CURLE_OUT_OF_MEMORY;
652 }
653 
brotli_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)654 static CURLcode brotli_unencode_write(struct Curl_easy *data,
655                                       struct contenc_writer *writer,
656                                       const char *buf, size_t nbytes)
657 {
658   struct brotli_writer *bp = (struct brotli_writer *) writer;
659   const uint8_t *src = (const uint8_t *) buf;
660   char *decomp;
661   uint8_t *dst;
662   size_t dstleft;
663   CURLcode result = CURLE_OK;
664   BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
665 
666   if(!bp->br)
667     return CURLE_WRITE_ERROR;  /* Stream already ended. */
668 
669   decomp = malloc(DSIZ);
670   if(!decomp)
671     return CURLE_OUT_OF_MEMORY;
672 
673   while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) &&
674         result == CURLE_OK) {
675     dst = (uint8_t *) decomp;
676     dstleft = DSIZ;
677     r = BrotliDecoderDecompressStream(bp->br,
678                                       &nbytes, &src, &dstleft, &dst, NULL);
679     result = Curl_unencode_write(data, writer->downstream,
680                                  decomp, DSIZ - dstleft);
681     if(result)
682       break;
683     switch(r) {
684     case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
685     case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
686       break;
687     case BROTLI_DECODER_RESULT_SUCCESS:
688       BrotliDecoderDestroyInstance(bp->br);
689       bp->br = NULL;
690       if(nbytes)
691         result = CURLE_WRITE_ERROR;
692       break;
693     default:
694       result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br));
695       break;
696     }
697   }
698   free(decomp);
699   return result;
700 }
701 
brotli_close_writer(struct Curl_easy * data,struct contenc_writer * writer)702 static void brotli_close_writer(struct Curl_easy *data,
703                                 struct contenc_writer *writer)
704 {
705   struct brotli_writer *bp = (struct brotli_writer *) writer;
706 
707   (void) data;
708 
709   if(bp->br) {
710     BrotliDecoderDestroyInstance(bp->br);
711     bp->br = NULL;
712   }
713 }
714 
715 static const struct content_encoding brotli_encoding = {
716   "br",
717   NULL,
718   brotli_init_writer,
719   brotli_unencode_write,
720   brotli_close_writer,
721   sizeof(struct brotli_writer)
722 };
723 #endif
724 
725 
726 #ifdef HAVE_ZSTD
727 /* Zstd writer. */
728 struct zstd_writer {
729   struct contenc_writer super;
730   ZSTD_DStream *zds;    /* State structure for zstd. */
731   void *decomp;
732 };
733 
zstd_init_writer(struct Curl_easy * data,struct contenc_writer * writer)734 static CURLcode zstd_init_writer(struct Curl_easy *data,
735                                  struct contenc_writer *writer)
736 {
737   struct zstd_writer *zp = (struct zstd_writer *) writer;
738 
739   (void)data;
740 
741   if(!writer->downstream)
742     return CURLE_WRITE_ERROR;
743 
744   zp->zds = ZSTD_createDStream();
745   zp->decomp = NULL;
746   return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY;
747 }
748 
zstd_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)749 static CURLcode zstd_unencode_write(struct Curl_easy *data,
750                                     struct contenc_writer *writer,
751                                     const char *buf, size_t nbytes)
752 {
753   CURLcode result = CURLE_OK;
754   struct zstd_writer *zp = (struct zstd_writer *) writer;
755   ZSTD_inBuffer in;
756   ZSTD_outBuffer out;
757   size_t errorCode;
758 
759   if(!zp->decomp) {
760     zp->decomp = malloc(DSIZ);
761     if(!zp->decomp)
762       return CURLE_OUT_OF_MEMORY;
763   }
764   in.pos = 0;
765   in.src = buf;
766   in.size = nbytes;
767 
768   for(;;) {
769     out.pos = 0;
770     out.dst = zp->decomp;
771     out.size = DSIZ;
772 
773     errorCode = ZSTD_decompressStream(zp->zds, &out, &in);
774     if(ZSTD_isError(errorCode)) {
775       return CURLE_BAD_CONTENT_ENCODING;
776     }
777     if(out.pos > 0) {
778       result = Curl_unencode_write(data, writer->downstream,
779                                    zp->decomp, out.pos);
780       if(result)
781         break;
782     }
783     if((in.pos == nbytes) && (out.pos < out.size))
784       break;
785   }
786 
787   return result;
788 }
789 
zstd_close_writer(struct Curl_easy * data,struct contenc_writer * writer)790 static void zstd_close_writer(struct Curl_easy *data,
791                               struct contenc_writer *writer)
792 {
793   struct zstd_writer *zp = (struct zstd_writer *) writer;
794 
795   (void)data;
796 
797   if(zp->decomp) {
798     free(zp->decomp);
799     zp->decomp = NULL;
800   }
801   if(zp->zds) {
802     ZSTD_freeDStream(zp->zds);
803     zp->zds = NULL;
804   }
805 }
806 
807 static const struct content_encoding zstd_encoding = {
808   "zstd",
809   NULL,
810   zstd_init_writer,
811   zstd_unencode_write,
812   zstd_close_writer,
813   sizeof(struct zstd_writer)
814 };
815 #endif
816 
817 
818 /* Identity handler. */
identity_init_writer(struct Curl_easy * data,struct contenc_writer * writer)819 static CURLcode identity_init_writer(struct Curl_easy *data,
820                                      struct contenc_writer *writer)
821 {
822   (void) data;
823   return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR;
824 }
825 
identity_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)826 static CURLcode identity_unencode_write(struct Curl_easy *data,
827                                         struct contenc_writer *writer,
828                                         const char *buf, size_t nbytes)
829 {
830   return Curl_unencode_write(data, writer->downstream, buf, nbytes);
831 }
832 
identity_close_writer(struct Curl_easy * data,struct contenc_writer * writer)833 static void identity_close_writer(struct Curl_easy *data,
834                                   struct contenc_writer *writer)
835 {
836   (void) data;
837   (void) writer;
838 }
839 
840 static const struct content_encoding identity_encoding = {
841   "identity",
842   "none",
843   identity_init_writer,
844   identity_unencode_write,
845   identity_close_writer,
846   sizeof(struct contenc_writer)
847 };
848 
849 
850 /* supported content encodings table. */
851 static const struct content_encoding * const encodings[] = {
852   &identity_encoding,
853 #ifdef HAVE_LIBZ
854   &deflate_encoding,
855   &gzip_encoding,
856 #endif
857 #ifdef HAVE_BROTLI
858   &brotli_encoding,
859 #endif
860 #ifdef HAVE_ZSTD
861   &zstd_encoding,
862 #endif
863   NULL
864 };
865 
866 
867 /* Return a list of comma-separated names of supported encodings. */
Curl_all_content_encodings(void)868 char *Curl_all_content_encodings(void)
869 {
870   size_t len = 0;
871   const struct content_encoding * const *cep;
872   const struct content_encoding *ce;
873   char *ace;
874 
875   for(cep = encodings; *cep; cep++) {
876     ce = *cep;
877     if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT))
878       len += strlen(ce->name) + 2;
879   }
880 
881   if(!len)
882     return strdup(CONTENT_ENCODING_DEFAULT);
883 
884   ace = malloc(len);
885   if(ace) {
886     char *p = ace;
887     for(cep = encodings; *cep; cep++) {
888       ce = *cep;
889       if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT)) {
890         strcpy(p, ce->name);
891         p += strlen(p);
892         *p++ = ',';
893         *p++ = ' ';
894       }
895     }
896     p[-2] = '\0';
897   }
898 
899   return ace;
900 }
901 
902 
903 /* Real client writer: no downstream. */
client_init_writer(struct Curl_easy * data,struct contenc_writer * writer)904 static CURLcode client_init_writer(struct Curl_easy *data,
905                                    struct contenc_writer *writer)
906 {
907   (void) data;
908   return writer->downstream? CURLE_WRITE_ERROR: CURLE_OK;
909 }
910 
client_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)911 static CURLcode client_unencode_write(struct Curl_easy *data,
912                                       struct contenc_writer *writer,
913                                       const char *buf, size_t nbytes)
914 {
915   struct SingleRequest *k = &data->req;
916 
917   (void) writer;
918 
919   if(!nbytes || k->ignorebody)
920     return CURLE_OK;
921 
922   return Curl_client_write(data, CLIENTWRITE_BODY, (char *) buf, nbytes);
923 }
924 
client_close_writer(struct Curl_easy * data,struct contenc_writer * writer)925 static void client_close_writer(struct Curl_easy *data,
926                                 struct contenc_writer *writer)
927 {
928   (void) data;
929   (void) writer;
930 }
931 
932 static const struct content_encoding client_encoding = {
933   NULL,
934   NULL,
935   client_init_writer,
936   client_unencode_write,
937   client_close_writer,
938   sizeof(struct contenc_writer)
939 };
940 
941 
942 /* Deferred error dummy writer. */
error_init_writer(struct Curl_easy * data,struct contenc_writer * writer)943 static CURLcode error_init_writer(struct Curl_easy *data,
944                                   struct contenc_writer *writer)
945 {
946   (void) data;
947   return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR;
948 }
949 
error_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)950 static CURLcode error_unencode_write(struct Curl_easy *data,
951                                      struct contenc_writer *writer,
952                                      const char *buf, size_t nbytes)
953 {
954   char *all = Curl_all_content_encodings();
955 
956   (void) writer;
957   (void) buf;
958   (void) nbytes;
959 
960   if(!all)
961     return CURLE_OUT_OF_MEMORY;
962   failf(data, "Unrecognized content encoding type. "
963         "libcurl understands %s content encodings.", all);
964   free(all);
965   return CURLE_BAD_CONTENT_ENCODING;
966 }
967 
error_close_writer(struct Curl_easy * data,struct contenc_writer * writer)968 static void error_close_writer(struct Curl_easy *data,
969                                struct contenc_writer *writer)
970 {
971   (void) data;
972   (void) writer;
973 }
974 
975 static const struct content_encoding error_encoding = {
976   NULL,
977   NULL,
978   error_init_writer,
979   error_unencode_write,
980   error_close_writer,
981   sizeof(struct contenc_writer)
982 };
983 
984 /* Create an unencoding writer stage using the given handler. */
985 static struct contenc_writer *
new_unencoding_writer(struct Curl_easy * data,const struct content_encoding * handler,struct contenc_writer * downstream,int order)986 new_unencoding_writer(struct Curl_easy *data,
987                       const struct content_encoding *handler,
988                       struct contenc_writer *downstream,
989                       int order)
990 {
991   struct contenc_writer *writer;
992 
993   DEBUGASSERT(handler->writersize >= sizeof(struct contenc_writer));
994   writer = (struct contenc_writer *) calloc(1, handler->writersize);
995 
996   if(writer) {
997     writer->handler = handler;
998     writer->downstream = downstream;
999     writer->order = order;
1000     if(handler->init_writer(data, writer)) {
1001       free(writer);
1002       writer = NULL;
1003     }
1004   }
1005 
1006   return writer;
1007 }
1008 
1009 /* Write data using an unencoding writer stack. "nbytes" is not
1010    allowed to be 0. */
Curl_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)1011 CURLcode Curl_unencode_write(struct Curl_easy *data,
1012                              struct contenc_writer *writer,
1013                              const char *buf, size_t nbytes)
1014 {
1015   if(!nbytes)
1016     return CURLE_OK;
1017   return writer->handler->unencode_write(data, writer, buf, nbytes);
1018 }
1019 
1020 /* Close and clean-up the connection's writer stack. */
Curl_unencode_cleanup(struct Curl_easy * data)1021 void Curl_unencode_cleanup(struct Curl_easy *data)
1022 {
1023   struct SingleRequest *k = &data->req;
1024   struct contenc_writer *writer = k->writer_stack;
1025 
1026   while(writer) {
1027     k->writer_stack = writer->downstream;
1028     writer->handler->close_writer(data, writer);
1029     free(writer);
1030     writer = k->writer_stack;
1031   }
1032 }
1033 
1034 /* Find the content encoding by name. */
find_encoding(const char * name,size_t len)1035 static const struct content_encoding *find_encoding(const char *name,
1036                                                     size_t len)
1037 {
1038   const struct content_encoding * const *cep;
1039 
1040   for(cep = encodings; *cep; cep++) {
1041     const struct content_encoding *ce = *cep;
1042     if((strncasecompare(name, ce->name, len) && !ce->name[len]) ||
1043        (ce->alias && strncasecompare(name, ce->alias, len) && !ce->alias[len]))
1044       return ce;
1045   }
1046   return NULL;
1047 }
1048 
1049 /* allow no more than 5 "chained" compression steps */
1050 #define MAX_ENCODE_STACK 5
1051 
1052 /* Set-up the unencoding stack from the Content-Encoding header value.
1053  * See RFC 7231 section 3.1.2.2. */
Curl_build_unencoding_stack(struct Curl_easy * data,const char * enclist,int is_transfer)1054 CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
1055                                      const char *enclist, int is_transfer)
1056 {
1057   struct SingleRequest *k = &data->req;
1058   unsigned int order = is_transfer? 2: 1;
1059 
1060   do {
1061     const char *name;
1062     size_t namelen;
1063 
1064     /* Parse a single encoding name. */
1065     while(ISBLANK(*enclist) || *enclist == ',')
1066       enclist++;
1067 
1068     name = enclist;
1069 
1070     for(namelen = 0; *enclist && *enclist != ','; enclist++)
1071       if(!ISSPACE(*enclist))
1072         namelen = enclist - name + 1;
1073 
1074     /* Special case: chunked encoding is handled at the reader level. */
1075     if(is_transfer && namelen == 7 && strncasecompare(name, "chunked", 7)) {
1076       k->chunk = TRUE;             /* chunks coming our way. */
1077       Curl_httpchunk_init(data);   /* init our chunky engine. */
1078     }
1079     else if(namelen) {
1080       const struct content_encoding *encoding = find_encoding(name, namelen);
1081       struct contenc_writer *writer;
1082 
1083       if(!k->writer_stack) {
1084         k->writer_stack = new_unencoding_writer(data, &client_encoding,
1085                                                 NULL, 0);
1086 
1087         if(!k->writer_stack)
1088           return CURLE_OUT_OF_MEMORY;
1089       }
1090 
1091       if(!encoding)
1092         encoding = &error_encoding;  /* Defer error at stack use. */
1093 
1094       if(k->writer_stack_depth++ >= MAX_ENCODE_STACK) {
1095         failf(data, "Reject response due to more than %u content encodings",
1096               MAX_ENCODE_STACK);
1097         return CURLE_BAD_CONTENT_ENCODING;
1098       }
1099       /* Stack the unencoding stage. */
1100       if(order >= k->writer_stack->order) {
1101         writer = new_unencoding_writer(data, encoding,
1102                                        k->writer_stack, order);
1103         if(!writer)
1104           return CURLE_OUT_OF_MEMORY;
1105         k->writer_stack = writer;
1106       }
1107       else {
1108         struct contenc_writer *w = k->writer_stack;
1109         while(w->downstream && order < w->downstream->order)
1110           w = w->downstream;
1111         writer = new_unencoding_writer(data, encoding,
1112                                        w->downstream, order);
1113         if(!writer)
1114           return CURLE_OUT_OF_MEMORY;
1115         w->downstream = writer;
1116       }
1117     }
1118   } while(*enclist);
1119 
1120   return CURLE_OK;
1121 }
1122 
1123 #else
1124 /* Stubs for builds without HTTP. */
Curl_build_unencoding_stack(struct Curl_easy * data,const char * enclist,int is_transfer)1125 CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
1126                                      const char *enclist, int is_transfer)
1127 {
1128   (void) data;
1129   (void) enclist;
1130   (void) is_transfer;
1131   return CURLE_NOT_BUILT_IN;
1132 }
1133 
Curl_unencode_write(struct Curl_easy * data,struct contenc_writer * writer,const char * buf,size_t nbytes)1134 CURLcode Curl_unencode_write(struct Curl_easy *data,
1135                              struct contenc_writer *writer,
1136                              const char *buf, size_t nbytes)
1137 {
1138   (void) data;
1139   (void) writer;
1140   (void) buf;
1141   (void) nbytes;
1142   return CURLE_NOT_BUILT_IN;
1143 }
1144 
Curl_unencode_cleanup(struct Curl_easy * data)1145 void Curl_unencode_cleanup(struct Curl_easy *data)
1146 {
1147   (void) data;
1148 }
1149 
Curl_all_content_encodings(void)1150 char *Curl_all_content_encodings(void)
1151 {
1152   return strdup(CONTENT_ENCODING_DEFAULT);  /* Satisfy caller. */
1153 }
1154 
1155 #endif /* CURL_DISABLE_HTTP */
1156