Git init
[external/curl.git] / lib / http_chunks.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 #include "setup.h"
23
24 #ifndef CURL_DISABLE_HTTP
25 /* -- WIN32 approved -- */
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <ctype.h>
31
32 #include "urldata.h" /* it includes http_chunks.h */
33 #include "sendf.h"   /* for the client write stuff */
34
35 #include "content_encoding.h"
36 #include "http.h"
37 #include "curl_memory.h"
38 #include "easyif.h" /* for Curl_convert_to_network prototype */
39
40 #define _MPRINTF_REPLACE /* use our functions only */
41 #include <curl/mprintf.h>
42
43 /* The last #include file should be: */
44 #include "memdebug.h"
45
46 /*
47  * Chunk format (simplified):
48  *
49  * <HEX SIZE>[ chunk extension ] CRLF
50  * <DATA> CRLF
51  *
52  * Highlights from RFC2616 section 3.6 say:
53
54    The chunked encoding modifies the body of a message in order to
55    transfer it as a series of chunks, each with its own size indicator,
56    followed by an OPTIONAL trailer containing entity-header fields. This
57    allows dynamically produced content to be transferred along with the
58    information necessary for the recipient to verify that it has
59    received the full message.
60
61        Chunked-Body   = *chunk
62                         last-chunk
63                         trailer
64                         CRLF
65
66        chunk          = chunk-size [ chunk-extension ] CRLF
67                         chunk-data CRLF
68        chunk-size     = 1*HEX
69        last-chunk     = 1*("0") [ chunk-extension ] CRLF
70
71        chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
72        chunk-ext-name = token
73        chunk-ext-val  = token | quoted-string
74        chunk-data     = chunk-size(OCTET)
75        trailer        = *(entity-header CRLF)
76
77    The chunk-size field is a string of hex digits indicating the size of
78    the chunk. The chunked encoding is ended by any chunk whose size is
79    zero, followed by the trailer, which is terminated by an empty line.
80
81  */
82
83 /* Check for an ASCII hex digit.
84  We avoid the use of isxdigit to accommodate non-ASCII hosts. */
85 static bool Curl_isxdigit(char digit)
86 {
87   return (bool)( (digit >= 0x30 && digit <= 0x39)    /* 0-9 */
88               || (digit >= 0x41 && digit <= 0x46)    /* A-F */
89               || (digit >= 0x61 && digit <= 0x66) ); /* a-f */
90 }
91
92 void Curl_httpchunk_init(struct connectdata *conn)
93 {
94   struct Curl_chunker *chunk = &conn->chunk;
95   chunk->hexindex=0; /* start at 0 */
96   chunk->dataleft=0; /* no data left yet! */
97   chunk->state = CHUNK_HEX; /* we get hex first! */
98 }
99
100 /*
101  * chunk_read() returns a OK for normal operations, or a positive return code
102  * for errors. STOP means this sequence of chunks is complete.  The 'wrote'
103  * argument is set to tell the caller how many bytes we actually passed to the
104  * client (for byte-counting and whatever).
105  *
106  * The states and the state-machine is further explained in the header file.
107  *
108  * This function always uses ASCII hex values to accommodate non-ASCII hosts.
109  * For example, 0x0d and 0x0a are used instead of '\r' and '\n'.
110  */
111 CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
112                               char *datap,
113                               ssize_t datalen,
114                               ssize_t *wrotep)
115 {
116   CURLcode result=CURLE_OK;
117   struct SessionHandle *data = conn->data;
118   struct Curl_chunker *ch = &conn->chunk;
119   struct SingleRequest *k = &data->req;
120   size_t piece;
121   size_t length = (size_t)datalen;
122   size_t *wrote = (size_t *)wrotep;
123
124   *wrote = 0; /* nothing's written yet */
125
126   /* the original data is written to the client, but we go on with the
127      chunk read process, to properly calculate the content length*/
128   if(data->set.http_te_skip && !k->ignorebody) {
129     result = Curl_client_write(conn, CLIENTWRITE_BODY, datap, datalen);
130     if(result)
131       return CHUNKE_WRITE_ERROR;
132   }
133
134   while(length) {
135     switch(ch->state) {
136     case CHUNK_HEX:
137       if(Curl_isxdigit(*datap)) {
138         if(ch->hexindex < MAXNUM_SIZE) {
139           ch->hexbuffer[ch->hexindex] = *datap;
140           datap++;
141           length--;
142           ch->hexindex++;
143         }
144         else {
145           return CHUNKE_TOO_LONG_HEX; /* longer hex than we support */
146         }
147       }
148       else {
149         if(0 == ch->hexindex) {
150           /* This is illegal data, we received junk where we expected
151              a hexadecimal digit. */
152           return CHUNKE_ILLEGAL_HEX;
153         }
154         /* length and datap are unmodified */
155         ch->hexbuffer[ch->hexindex]=0;
156 #ifdef CURL_DOES_CONVERSIONS
157         /* convert to host encoding before calling strtoul */
158         result = Curl_convert_from_network(conn->data,
159                                            ch->hexbuffer,
160                                            ch->hexindex);
161         if(result != CURLE_OK) {
162           /* Curl_convert_from_network calls failf if unsuccessful */
163           /* Treat it as a bad hex character */
164           return(CHUNKE_ILLEGAL_HEX);
165         }
166 #endif /* CURL_DOES_CONVERSIONS */
167         ch->datasize=strtoul(ch->hexbuffer, NULL, 16);
168         ch->state = CHUNK_POSTHEX;
169       }
170       break;
171
172     case CHUNK_POSTHEX:
173       /* In this state, we're waiting for CRLF to arrive. We support
174          this to allow so called chunk-extensions to show up here
175          before the CRLF comes. */
176       if(*datap == 0x0d)
177         ch->state = CHUNK_CR;
178       length--;
179       datap++;
180       break;
181
182     case CHUNK_CR:
183       /* waiting for the LF */
184       if(*datap == 0x0a) {
185         /* we're now expecting data to come, unless size was zero! */
186         if(0 == ch->datasize) {
187           ch->state = CHUNK_TRAILER; /* now check for trailers */
188           conn->trlPos=0;
189         }
190         else {
191           ch->state = CHUNK_DATA;
192         }
193       }
194       else
195         /* previously we got a fake CR, go back to CR waiting! */
196         ch->state = CHUNK_CR;
197       datap++;
198       length--;
199       break;
200
201     case CHUNK_DATA:
202       /* we get pure and fine data
203
204          We expect another 'datasize' of data. We have 'length' right now,
205          it can be more or less than 'datasize'. Get the smallest piece.
206       */
207       piece = (ch->datasize >= length)?length:ch->datasize;
208
209       /* Write the data portion available */
210 #ifdef HAVE_LIBZ
211       switch (conn->data->set.http_ce_skip?
212               IDENTITY : data->req.content_encoding) {
213       case IDENTITY:
214 #endif
215         if(!k->ignorebody) {
216           if( !data->set.http_te_skip )
217             result = Curl_client_write(conn, CLIENTWRITE_BODY, datap,
218                                        piece);
219           else
220             result = CURLE_OK;
221         }
222 #ifdef HAVE_LIBZ
223         break;
224
225       case DEFLATE:
226         /* update data->req.keep.str to point to the chunk data. */
227         data->req.str = datap;
228         result = Curl_unencode_deflate_write(conn, &data->req,
229                                              (ssize_t)piece);
230         break;
231
232       case GZIP:
233         /* update data->req.keep.str to point to the chunk data. */
234         data->req.str = datap;
235         result = Curl_unencode_gzip_write(conn, &data->req,
236                                           (ssize_t)piece);
237         break;
238
239       case COMPRESS:
240       default:
241         failf (conn->data,
242                "Unrecognized content encoding type. "
243                "libcurl understands `identity', `deflate' and `gzip' "
244                "content encodings.");
245         return CHUNKE_BAD_ENCODING;
246       }
247 #endif
248
249       if(result)
250         return CHUNKE_WRITE_ERROR;
251
252       *wrote += piece;
253
254       ch->datasize -= piece; /* decrease amount left to expect */
255       datap += piece;    /* move read pointer forward */
256       length -= piece;   /* decrease space left in this round */
257
258       if(0 == ch->datasize)
259         /* end of data this round, we now expect a trailing CRLF */
260         ch->state = CHUNK_POSTCR;
261       break;
262
263     case CHUNK_POSTCR:
264       if(*datap == 0x0d) {
265         ch->state = CHUNK_POSTLF;
266         datap++;
267         length--;
268       }
269       else
270         return CHUNKE_BAD_CHUNK;
271
272       break;
273
274     case CHUNK_POSTLF:
275       if(*datap == 0x0a) {
276         /*
277          * The last one before we go back to hex state and start all
278          * over.
279          */
280         Curl_httpchunk_init(conn);
281         datap++;
282         length--;
283       }
284       else
285         return CHUNKE_BAD_CHUNK;
286
287       break;
288
289     case CHUNK_TRAILER:
290       if(*datap == 0x0d) {
291         /* this is the end of a trailer, but if the trailer was zero bytes
292            there was no trailer and we move on */
293
294         if(conn->trlPos) {
295           /* we allocate trailer with 3 bytes extra room to fit this */
296           conn->trailer[conn->trlPos++]=0x0d;
297           conn->trailer[conn->trlPos++]=0x0a;
298           conn->trailer[conn->trlPos]=0;
299
300 #ifdef CURL_DOES_CONVERSIONS
301           /* Convert to host encoding before calling Curl_client_write */
302           result = Curl_convert_from_network(conn->data,
303                                              conn->trailer,
304                                              conn->trlPos);
305           if(result != CURLE_OK)
306             /* Curl_convert_from_network calls failf if unsuccessful */
307             /* Treat it as a bad chunk */
308             return CHUNKE_BAD_CHUNK;
309
310 #endif /* CURL_DOES_CONVERSIONS */
311           if(!data->set.http_te_skip) {
312             result = Curl_client_write(conn, CLIENTWRITE_HEADER,
313                                        conn->trailer, conn->trlPos);
314             if(result)
315               return CHUNKE_WRITE_ERROR;
316           }
317           conn->trlPos=0;
318           ch->state = CHUNK_TRAILER_CR;
319         }
320         else {
321           /* no trailer, we're on the final CRLF pair */
322           ch->state = CHUNK_TRAILER_POSTCR;
323           break; /* don't advance the pointer */
324         }
325       }
326       else {
327         /* conn->trailer is assumed to be freed in url.c on a
328            connection basis */
329         if(conn->trlPos >= conn->trlMax) {
330           /* we always allocate three extra bytes, just because when the full
331              header has been received we append CRLF\0 */
332           char *ptr;
333           if(conn->trlMax) {
334             conn->trlMax *= 2;
335             ptr = realloc(conn->trailer, conn->trlMax + 3);
336           }
337           else {
338             conn->trlMax=128;
339             ptr = malloc(conn->trlMax + 3);
340           }
341           if(!ptr)
342             return CHUNKE_OUT_OF_MEMORY;
343           conn->trailer = ptr;
344         }
345         conn->trailer[conn->trlPos++]=*datap;
346       }
347       datap++;
348       length--;
349       break;
350
351     case CHUNK_TRAILER_CR:
352       if(*datap == 0x0a) {
353         ch->state = CHUNK_TRAILER_POSTCR;
354         datap++;
355         length--;
356       }
357       else
358         return CHUNKE_BAD_CHUNK;
359       break;
360
361     case CHUNK_TRAILER_POSTCR:
362       /* We enter this state when a CR should arrive so we expect to
363          have to first pass a CR before we wait for LF */
364       if(*datap != 0x0d) {
365         /* not a CR then it must be another header in the trailer */
366         ch->state = CHUNK_TRAILER;
367         break;
368       }
369       datap++;
370       length--;
371       /* now wait for the final LF */
372       ch->state = CHUNK_STOP;
373       break;
374
375     case CHUNK_STOPCR:
376       /* Read the final CRLF that ends all chunk bodies */
377
378       if(*datap == 0x0d) {
379         ch->state = CHUNK_STOP;
380         datap++;
381         length--;
382       }
383       else
384         return CHUNKE_BAD_CHUNK;
385       break;
386
387     case CHUNK_STOP:
388       if(*datap == 0x0a) {
389         length--;
390
391         /* Record the length of any data left in the end of the buffer
392            even if there's no more chunks to read */
393
394         ch->dataleft = length;
395         return CHUNKE_STOP; /* return stop */
396       }
397       else
398         return CHUNKE_BAD_CHUNK;
399
400     default:
401       return CHUNKE_STATE_ERROR;
402     }
403   }
404   return CHUNKE_OK;
405 }
406 #endif /* CURL_DISABLE_HTTP */