2 // System.Net.ChunkStream
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Globalization;
53 public Chunk (byte [] chunk)
58 public int Read (byte [] buffer, int offset, int size)
60 int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
61 Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
67 internal WebHeaderCollection headers;
79 public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
82 Write (buffer, offset, size);
85 public ChunkStream (WebHeaderCollection headers)
87 this.headers = headers;
88 saved = new StringBuilder ();
89 chunks = new ArrayList ();
94 public void ResetBuffer ()
102 public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
104 if (offset + read > 0)
105 Write (buffer, offset, offset+read);
106 read = Read (buffer, offset, size);
109 public int Read (byte [] buffer, int offset, int size)
111 return ReadFromChunks (buffer, offset, size);
114 int ReadFromChunks (byte [] buffer, int offset, int size)
116 int count = chunks.Count;
119 var chunksForRemoving = new List<Chunk>(count);
120 for (int i = 0; i < count; i++) {
121 Chunk chunk = (Chunk) chunks [i];
123 if (chunk.Offset == chunk.Bytes.Length) {
124 chunksForRemoving.Add(chunk);
128 nread += chunk.Read (buffer, offset + nread, size - nread);
133 foreach (var chunk in chunksForRemoving)
134 chunks.Remove(chunk);
139 public void Write (byte [] buffer, int offset, int size)
142 InternalWrite (buffer, ref offset, size);
145 void InternalWrite (byte [] buffer, ref int offset, int size)
147 if (state == State.None || state == State.PartialSize) {
148 state = GetChunkSize (buffer, ref offset, size);
149 if (state == State.PartialSize)
157 if (state == State.Body && offset < size) {
158 state = ReadBody (buffer, ref offset, size);
159 if (state == State.Body)
163 if (state == State.BodyFinished && offset < size) {
164 state = ReadCRLF (buffer, ref offset, size);
165 if (state == State.BodyFinished)
171 if (state == State.Trailer && offset < size) {
172 state = ReadTrailer (buffer, ref offset, size);
173 if (state == State.Trailer)
182 InternalWrite (buffer, ref offset, size);
185 public bool WantMore {
186 get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); }
189 public bool DataAvailable {
191 int count = chunks.Count;
192 for (int i = 0; i < count; i++) {
193 Chunk ch = (Chunk) chunks [i];
194 if (ch == null || ch.Bytes == null)
196 if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
197 return (state != State.Body);
203 public int TotalDataSize {
204 get { return totalWritten; }
207 public int ChunkLeft {
208 get { return chunkSize - chunkRead; }
211 State ReadBody (byte [] buffer, ref int offset, int size)
214 return State.BodyFinished;
216 int diff = size - offset;
217 if (diff + chunkRead > chunkSize)
218 diff = chunkSize - chunkRead;
220 byte [] chunk = new byte [diff];
221 Buffer.BlockCopy (buffer, offset, chunk, 0, diff);
222 chunks.Add (new Chunk (chunk));
225 totalWritten += diff;
226 return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
230 State GetChunkSize (byte [] buffer, ref int offset, int size)
235 while (offset < size) {
236 c = (char) buffer [offset++];
239 ThrowProtocolViolation ("2 CR found");
245 if (sawCR && c == '\n')
254 if (saved.Length > 20)
255 ThrowProtocolViolation ("chunk size too long.");
258 if (!sawCR || c != '\n') {
260 ThrowProtocolViolation ("Missing \\n");
263 if (saved.Length > 0) {
264 chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
266 } catch (Exception) {
267 ThrowProtocolViolation ("Cannot parse chunk size.");
270 return State.PartialSize;
275 chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
276 } catch (Exception) {
277 ThrowProtocolViolation ("Cannot parse chunk size.");
280 if (chunkSize == 0) {
282 return State.Trailer;
288 static string RemoveChunkExtension (string input)
290 int idx = input.IndexOf (';');
293 return input.Substring (0, idx);
296 State ReadCRLF (byte [] buffer, ref int offset, int size)
299 if ((char) buffer [offset++] != '\r')
300 ThrowProtocolViolation ("Expecting \\r");
304 return State.BodyFinished;
307 if (sawCR && (char) buffer [offset++] != '\n')
308 ThrowProtocolViolation ("Expecting \\n");
313 State ReadTrailer (byte [] buffer, ref int offset, int size)
318 if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) {
320 if (offset < size && (char) buffer [offset] == '\n') {
327 int st = trailerState;
328 string stString = "\r\n\r";
329 while (offset < size && st < 4) {
330 c = (char) buffer [offset++];
331 if ((st == 0 || st == 2) && c == '\r') {
336 if ((st == 1 || st == 3) && c == '\n') {
342 saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
344 if (saved.Length > 4196)
345 ThrowProtocolViolation ("Error reading trailer (too long).");
352 ThrowProtocolViolation ("Error reading trailer.");
354 return State.Trailer;
357 StringReader reader = new StringReader (saved.ToString ());
359 while ((line = reader.ReadLine ()) != null && line != "")
365 static void ThrowProtocolViolation (string message)
367 WebException we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);