follow redirect: ignore response-body on redirect even if compressed
[platform/upstream/curl.git] / lib / content_encoding.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2010, 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 http://curl.haxx.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  ***************************************************************************/
22
23 #include "setup.h"
24
25 #ifdef HAVE_LIBZ
26
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include "urldata.h"
31 #include <curl/curl.h>
32 #include "sendf.h"
33 #include "content_encoding.h"
34 #include "curl_memory.h"
35
36 #include "memdebug.h"
37
38 /* Comment this out if zlib is always going to be at least ver. 1.2.0.4
39    (doing so will reduce code size slightly). */
40 #define OLD_ZLIB_SUPPORT 1
41
42 #define DSIZ CURL_MAX_WRITE_SIZE /* buffer size for decompressed data */
43
44 #define GZIP_MAGIC_0 0x1f
45 #define GZIP_MAGIC_1 0x8b
46
47 /* gzip flag byte */
48 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
49 #define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
50 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
51 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
52 #define COMMENT      0x10 /* bit 4 set: file comment present */
53 #define RESERVED     0xE0 /* bits 5..7: reserved */
54
55 static CURLcode
56 process_zlib_error(struct connectdata *conn, z_stream *z)
57 {
58   struct SessionHandle *data = conn->data;
59   if(z->msg)
60     failf (data, "Error while processing content unencoding: %s",
61            z->msg);
62   else
63     failf (data, "Error while processing content unencoding: "
64            "Unknown failure within decompression software.");
65
66   return CURLE_BAD_CONTENT_ENCODING;
67 }
68
69 static CURLcode
70 exit_zlib(z_stream *z, zlibInitState *zlib_init, CURLcode result)
71 {
72   inflateEnd(z);
73   *zlib_init = ZLIB_UNINIT;
74   return result;
75 }
76
77 static CURLcode
78 inflate_stream(struct connectdata *conn,
79                struct SingleRequest *k)
80 {
81   int allow_restart = 1;
82   z_stream *z = &k->z;          /* zlib state structure */
83   uInt nread = z->avail_in;
84   Bytef *orig_in = z->next_in;
85   int status;                   /* zlib status */
86   CURLcode result = CURLE_OK;   /* Curl_client_write status */
87   char *decomp;                 /* Put the decompressed data here. */
88
89   /* Dynamically allocate a buffer for decompression because it's uncommonly
90      large to hold on the stack */
91   decomp = malloc(DSIZ);
92   if(decomp == NULL) {
93     return exit_zlib(z, &k->zlib_init, CURLE_OUT_OF_MEMORY);
94   }
95
96   /* because the buffer size is fixed, iteratively decompress and transfer to
97      the client via client_write. */
98   for (;;) {
99     /* (re)set buffer for decompressed output for every iteration */
100     z->next_out = (Bytef *)decomp;
101     z->avail_out = DSIZ;
102
103     status = inflate(z, Z_SYNC_FLUSH);
104     if(status == Z_OK || status == Z_STREAM_END) {
105       allow_restart = 0;
106       if((DSIZ - z->avail_out) && (!k->ignorebody)) {
107         result = Curl_client_write(conn, CLIENTWRITE_BODY, decomp,
108                                    DSIZ - z->avail_out);
109         /* if !CURLE_OK, clean up, return */
110         if(result) {
111           free(decomp);
112           return exit_zlib(z, &k->zlib_init, result);
113         }
114       }
115
116       /* Done? clean up, return */
117       if(status == Z_STREAM_END) {
118         free(decomp);
119         if(inflateEnd(z) == Z_OK)
120           return exit_zlib(z, &k->zlib_init, result);
121         else
122           return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
123       }
124
125       /* Done with these bytes, exit */
126       if(status == Z_OK && z->avail_in == 0) {
127         free(decomp);
128         return result;
129       }
130     }
131     else if(allow_restart && status == Z_DATA_ERROR) {
132       /* some servers seem to not generate zlib headers, so this is an attempt
133          to fix and continue anyway */
134
135       (void) inflateEnd(z);     /* don't care about the return code */
136       if(inflateInit2(z, -MAX_WBITS) != Z_OK) {
137         free(decomp);
138         return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
139       }
140       z->next_in = orig_in;
141       z->avail_in = nread;
142       allow_restart = 0;
143       continue;
144     }
145     else {                      /* Error; exit loop, handle below */
146       free(decomp);
147       return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
148     }
149   }
150   /* Will never get here */
151 }
152
153 CURLcode
154 Curl_unencode_deflate_write(struct connectdata *conn,
155                             struct SingleRequest *k,
156                             ssize_t nread)
157 {
158   z_stream *z = &k->z;          /* zlib state structure */
159
160   /* Initialize zlib? */
161   if(k->zlib_init == ZLIB_UNINIT) {
162     z->zalloc = (alloc_func)Z_NULL;
163     z->zfree = (free_func)Z_NULL;
164     z->opaque = 0;
165     z->next_in = NULL;
166     z->avail_in = 0;
167     if(inflateInit(z) != Z_OK)
168       return process_zlib_error(conn, z);
169     k->zlib_init = ZLIB_INIT;
170   }
171
172   /* Set the compressed input when this function is called */
173   z->next_in = (Bytef *)k->str;
174   z->avail_in = (uInt)nread;
175
176   /* Now uncompress the data */
177   return inflate_stream(conn, k);
178 }
179
180 #ifdef OLD_ZLIB_SUPPORT
181 /* Skip over the gzip header */
182 static enum {
183   GZIP_OK,
184   GZIP_BAD,
185   GZIP_UNDERFLOW
186 } check_gzip_header(unsigned char const *data, ssize_t len, ssize_t *headerlen)
187 {
188   int method, flags;
189   const ssize_t totallen = len;
190
191   /* The shortest header is 10 bytes */
192   if(len < 10)
193     return GZIP_UNDERFLOW;
194
195   if((data[0] != GZIP_MAGIC_0) || (data[1] != GZIP_MAGIC_1))
196     return GZIP_BAD;
197
198   method = data[2];
199   flags = data[3];
200
201   if(method != Z_DEFLATED || (flags & RESERVED) != 0) {
202     /* Can't handle this compression method or unknown flag */
203     return GZIP_BAD;
204   }
205
206   /* Skip over time, xflags, OS code and all previous bytes */
207   len -= 10;
208   data += 10;
209
210   if(flags & EXTRA_FIELD) {
211     ssize_t extra_len;
212
213     if(len < 2)
214       return GZIP_UNDERFLOW;
215
216     extra_len = (data[1] << 8) | data[0];
217
218     if(len < (extra_len+2))
219       return GZIP_UNDERFLOW;
220
221     len -= (extra_len + 2);
222     data += (extra_len + 2);
223   }
224
225   if(flags & ORIG_NAME) {
226     /* Skip over NUL-terminated file name */
227     while(len && *data) {
228       --len;
229       ++data;
230     }
231     if(!len || *data)
232       return GZIP_UNDERFLOW;
233
234     /* Skip over the NUL */
235     --len;
236     ++data;
237   }
238
239   if(flags & COMMENT) {
240     /* Skip over NUL-terminated comment */
241     while(len && *data) {
242       --len;
243       ++data;
244     }
245     if(!len || *data)
246       return GZIP_UNDERFLOW;
247
248     /* Skip over the NUL */
249     --len;
250   }
251
252   if(flags & HEAD_CRC) {
253     if(len < 2)
254       return GZIP_UNDERFLOW;
255
256     len -= 2;
257   }
258
259   *headerlen = totallen - len;
260   return GZIP_OK;
261 }
262 #endif
263
264 CURLcode
265 Curl_unencode_gzip_write(struct connectdata *conn,
266                          struct SingleRequest *k,
267                          ssize_t nread)
268 {
269   z_stream *z = &k->z;          /* zlib state structure */
270
271   /* Initialize zlib? */
272   if(k->zlib_init == ZLIB_UNINIT) {
273     z->zalloc = (alloc_func)Z_NULL;
274     z->zfree = (free_func)Z_NULL;
275     z->opaque = 0;
276     z->next_in = NULL;
277     z->avail_in = 0;
278
279     if(strcmp(zlibVersion(), "1.2.0.4") >= 0) {
280       /* zlib ver. >= 1.2.0.4 supports transparent gzip decompressing */
281       if(inflateInit2(z, MAX_WBITS+32) != Z_OK) {
282         return process_zlib_error(conn, z);
283       }
284       k->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
285     }
286     else {
287       /* we must parse the gzip header ourselves */
288       if(inflateInit2(z, -MAX_WBITS) != Z_OK) {
289         return process_zlib_error(conn, z);
290       }
291       k->zlib_init = ZLIB_INIT;   /* Initial call state */
292     }
293   }
294
295   if(k->zlib_init == ZLIB_INIT_GZIP) {
296     /* Let zlib handle the gzip decompression entirely */
297     z->next_in = (Bytef *)k->str;
298     z->avail_in = (uInt)nread;
299     /* Now uncompress the data */
300     return inflate_stream(conn, k);
301   }
302
303 #ifndef OLD_ZLIB_SUPPORT
304   /* Support for old zlib versions is compiled away and we are running with
305      an old version, so return an error. */
306   return exit_zlib(z, &k->zlib_init, CURLE_FUNCTION_NOT_FOUND);
307
308 #else
309   /* This next mess is to get around the potential case where there isn't
310    * enough data passed in to skip over the gzip header.  If that happens, we
311    * malloc a block and copy what we have then wait for the next call.  If
312    * there still isn't enough (this is definitely a worst-case scenario), we
313    * make the block bigger, copy the next part in and keep waiting.
314    *
315    * This is only required with zlib versions < 1.2.0.4 as newer versions
316    * can handle the gzip header themselves.
317    */
318
319   switch (k->zlib_init) {
320   /* Skip over gzip header? */
321   case ZLIB_INIT:
322   {
323     /* Initial call state */
324     ssize_t hlen;
325
326     switch (check_gzip_header((unsigned char *)k->str, nread, &hlen)) {
327     case GZIP_OK:
328       z->next_in = (Bytef *)k->str + hlen;
329       z->avail_in = (uInt)(nread - hlen);
330       k->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */
331       break;
332
333     case GZIP_UNDERFLOW:
334       /* We need more data so we can find the end of the gzip header.  It's
335        * possible that the memory block we malloc here will never be freed if
336        * the transfer abruptly aborts after this point.  Since it's unlikely
337        * that circumstances will be right for this code path to be followed in
338        * the first place, and it's even more unlikely for a transfer to fail
339        * immediately afterwards, it should seldom be a problem.
340        */
341       z->avail_in = (uInt)nread;
342       z->next_in = malloc(z->avail_in);
343       if(z->next_in == NULL) {
344         return exit_zlib(z, &k->zlib_init, CURLE_OUT_OF_MEMORY);
345       }
346       memcpy(z->next_in, k->str, z->avail_in);
347       k->zlib_init = ZLIB_GZIP_HEADER;   /* Need more gzip header data state */
348       /* We don't have any data to inflate yet */
349       return CURLE_OK;
350
351     case GZIP_BAD:
352     default:
353       return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
354     }
355
356   }
357   break;
358
359   case ZLIB_GZIP_HEADER:
360   {
361     /* Need more gzip header data state */
362     ssize_t hlen;
363     unsigned char *oldblock = z->next_in;
364
365     z->avail_in += (uInt)nread;
366     z->next_in = realloc(z->next_in, z->avail_in);
367     if(z->next_in == NULL) {
368       free(oldblock);
369       return exit_zlib(z, &k->zlib_init, CURLE_OUT_OF_MEMORY);
370     }
371     /* Append the new block of data to the previous one */
372     memcpy(z->next_in + z->avail_in - nread, k->str, nread);
373
374     switch (check_gzip_header(z->next_in, z->avail_in, &hlen)) {
375     case GZIP_OK:
376       /* This is the zlib stream data */
377       free(z->next_in);
378       /* Don't point into the malloced block since we just freed it */
379       z->next_in = (Bytef *)k->str + hlen + nread - z->avail_in;
380       z->avail_in = (uInt)(z->avail_in - hlen);
381       k->zlib_init = ZLIB_GZIP_INFLATING;   /* Inflating stream state */
382       break;
383
384     case GZIP_UNDERFLOW:
385       /* We still don't have any data to inflate! */
386       return CURLE_OK;
387
388     case GZIP_BAD:
389     default:
390       free(z->next_in);
391       return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
392     }
393
394   }
395   break;
396
397   case ZLIB_GZIP_INFLATING:
398   default:
399     /* Inflating stream state */
400     z->next_in = (Bytef *)k->str;
401     z->avail_in = (uInt)nread;
402     break;
403   }
404
405   if(z->avail_in == 0) {
406     /* We don't have any data to inflate; wait until next time */
407     return CURLE_OK;
408   }
409
410   /* We've parsed the header, now uncompress the data */
411   return inflate_stream(conn, k);
412 #endif
413 }
414
415 void Curl_unencode_cleanup(struct connectdata *conn)
416 {
417   struct SessionHandle *data = conn->data;
418   struct SingleRequest *k = &data->req;
419   z_stream *z = &k->z;
420   if(k->zlib_init != ZLIB_UNINIT)
421     (void) exit_zlib(z, &k->zlib_init, CURLE_OK);
422 }
423
424 #endif /* HAVE_LIBZ */