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.Globalization;
52 public Chunk (byte [] chunk)
57 public int Read (byte [] buffer, int offset, int size)
59 int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
60 Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
66 internal WebHeaderCollection headers;
78 public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
81 Write (buffer, offset, size);
84 public ChunkStream (WebHeaderCollection headers)
86 this.headers = headers;
87 saved = new StringBuilder ();
88 chunks = new ArrayList ();
93 public void ResetBuffer ()
101 public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
103 if (offset + read > 0)
104 Write (buffer, offset, offset+read);
105 read = Read (buffer, offset, size);
108 public int Read (byte [] buffer, int offset, int size)
110 return ReadFromChunks (buffer, offset, size);
113 int ReadFromChunks (byte [] buffer, int offset, int size)
115 int count = chunks.Count;
117 for (int i = 0; i < count; i++) {
118 Chunk chunk = (Chunk) chunks [i];
122 if (chunk.Offset == chunk.Bytes.Length) {
127 nread += chunk.Read (buffer, offset + nread, size - nread);
135 public void Write (byte [] buffer, int offset, int size)
138 InternalWrite (buffer, ref offset, size);
141 void InternalWrite (byte [] buffer, ref int offset, int size)
143 if (state == State.None || state == State.PartialSize) {
144 state = GetChunkSize (buffer, ref offset, size);
145 if (state == State.PartialSize)
153 if (state == State.Body && offset < size) {
154 state = ReadBody (buffer, ref offset, size);
155 if (state == State.Body)
159 if (state == State.BodyFinished && offset < size) {
160 state = ReadCRLF (buffer, ref offset, size);
161 if (state == State.BodyFinished)
167 if (state == State.Trailer && offset < size) {
168 state = ReadTrailer (buffer, ref offset, size);
169 if (state == State.Trailer)
178 InternalWrite (buffer, ref offset, size);
181 public bool WantMore {
182 get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); }
185 public bool DataAvailable {
187 int count = chunks.Count;
188 for (int i = 0; i < count; i++) {
189 Chunk ch = (Chunk) chunks [i];
190 if (ch == null || ch.Bytes == null)
192 if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
193 return (state != State.Body);
199 public int TotalDataSize {
200 get { return totalWritten; }
203 public int ChunkLeft {
204 get { return chunkSize - chunkRead; }
207 State ReadBody (byte [] buffer, ref int offset, int size)
210 return State.BodyFinished;
212 int diff = size - offset;
213 if (diff + chunkRead > chunkSize)
214 diff = chunkSize - chunkRead;
216 byte [] chunk = new byte [diff];
217 Buffer.BlockCopy (buffer, offset, chunk, 0, diff);
218 chunks.Add (new Chunk (chunk));
221 totalWritten += diff;
222 return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
226 State GetChunkSize (byte [] buffer, ref int offset, int size)
231 while (offset < size) {
232 c = (char) buffer [offset++];
235 ThrowProtocolViolation ("2 CR found");
241 if (sawCR && c == '\n')
250 if (saved.Length > 20)
251 ThrowProtocolViolation ("chunk size too long.");
254 if (!sawCR || c != '\n') {
256 ThrowProtocolViolation ("Missing \\n");
259 if (saved.Length > 0) {
260 chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
262 } catch (Exception) {
263 ThrowProtocolViolation ("Cannot parse chunk size.");
266 return State.PartialSize;
271 chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
272 } catch (Exception) {
273 ThrowProtocolViolation ("Cannot parse chunk size.");
276 if (chunkSize == 0) {
278 return State.Trailer;
284 static string RemoveChunkExtension (string input)
286 int idx = input.IndexOf (';');
289 return input.Substring (0, idx);
292 State ReadCRLF (byte [] buffer, ref int offset, int size)
295 if ((char) buffer [offset++] != '\r')
296 ThrowProtocolViolation ("Expecting \\r");
300 return State.BodyFinished;
303 if (sawCR && (char) buffer [offset++] != '\n')
304 ThrowProtocolViolation ("Expecting \\n");
309 State ReadTrailer (byte [] buffer, ref int offset, int size)
314 if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) {
316 if (offset < size && (char) buffer [offset] == '\n') {
323 int st = trailerState;
324 string stString = "\r\n\r";
325 while (offset < size && st < 4) {
326 c = (char) buffer [offset++];
327 if ((st == 0 || st == 2) && c == '\r') {
332 if ((st == 1 || st == 3) && c == '\n') {
338 saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
340 if (saved.Length > 4196)
341 ThrowProtocolViolation ("Error reading trailer (too long).");
348 ThrowProtocolViolation ("Error reading trailer.");
350 return State.Trailer;
353 StringReader reader = new StringReader (saved.ToString ());
355 while ((line = reader.ReadLine ()) != null && line != "")
361 static void ThrowProtocolViolation (string message)
363 WebException we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);