2009-08-03 Gonzalo Paniagua Javier <gonzalo@novell.com>
[mono.git] / mcs / class / System / System.Net / ChunkStream.cs
index fed9aafdc31dc597de2de0ede70335c392c98a73..3e4c08f193010c04dfb05cfa6932b09e72b7f320 100644 (file)
@@ -7,6 +7,28 @@
 // (C) 2003 Ximian, Inc (http://www.ximian.com)
 //
 
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections;
 using System.Globalization;
 using System.IO;
 using System.Text;
@@ -22,50 +44,90 @@ namespace System.Net
                        Trailer
                }
 
-               MemoryStream ms;
-               WebHeaderCollection headers;
+               class Chunk {
+                       public byte [] Bytes;
+                       public int Offset;
+
+                       public Chunk (byte [] chunk)
+                       {
+                               this.Bytes = chunk;
+                       }
+
+                       public int Read (byte [] buffer, int offset, int size)
+                       {
+                               int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
+                               Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
+                               Offset += nread;
+                               return nread;
+                       }
+               }
+
+               internal WebHeaderCollection headers;
                int chunkSize;
                int chunkRead;
                State state;
-               byte [] waitBuffer;
+               //byte [] waitBuffer;
                StringBuilder saved;
                bool sawCR;
                bool gotit;
-               long readPosition;
+               int trailerState;
+               ArrayList chunks;
                
                public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
+                                       : this (headers)
+               {
+                       Write (buffer, offset, size);
+               }
+
+               public ChunkStream (WebHeaderCollection headers)
                {
                        this.headers = headers;
-                       ms = new MemoryStream ();
                        saved = new StringBuilder ();
+                       chunks = new ArrayList ();
                        chunkSize = -1;
-                       if (offset < size)
-                               Write (buffer, offset, size);
                }
 
                public void ResetBuffer ()
                {
-                       ms.SetLength (0);
-                       readPosition = 0;
                        chunkSize = -1;
                        chunkRead = 0;
+                       chunks.Clear ();
                }
                
                public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
                {
-                       Write (buffer, offset, read);
+                       if (offset + read > 0)
+                               Write (buffer, offset, offset+read);
                        read = Read (buffer, offset, size);
                }
 
                public int Read (byte [] buffer, int offset, int size)
                {
-                       ms.Position = readPosition;
-                       int r = ms.Read (buffer, offset, size);
-                       readPosition += r;
-                       ms.Position = ms.Length;
-                       return r;
+                       return ReadFromChunks (buffer, offset, size);
                }
 
+               int ReadFromChunks (byte [] buffer, int offset, int size)
+               {
+                       int count = chunks.Count;
+                       int nread = 0;
+                       for (int i = 0; i < count; i++) {
+                               Chunk chunk = (Chunk) chunks [i];
+                               if (chunk == null)
+                                       continue;
+
+                               if (chunk.Offset == chunk.Bytes.Length) {
+                                       chunks [i] = null;
+                                       continue;
+                               }
+                               
+                               nread += chunk.Read (buffer, offset + nread, size - nread);
+                               if (nread == size)
+                                       break;
+                       }
+
+                       return nread;
+               }
+               
                public void Write (byte [] buffer, int offset, int size)
                {
                        InternalWrite (buffer, ref offset, size);
@@ -112,15 +174,11 @@ namespace System.Net
                }
 
                public bool WantMore {
-                       get { return (chunkRead != chunkSize); }
+                       get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); }
                }
