chunked transfer encoding support
[platform/upstream/curl.git] / lib / http_chunks.c
1 /*****************************************************************************
2  *                                  _   _ ____  _     
3  *  Project                     ___| | | |  _ \| |    
4  *                             / __| | | | |_) | |    
5  *                            | (__| |_| |  _ <| |___ 
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2001, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * In order to be useful for every potential user, curl and libcurl are
11  * dual-licensed under the MPL and the MIT/X-derivate licenses.
12  *
13  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
14  * copies of the Software, and permit persons to whom the Software is
15  * furnished to do so, under the terms of the MPL or the MIT/X-derivate
16  * licenses. You may pick one of these licenses.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  *****************************************************************************/
23 #include "setup.h"
24
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 #define _MPRINTF_REPLACE /* use our functions only */
36 #include <curl/mprintf.h>
37
38 /* The last #include file should be: */
39 #ifdef MALLOCDEBUG
40 #include "memdebug.h"
41 #endif
42
43 /* 
44  * Chunk format (simplified):
45  *
46  * <HEX SIZE>[ chunk extension ] CRLF
47  * <DATA>
48  *
49  * Highlights from RFC2616 section 3.6 say:
50
51    The chunked encoding modifies the body of a message in order to
52    transfer it as a series of chunks, each with its own size indicator,
53    followed by an OPTIONAL trailer containing entity-header fields. This
54    allows dynamically produced content to be transferred along with the
55    information necessary for the recipient to verify that it has
56    received the full message.
57
58        Chunked-Body   = *chunk
59                         last-chunk
60                         trailer
61                         CRLF
62
63        chunk          = chunk-size [ chunk-extension ] CRLF
64                         chunk-data CRLF
65        chunk-size     = 1*HEX
66        last-chunk     = 1*("0") [ chunk-extension ] CRLF
67
68        chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
69        chunk-ext-name = token
70        chunk-ext-val  = token | quoted-string
71        chunk-data     = chunk-size(OCTET)
72        trailer        = *(entity-header CRLF)
73
74    The chunk-size field is a string of hex digits indicating the size of
75    the chunk. The chunked encoding is ended by any chunk whose size is
76    zero, followed by the trailer, which is terminated by an empty line.
77
78  */
79
80
81 void Curl_httpchunk_init(struct connectdata *conn)
82 {
83   struct Curl_chunker *chunk = &conn->proto.http->chunk;
84   chunk->hexindex=0; /* start at 0 */
85   chunk->state = CHUNK_HEX; /* we get hex first! */
86 }
87
88 /*
89  * chunk_read() returns a 0 for normal operations, or a positive return code
90  * for errors. A negative number means this sequence of chunks is complete,
91  * and that many ~bytes were NOT used at the end of the buffer passed in.
92  * The 'wrote' argument is set to tell the caller how many bytes we actually
93  * passed to the client (for byte-counting and whatever).
94  *
95  * The states and the state-machine is further explained in the header file.
96  */
97 CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
98                               char *datap,
99                               ssize_t length,
100                               ssize_t *wrote)
101 {
102   CURLcode result;
103   struct Curl_chunker *ch = &conn->proto.http->chunk;
104   int piece;
105   *wrote = 0; /* nothing yet */
106
107   while(length) {
108     switch(ch->state) {
109     case CHUNK_HEX:
110       if(isxdigit((int)*datap)) {
111         if(ch->hexindex < MAXNUM_SIZE) {
112           ch->hexbuffer[ch->hexindex] = *datap;
113           datap++;
114           length--;
115           ch->hexindex++;
116         }
117         else {
118           return 1; /* longer hex than we support */
119         }
120       }
121       else {
122         /* length and datap are unmodified */
123         ch->hexbuffer[ch->hexindex]=0;
124         ch->datasize=strtoul(ch->hexbuffer, NULL, 16);
125         ch->state = CHUNK_POSTHEX;
126       }
127       break;
128
129     case CHUNK_POSTHEX:
130       /* just a lame state waiting for CRLF to arrive */
131       if(*datap == '\r')
132         ch->state = CHUNK_CR;
133       length--;
134       datap++;
135       break;
136
137     case CHUNK_CR:
138       /* waiting for the LF */
139       if(*datap == '\n') {
140         /* we're now expecting data to come, unless size was zero! */
141         if(0 == ch->datasize) {
142           ch->state = CHUNK_STOP; /* stop reading! */
143           if(1 == length) {
144             /* This was the final byte, return right now */
145             return ~0;
146           }
147         }
148         else
149           ch->state = CHUNK_DATA;
150       }
151       else
152         /* previously we got a fake CR, go back to CR waiting! */
153         ch->state = CHUNK_CR;
154       datap++;
155       length--;
156       break;
157
158     case CHUNK_DATA:
159       /* we get pure and fine data
160
161          We expect another 'datasize' of data. We have 'length' right now,
162          it can be more or less than 'datasize'. Get the smallest piece.
163       */
164       piece = (ch->datasize >= length)?length:ch->datasize;
165
166       /* Write the data portion available */
167       result = Curl_client_write(conn->data, CLIENTWRITE_BODY, datap, piece);
168       if(result)
169         return CHUNKE_WRITE_ERROR;
170       *wrote += piece;
171
172       ch->datasize -= piece; /* decrease amount left to expect */
173       datap += piece;    /* move read pointer forward */
174       length -= piece;   /* decrease space left in this round */
175
176       if(0 == ch->datasize)
177         /* end of data this round, go back to get a new size */
178         Curl_httpchunk_init(conn);
179
180       break;
181     case CHUNK_STOP:
182       return ~length; /* return the data size left */
183     default:
184       return CHUNKE_STATE_ERROR;
185     }
186   }
187   return CHUNKE_OK;
188 }