1/***************************************************************************
2 *                                  _   _ ____  _
3 *  Project                     ___| | | |  _ \| |
4 *                             / __| | | | |_) | |
5 *                            | (__| |_| |  _ <| |___
6 *                             \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2011, 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
55static CURLcode
56process_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
69static CURLcode
70exit_zlib(z_stream *z, zlibInitState *zlib_init, CURLcode result)
71{
72  inflateEnd(z);
73  *zlib_init = ZLIB_UNINIT;
74  return result;
75}
76
77static CURLcode
78inflate_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
127      /* status is always Z_OK at this point! */
128      if(z->avail_in == 0) {
129        free(decomp);
130        return result;
131      }
132    }
133    else if(allow_restart && status == Z_DATA_ERROR) {
134      /* some servers seem to not generate zlib headers, so this is an attempt
135         to fix and continue anyway */
136
137      (void) inflateEnd(z);     /* don't care about the return code */
138      if(inflateInit2(z, -MAX_WBITS) != Z_OK) {
139        free(decomp);
140        return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
141      }
142      z->next_in = orig_in;
143      z->avail_in = nread;
144      allow_restart = 0;
145      continue;
146    }
147    else {                      /* Error; exit loop, handle below */
148      free(decomp);
149      return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
150    }
151  }
152  /* Will never get here */
153}
154
155CURLcode
156Curl_unencode_deflate_write(struct connectdata *conn,
157                            struct SingleRequest *k,
158                            ssize_t nread)
159{
160  z_stream *z = &k->z;          /* zlib state structure */
161
162  /* Initialize zlib? */
163  if(k->zlib_init == ZLIB_UNINIT) {
164    z->zalloc = (alloc_func)Z_NULL;
165    z->zfree = (free_func)Z_NULL;
166    z->opaque = 0;
167    z->next_in = NULL;
168    z->avail_in = 0;
169    if(inflateInit(z) != Z_OK)
170      return process_zlib_error(conn, z);
171    k->zlib_init = ZLIB_INIT;
172  }
173
174  /* Set the compressed input when this function is called */
175  z->next_in = (Bytef *)k->str;
176  z->avail_in = (uInt)nread;
177
178  /* Now uncompress the data */
179  return inflate_stream(conn, k);
180}
181
182#ifdef OLD_ZLIB_SUPPORT
183/* Skip over the gzip header */
184static enum {
185  GZIP_OK,
186  GZIP_BAD,
187  GZIP_UNDERFLOW
188} check_gzip_header(unsigned char const *data, ssize_t len, ssize_t *headerlen)
189{
190  int method, flags;
191  const ssize_t totallen = len;
192
193  /* The shortest header is 10 bytes */
194  if(len < 10)
195    return GZIP_UNDERFLOW;
196
197  if((data[0] != GZIP_MAGIC_0) || (data[1] != GZIP_MAGIC_1))
198    return GZIP_BAD;
199
200  method = data[2];
201  flags = data[3];
202
203  if(method != Z_DEFLATED || (flags & RESERVED) != 0) {
204    /* Can't handle this compression method or unknown flag */
205    return GZIP_BAD;
206  }
207
208  /* Skip over time, xflags, OS code and all previous bytes */
209  len -= 10;
210  data += 10;
211
212  if(flags & EXTRA_FIELD) {
213    ssize_t extra_len;
214
215    if(len < 2)
216      return GZIP_UNDERFLOW;
217
218    extra_len = (data[1] << 8) | data[0];
219
220    if(len < (extra_len+2))
221      return GZIP_UNDERFLOW;
222
223    len -= (extra_len + 2);
224    data += (extra_len + 2);
225  }
226
227  if(flags & ORIG_NAME) {
228    /* Skip over NUL-terminated file name */
229    while(len && *data) {
230      --len;
231      ++data;
232    }
233    if(!len || *data)
234      return GZIP_UNDERFLOW;
235
236    /* Skip over the NUL */
237    --len;
238    ++data;
239  }
240
241  if(flags & COMMENT) {
242    /* Skip over NUL-terminated comment */
243    while(len && *data) {
244      --len;
245      ++data;
246    }
247    if(!len || *data)
248      return GZIP_UNDERFLOW;
249
250    /* Skip over the NUL */
251    --len;
252  }
253
254  if(flags & HEAD_CRC) {
255    if(len < 2)
256      return GZIP_UNDERFLOW;
257
258    len -= 2;
259  }
260
261  *headerlen = totallen - len;
262  return GZIP_OK;
263}
264#endif
265
266CURLcode
267Curl_unencode_gzip_write(struct connectdata *conn,
268                         struct SingleRequest *k,
269                         ssize_t nread)
270{
271  z_stream *z = &k->z;          /* zlib state structure */
272
273  /* Initialize zlib? */
274  if(k->zlib_init == ZLIB_UNINIT) {
275    z->zalloc = (alloc_func)Z_NULL;
276    z->zfree = (free_func)Z_NULL;
277    z->opaque = 0;
278    z->next_in = NULL;
279    z->avail_in = 0;
280
281    if(strcmp(zlibVersion(), "1.2.0.4") >= 0) {
282      /* zlib ver. >= 1.2.0.4 supports transparent gzip decompressing */
283      if(inflateInit2(z, MAX_WBITS+32) != Z_OK) {
284        return process_zlib_error(conn, z);
285      }
286      k->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
287    }
288    else {
289      /* we must parse the gzip header ourselves */
290      if(inflateInit2(z, -MAX_WBITS) != Z_OK) {
291        return process_zlib_error(conn, z);
292      }
293      k->zlib_init = ZLIB_INIT;   /* Initial call state */
294    }
295  }
296
297  if(k->zlib_init == ZLIB_INIT_GZIP) {
298    /* Let zlib handle the gzip decompression entirely */
299    z->next_in = (Bytef *)k->str;
300    z->avail_in = (uInt)nread;
301    /* Now uncompress the data */
302    return inflate_stream(conn, k);
303  }
304
305#ifndef OLD_ZLIB_SUPPORT
306  /* Support for old zlib versions is compiled away and we are running with
307     an old version, so return an error. */
308  return exit_zlib(z, &k->zlib_init, CURLE_FUNCTION_NOT_FOUND);
309
310#else
311  /* This next mess is to get around the potential case where there isn't
312   * enough data passed in to skip over the gzip header.  If that happens, we
313   * malloc a block and copy what we have then wait for the next call.  If
314   * there still isn't enough (this is definitely a worst-case scenario), we
315   * make the block bigger, copy the next part in and keep waiting.
316   *
317   * This is only required with zlib versions < 1.2.0.4 as newer versions
318   * can handle the gzip header themselves.
319   */
320
321  switch (k->zlib_init) {
322  /* Skip over gzip header? */
323  case ZLIB_INIT:
324  {
325    /* Initial call state */
326    ssize_t hlen;
327
328    switch (check_gzip_header((unsigned char *)k->str, nread, &hlen)) {
329    case GZIP_OK:
330      z->next_in = (Bytef *)k->str + hlen;
331      z->avail_in = (uInt)(nread - hlen);
332      k->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */
333      break;
334
335    case GZIP_UNDERFLOW:
336      /* We need more data so we can find the end of the gzip header.  It's
337       * possible that the memory block we malloc here will never be freed if
338       * the transfer abruptly aborts after this point.  Since it's unlikely
339       * that circumstances will be right for this code path to be followed in
340       * the first place, and it's even more unlikely for a transfer to fail
341       * immediately afterwards, it should seldom be a problem.
342       */
343      z->avail_in = (uInt)nread;
344      z->next_in = malloc(z->avail_in);
345      if(z->next_in == NULL) {
346        return exit_zlib(z, &k->zlib_init, CURLE_OUT_OF_MEMORY);
347      }
348      memcpy(z->next_in, k->str, z->avail_in);
349      k->zlib_init = ZLIB_GZIP_HEADER;   /* Need more gzip header data state */
350      /* We don't have any data to inflate yet */
351      return CURLE_OK;
352
353    case GZIP_BAD:
354    default:
355      return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
356    }
357
358  }
359  break;
360
361  case ZLIB_GZIP_HEADER:
362  {
363    /* Need more gzip header data state */
364    ssize_t hlen;
365    unsigned char *oldblock = z->next_in;
366
367    z->avail_in += (uInt)nread;
368    z->next_in = realloc(z->next_in, z->avail_in);
369    if(z->next_in == NULL) {
370      free(oldblock);
371      return exit_zlib(z, &k->zlib_init, CURLE_OUT_OF_MEMORY);
372    }
373    /* Append the new block of data to the previous one */
374    memcpy(z->next_in + z->avail_in - nread, k->str, nread);
375
376    switch (check_gzip_header(z->next_in, z->avail_in, &hlen)) {
377    case GZIP_OK:
378      /* This is the zlib stream data */
379      free(z->next_in);
380      /* Don't point into the malloced block since we just freed it */
381      z->next_in = (Bytef *)k->str + hlen + nread - z->avail_in;
382      z->avail_in = (uInt)(z->avail_in - hlen);
383      k->zlib_init = ZLIB_GZIP_INFLATING;   /* Inflating stream state */
384      break;
385
386    case GZIP_UNDERFLOW:
387      /* We still don't have any data to inflate! */
388      return CURLE_OK;
389
390    case GZIP_BAD:
391    default:
392      free(z->next_in);
393      return exit_zlib(z, &k->zlib_init, process_zlib_error(conn, z));
394    }
395
396  }
397  break;
398
399  case ZLIB_GZIP_INFLATING:
400  default:
401    /* Inflating stream state */
402    z->next_in = (Bytef *)k->str;
403    z->avail_in = (uInt)nread;
404    break;
405  }
406
407  if(z->avail_in == 0) {
408    /* We don't have any data to inflate; wait until next time */
409    return CURLE_OK;
410  }
411
412  /* We've parsed the header, now uncompress the data */
413  return inflate_stream(conn, k);
414#endif
415}
416
417void Curl_unencode_cleanup(struct connectdata *conn)
418{
419  struct SessionHandle *data = conn->data;
420  struct SingleRequest *k = &data->req;
421  z_stream *z = &k->z;
422  if(k->zlib_init != ZLIB_UNINIT)
423    (void) exit_zlib(z, &k->zlib_init, CURLE_OK);
424}
425
426#endif /* HAVE_LIBZ */
427