-               
-               public bool EOF {
-                       get { return (Available == 0); }
-               }
-               
-               public int Available {
-                       get { return (int) (ms.Length - readPosition); }
+
+               public int ChunkLeft {
+                       get { return chunkSize - chunkRead; }
                }
                
                State ReadBody (byte [] buffer, ref int offset, int size)
@@ -132,7 +190,9 @@ namespace System.Net
                        if (diff + chunkRead > chunkSize)
                                diff = chunkSize - chunkRead;
 
-                       ms.Write (buffer, offset, diff);
+                       byte [] chunk = new byte [diff];
+                       Buffer.BlockCopy (buffer, offset, chunk, 0, diff);
+                       chunks.Add (new Chunk (chunk));
                        offset += diff;
                        chunkRead += diff;
                        return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
@@ -146,7 +206,7 @@ namespace System.Net
                                c = (char) buffer [offset++];
                                if (c == '\r') {
                                        if (sawCR)
-                                               throw new ProtocolViolationException ("2 CR found");
+                                               ThrowProtocolViolation ("2 CR found");
 
                                        sawCR = true;
                                        continue;
@@ -160,15 +220,36 @@ namespace System.Net
 
                                if (!gotit)
                                        saved.Append (c);
+
+                               if (saved.Length > 20)
+                                       ThrowProtocolViolation ("chunk size too long.");
                        }
 
-                       if (!sawCR || c != '\n')
+                       if (!sawCR || c != '\n') {
+                               if (offset < size)
+                                       ThrowProtocolViolation ("Missing \\n");
+
+                               try {
+                                       if (saved.Length > 0)
+                                               chunkSize = Int32.Parse (saved.ToString (), NumberStyles.HexNumber);
+                               } catch (Exception) {
+                                       ThrowProtocolViolation ("Cannot parse chunk size.");
+                               }
+
                                return State.None;
+                       }
 
                        chunkRead = 0;
-                       chunkSize = Int32.Parse (saved.ToString (), NumberStyles.HexNumber);
-                       if (chunkSize == 0)
+                       try {
+                               chunkSize = Int32.Parse (saved.ToString (), NumberStyles.HexNumber);
+                       } catch (Exception) {
+                               ThrowProtocolViolation ("Cannot parse chunk size.");
+                       }
+                       
+                       if (chunkSize == 0) {
+                               trailerState = 2;
                                return State.Trailer;
+                       }
 
                        return State.Body;
                }
@@ -177,15 +258,15 @@ namespace System.Net
                {
                        if (!sawCR) {
                                if ((char) buffer [offset++] != '\r')
-                                       throw new ProtocolViolationException ("Expecting \\r");
+                                       ThrowProtocolViolation ("Expecting \\r");
 
                                sawCR = true;
                                if (offset == size)
                                        return State.BodyFinished;
                        }
                        
-                       if ((char) buffer [offset++] != '\n')
-                               throw new ProtocolViolationException ("Expecting \\n");
+                       if (sawCR && (char) buffer [offset++] != '\n')
+                               ThrowProtocolViolation ("Expecting \\n");
 
                        return State.None;
                }
@@ -193,19 +274,18 @@ namespace System.Net
                State ReadTrailer (byte [] buffer, ref int offset, int size)
                {
                        char c = '\0';
-                       bool empty = false;
 
                        // short path
-                       if ((char) buffer [offset] == '\r') {
+                       if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) {
                                offset++;
-                               if ((char) buffer [offset] == '\n') {
+                               if (offset < size && (char) buffer [offset] == '\n') {
                                        offset++;
                                        return State.None;
                                }
                                offset--;
                        }
                        
-                       int st = 0;
+                       int st = trailerState;
                        string stString = "\r\n\r";
                        while (offset < size && st < 4) {
                                c = (char) buffer [offset++];
@@ -220,13 +300,18 @@ namespace System.Net
                                }
 
                                if (st > 0) {
-                                       saved.Append (stString.Substring (0, st));
+                                       saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
                                        st = 0;
                                }
                        }
 
-                       if (st < 4)
+                       if (st < 4) {
+                               trailerState = st;
+                               if (offset <  size)
+                                       ThrowProtocolViolation ("Error reading trailer.");
+
                                return State.Trailer;
+                       }
 
                        StringReader reader = new StringReader (saved.ToString ());
                        string line;
@@ -235,6 +320,12 @@ namespace System.Net
 
                        return State.None;
                }
+
+               static void ThrowProtocolViolation (string message)
+               {
+                       WebException we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
+                       throw we;
+               }
        }
 }