2010-03-12 Jb Evain <jbevain@novell.com>
[mono.git] / mcs / class / System / System.Net / ChunkStream.cs
1 //
2 // System.Net.ChunkStream
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System.Collections;
32 using System.Globalization;
33 using System.IO;
34 using System.Text;
35
36 namespace System.Net
37 {
38         class ChunkStream
39         {
40                 enum State {
41                         None,
42                         Body,
43                         BodyFinished,
44                         Trailer
45                 }
46
47                 class Chunk {
48                         public byte [] Bytes;
49                         public int Offset;
50
51                         public Chunk (byte [] chunk)
52                         {
53                                 this.Bytes = chunk;
54                         }
55
56                         public int Read (byte [] buffer, int offset, int size)
57                         {
58                                 int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
59                                 Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
60                                 Offset += nread;
61                                 return nread;
62                         }
63                 }
64
65                 internal WebHeaderCollection headers;
66                 int chunkSize;
67                 int chunkRead;
68                 State state;
69                 //byte [] waitBuffer;
70                 StringBuilder saved;
71                 bool sawCR;
72                 bool gotit;
73                 int trailerState;
74                 ArrayList chunks;
75                 
76                 public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
77                                         : this (headers)
78                 {
79                         Write (buffer, offset, size);
80                 }
81
82                 public ChunkStream (WebHeaderCollection headers)
83                 {
84                         this.headers = headers;
85                         saved = new StringBuilder ();
86                         chunks = new ArrayList ();
87                         chunkSize = -1;
88                 }
89
90                 public void ResetBuffer ()
91                 {
92                         chunkSize = -1;
93                         chunkRead = 0;
94                         chunks.Clear ();
95                 }
96                 
97                 public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
98                 {
99                         if (offset + read > 0)
100                                 Write (buffer, offset, offset+read);
101                         read = Read (buffer, offset, size);
102                 }
103
104                 public int Read (byte [] buffer, int offset, int size)
105                 {
106                         return ReadFromChunks (buffer, offset, size);
107                 }
108
109                 int ReadFromChunks (byte [] buffer, int offset, int size)
110                 {
111                         int count = chunks.Count;
112                         int nread = 0;
113                         for (int i = 0; i < count; i++) {
114                                 Chunk chunk = (Chunk) chunks [i];
115                                 if (chunk == null)
116                                         continue;
117
118                                 if (chunk.Offset == chunk.Bytes.Length) {
119                                         chunks [i] = null;
120                                         continue;
121                                 }
122                                 
123                                 nread += chunk.Read (buffer, offset + nread, size - nread);
124                                 if (nread == size)
125                                         break;
126                         }
127
128                         return nread;
129                 }
130                 
131                 public void Write (byte [] buffer, int offset, int size)
132                 {
133                         InternalWrite (buffer, ref offset, size);
134                 }
135                 
136                 void InternalWrite (byte [] buffer, ref int offset, int size)
137                 {
138                         if (state == State.None) {
139                                 state = GetChunkSize (buffer, ref offset, size);
140                                 if (state == State.None)
141                                         return;
142                                 
143                                 saved.Length = 0;
144                                 sawCR = false;
145                                 gotit = false;
146                         }
147                         
148                         if (state == State.Body && offset < size) {
149                                 state = ReadBody (buffer, ref offset, size);
150                                 if (state == State.Body)
151                                         return;
152                         }
153                         
154                         if (state == State.BodyFinished && offset < size) {
155                                 state = ReadCRLF (buffer, ref offset, size);
156                                 if (state == State.BodyFinished)
157                                         return;
158
159                                 sawCR = false;
160                         }
161                         
162                         if (state == State.Trailer && offset < size) {
163                                 state = ReadTrailer (buffer, ref offset, size);
164                                 if (state == State.Trailer)
165                                         return;
166
167                                 saved.Length = 0;
168                                 sawCR = false;
169                                 gotit = false;
170                         }
171
172                         if (offset < size)
173                                 InternalWrite (buffer, ref offset, size);
174                 }
175
176                 public bool WantMore {
177                         get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); }
178                 }
179
180                 public int ChunkLeft {
181                         get { return chunkSize - chunkRead; }
182                 }
183                 
184                 State ReadBody (byte [] buffer, ref int offset, int size)
185                 {
186                         if (chunkSize == 0)
187                                 return State.BodyFinished;
188
189                         int diff = size - offset;
190                         if (diff + chunkRead > chunkSize)
191                                 diff = chunkSize - chunkRead;
192
193                         byte [] chunk = new byte [diff];
194                         Buffer.BlockCopy (buffer, offset, chunk, 0, diff);
195                         chunks.Add (new Chunk (chunk));
196                         offset += diff;
197                         chunkRead += diff;
198                         return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
199                                 
200                 }
201                 
202                 State GetChunkSize (byte [] buffer, ref int offset, int size)
203                 {
204                         char c = '\0';
205                         while (offset < size) {
206                                 c = (char) buffer [offset++];
207                                 if (c == '\r') {
208                                         if (sawCR)
209                                                 ThrowProtocolViolation ("2 CR found");
210
211                                         sawCR = true;
212                                         continue;
213                                 }
214                                 
215                                 if (sawCR && c == '\n')
216                                         break;
217
218                                 if (c == ' ')
219                                         gotit = true;
220
221                                 if (!gotit)
222                                         saved.Append (c);
223
224                                 if (saved.Length > 20)
225                                         ThrowProtocolViolation ("chunk size too long.");
226                         }
227
228                         if (!sawCR || c != '\n') {
229                                 if (offset < size)
230                                         ThrowProtocolViolation ("Missing \\n");
231
232                                 try {
233                                         if (saved.Length > 0)
234                                                 chunkSize = Int32.Parse (saved.ToString (), NumberStyles.HexNumber);
235                                 } catch (Exception) {
236                                         ThrowProtocolViolation ("Cannot parse chunk size.");
237                                 }
238
239                                 return State.None;
240                         }
241
242                         chunkRead = 0;
243                         try {
244                                 chunkSize = Int32.Parse (saved.ToString (), NumberStyles.HexNumber);
245                         } catch (Exception) {
246                                 ThrowProtocolViolation ("Cannot parse chunk size.");
247                         }
248                         
249                         if (chunkSize == 0) {
250                                 trailerState = 2;
251                                 return State.Trailer;
252                         }
253
254                         return State.Body;
255                 }
256
257                 State ReadCRLF (byte [] buffer, ref int offset, int size)
258                 {
259                         if (!sawCR) {
260                                 if ((char) buffer [offset++] != '\r')
261                                         ThrowProtocolViolation ("Expecting \\r");
262
263                                 sawCR = true;
264                                 if (offset == size)
265                                         return State.BodyFinished;
266                         }
267                         
268                         if (sawCR && (char) buffer [offset++] != '\n')
269                                 ThrowProtocolViolation ("Expecting \\n");
270
271                         return State.None;
272                 }
273
274                 State ReadTrailer (byte [] buffer, ref int offset, int size)
275                 {
276                         char c = '\0';
277
278                         // short path
279                         if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) {
280                                 offset++;
281                                 if (offset < size && (char) buffer [offset] == '\n') {
282                                         offset++;
283                                         return State.None;
284                                 }
285                                 offset--;
286                         }
287                         
288                         int st = trailerState;
289                         string stString = "\r\n\r";
290                         while (offset < size && st < 4) {
291                                 c = (char) buffer [offset++];
292                                 if ((st == 0 || st == 2) && c == '\r') {
293                                         st++;
294                                         continue;
295                                 }
296
297                                 if ((st == 1 || st == 3) && c == '\n') {
298                                         st++;
299                                         continue;
300                                 }
301
302                                 if (st > 0) {
303                                         saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
304                                         st = 0;
305                                 }
306                         }
307
308                         if (st < 4) {
309                                 trailerState = st;
310                                 if (offset <  size)
311                                         ThrowProtocolViolation ("Error reading trailer.");
312
313                                 return State.Trailer;
314                         }
315
316                         StringReader reader = new StringReader (saved.ToString ());
317                         string line;
318                         while ((line = reader.ReadLine ()) != null && line != "")
319                                 headers.Add (line);
320
321                         return State.None;
322                 }
323
324                 static void ThrowProtocolViolation (string message)
325                 {
326                         WebException we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
327                         throw we;
328                 }
329         }
330 }
331