Chunked read error reporting improvement
[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                         chunkRead = 0;
205                         chunkSize = 0;
206                         char c = '\0';
207                         while (offset < size) {
208                                 c = (char) buffer [offset++];
209                                 if (c == '\r') {
210                                         if (sawCR)
211                                                 ThrowProtocolViolation ("2 CR found");
212
213                                         sawCR = true;
214                                         continue;
215                                 }
216                                 
217                                 if (sawCR && c == '\n')
218                                         break;
219
220                                 if (c == ' ')
221                                         gotit = true;
222
223                                 if (!gotit)
224                                         saved.Append (c);
225
226                                 if (saved.Length > 20)
227                                         ThrowProtocolViolation ("chunk size too long.");
228                         }
229
230                         if (!sawCR || c != '\n') {
231                                 if (offset < size)
232                                         ThrowProtocolViolation ("Missing \\n");
233
234                                 try {
235                                         if (saved.Length > 0) {
236                                                 chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
237                                         }
238                                 } catch (Exception) {
239                                         ThrowProtocolViolation ("Cannot parse chunk size.");
240                                 }
241
242                                 return State.None;
243                         }
244
245                         chunkRead = 0;
246                         try {
247                                 chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
248                         } catch (Exception) {
249                                 ThrowProtocolViolation ("Cannot parse chunk size.");
250                         }
251
252                         if (chunkSize == 0) {
253                                 trailerState = 2;
254                                 return State.Trailer;
255                         }
256
257                         return State.Body;
258                 }
259
260                 static string RemoveChunkExtension (string input)
261                 {
262                         int idx = input.IndexOf (';');
263                         if (idx == -1)
264                                 return input;
265                         return input.Substring (0, idx);
266                 }
267
268                 State ReadCRLF (byte [] buffer, ref int offset, int size)
269                 {
270                         if (!sawCR) {
271                                 if ((char) buffer [offset++] != '\r')
272                                         ThrowProtocolViolation ("Expecting \\r");
273
274                                 sawCR = true;
275                                 if (offset == size)
276                                         return State.BodyFinished;
277                         }
278                         
279                         if (sawCR && (char) buffer [offset++] != '\n')
280                                 ThrowProtocolViolation ("Expecting \\n");
281
282                         return State.None;
283                 }
284
285                 State ReadTrailer (byte [] buffer, ref int offset, int size)
286                 {
287                         char c = '\0';
288
289                         // short path
290                         if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) {
291                                 offset++;
292                                 if (offset < size && (char) buffer [offset] == '\n') {
293                                         offset++;
294                                         return State.None;
295                                 }
296                                 offset--;
297                         }
298                         
299                         int st = trailerState;
300                         string stString = "\r\n\r";
301                         while (offset < size && st < 4) {
302                                 c = (char) buffer [offset++];
303                                 if ((st == 0 || st == 2) && c == '\r') {
304                                         st++;
305                                         continue;
306                                 }
307
308                                 if ((st == 1 || st == 3) && c == '\n') {
309                                         st++;
310                                         continue;
311                                 }
312
313                                 if (st > 0) {
314                                         saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
315                                         st = 0;
316                                         if (saved.Length > 4196)
317                                                 ThrowProtocolViolation ("Error reading trailer (too long).");
318                                 }
319                         }
320
321                         if (st < 4) {
322                                 trailerState = st;
323                                 if (offset < size)
324                                         ThrowProtocolViolation ("Error reading trailer.");
325
326                                 return State.Trailer;
327                         }
328
329                         StringReader reader = new StringReader (saved.ToString ());
330                         string line;
331                         while ((line = reader.ReadLine ()) != null && line != "")
332                                 headers.Add (line);
333
334                         return State.None;
335                 }
336
337                 static void ThrowProtocolViolation (string message)
338                 {
339                         WebException we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
340                         throw we;
341                 }
342         }
343 }
344