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