2005-04-16 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System / System.Net / WebConnectionStream.cs
index 703f35d42b4096d4750571538043708b1abb811c..70ec0173b2c87caf8824888e64ec657966e4bf4a 100644 (file)
@@ -57,11 +57,14 @@ namespace System.Net
                byte [] headers;
                bool disposed;
                bool headersSent;
+               object locker = new object ();
+               bool initRead;
 
                public WebConnectionStream (WebConnection cnc)
                {
                        isRead = true;
                        pending = new ManualResetEvent (true);
+                       this.request = cnc.Data.request;
                        this.cnc = cnc;
                        string clength = cnc.Data.Headers ["Content-Length"];
                        if (clength != null && clength != "") {
@@ -113,9 +116,16 @@ namespace System.Net
                        get { return (int) writeBuffer.Length; }
                }
 
+               internal void ForceCompletion ()
+               {
+                       nextReadCalled = true;
+                       cnc.NextRead ();
+               }
+               
                internal void CheckComplete ()
                {
-                       if (!nextReadCalled && readBufferSize - readBufferOffset == contentLength) {
+                       bool nrc = nextReadCalled;
+                       if (!nrc && readBufferSize - readBufferOffset == contentLength) {
                                nextReadCalled = true;
                                cnc.NextRead ();
                        }
@@ -123,11 +133,16 @@ namespace System.Net
 
                internal void ReadAll ()
                {
-                       if (!isRead || totalRead >= contentLength || nextReadCalled)
+                       if (!isRead || totalRead >= contentLength || nextReadCalled) {
+                               if (!nextReadCalled) {
+                                       nextReadCalled = true;
+                                       cnc.NextRead ();
+                               }
                                return;
+                       }
 
                        pending.WaitOne ();
-                       lock (this) {
+                       lock (locker) {
                                if (totalRead >= contentLength)
                                        return;
                                
@@ -137,12 +152,18 @@ namespace System.Net
 
                                if (contentLength == Int32.MaxValue) {
                                        MemoryStream ms = new MemoryStream ();
-                                       if (readBuffer != null && diff > 0)
+                                       byte [] buffer = null;
+                                       if (readBuffer != null && diff > 0) {
                                                ms.Write (readBuffer, readBufferOffset, diff);
+                                               if (readBufferSize >= 8192)
+                                                       buffer = readBuffer;
+                                       }
+
+                                       if (buffer == null)
+                                               buffer = new byte [8192];
 
-                                       byte [] buffer = new byte [2048];
                                        int read;
-                                       while ((read = cnc.Read (buffer, 0, 2048)) != 0)
+                                       while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
                                                ms.Write (buffer, 0, read);
 
                                        b = ms.GetBuffer ();
@@ -151,8 +172,12 @@ namespace System.Net
                                } else {
                                        new_size = contentLength - totalRead;
                                        b = new byte [new_size];
-                                       if (readBuffer != null && diff > 0)
+                                       if (readBuffer != null && diff > 0) {
+                                               if (diff > new_size)
+                                                       diff = new_size;
+
                                                Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
+                                       }
                                        
                                        int remaining = new_size - diff;
                                        int r = -1;
@@ -172,12 +197,29 @@ namespace System.Net
 
                        cnc.NextRead ();
                }
-               
-               static void CallbackWrapper (IAsyncResult r)
+
+               void WriteCallbackWrapper (IAsyncResult r)
                {
-                       WebAsyncResult result = (WebAsyncResult) r.AsyncState;
-                       result.InnerAsyncResult = r;
-                       result.DoCallback ();
+                       WebAsyncResult result;
+                       if (r.AsyncState != null) {
+                               result = (WebAsyncResult) r.AsyncState;
+                               result.InnerAsyncResult = r;
+                               result.DoCallback ();
+                       } else {
+                               EndWrite (r);
+                       }
+               }
+
+               void ReadCallbackWrapper (IAsyncResult r)
+               {
+                       WebAsyncResult result;
+                       if (r.AsyncState != null) {
+                               result = (WebAsyncResult) r.AsyncState;
+                               result.InnerAsyncResult = r;
+                               result.DoCallback ();
+                       } else {
+                               EndRead (r);
+                       }
                }
 
                public override int Read (byte [] buffer, int offset, int size)
@@ -188,7 +230,13 @@ namespace System.Net
                        if (totalRead >= contentLength)
                                return 0;
 
-                       IAsyncResult res = BeginRead (buffer, offset, size, null, null);
+                       AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
+                       WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
+                       if (!res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
+                               cnc.Close (true);
+                               throw new IOException ("Read timed out.");
+                       }
+
                        return EndRead (res);
                }
 
@@ -205,6 +253,11 @@ namespace System.Net
                        if (size < 0 || offset < 0 || length < offset || length - offset < size)
                                throw new ArgumentOutOfRangeException ();
 
+                       lock (locker) {
+                               pendingReads++;
+                               pending.Reset ();
+                       }
+
                        WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
                        if (totalRead >= contentLength) {
                                result.SetCompleted (true, -1);
@@ -228,13 +281,8 @@ namespace System.Net
                                result.NBytes = copy;
                        }
 
-                       lock (this) {
-                               pendingReads++;
-                               pending.Reset ();
-                       }
-
                        if (cb != null)
-                               cb = new AsyncCallback (CallbackWrapper);
+                               cb = new AsyncCallback (ReadCallbackWrapper);
 
                        if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
                                size = contentLength - totalRead;
@@ -246,31 +294,37 @@ namespace System.Net
                public override int EndRead (IAsyncResult r)
                {
                        WebAsyncResult result = (WebAsyncResult) r;
+                       if (result.EndCalled) {
+                               int xx = result.NBytes;
+                               return (xx >= 0) ? xx : 0;
+                       }
 
-                       if (!result.IsCompleted) {
-                               int nbytes = cnc.EndRead (result.InnerAsyncResult);
-                               lock (this) {
-                                       pendingReads--;
-                                       if (pendingReads == 0)
-                                               pending.Set ();
-                               }
+                       result.EndCalled = true;
 
+                       if (!result.IsCompleted) {
+                               int nbytes = cnc.EndRead (result);
                                bool finished = (nbytes == -1);
                                if (finished && result.NBytes > 0)
                                        nbytes = 0;
 
-                               result.SetCompleted (false, nbytes + result.NBytes);
                                totalRead += nbytes;
+                               result.SetCompleted (false, nbytes + result.NBytes);
+                               result.DoCallback ();
                                if (finished || nbytes == 0)
                                        contentLength = totalRead;
                        }
 
-                       if (totalRead >= contentLength && !nextReadCalled) {
-                               nextReadCalled = true;
-                               cnc.NextRead ();
+                       lock (locker) {
+                               pendingReads--;
+                               if (pendingReads == 0)
+                                       pending.Set ();
                        }
 
-                       return result.NBytes;
+                       if (totalRead >= contentLength && !nextReadCalled)
+                               ReadAll ();
+
+                       int nb = result.NBytes;
+                       return (nb >= 0) ? nb : 0;
                }
                
                public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
@@ -287,7 +341,7 @@ namespace System.Net
                                throw new ArgumentOutOfRangeException ();
 
                        if (sendChunked) {
-                               lock (this) {
+                               lock (locker) {
                                        pendingWrites++;
                                        pending.Reset ();
                                }
@@ -305,7 +359,7 @@ namespace System.Net
 
                        AsyncCallback callback = null;
                        if (cb != null)
-                               callback = new AsyncCallback (CallbackWrapper);
+                               callback = new AsyncCallback (WriteCallbackWrapper);
 
                        if (sendChunked) {
                                WriteRequest ();
@@ -332,19 +386,25 @@ namespace System.Net
                        if (r == null)
                                throw new ArgumentNullException ("r");
 
-                       if (allowBuffering && !sendChunked)
-                               return;
-
                        WebAsyncResult result = r as WebAsyncResult;
                        if (result == null)
                                throw new ArgumentException ("Invalid IAsyncResult");
 
+                       if (result.EndCalled)
+                               return;
+
+                       result.EndCalled = true;
+
+                       if (allowBuffering && !sendChunked)
+                               return;
+
                        if (result.GotException)
                                throw result.Exception;
 
                        cnc.EndWrite (result.InnerAsyncResult);
+                       result.SetCompleted (false, 0);
                        if (sendChunked) {
-                               lock (this) {
+                               lock (locker) {
                                        pendingWrites--;
                                        if (pendingWrites == 0)
                                                pending.Set ();
@@ -357,7 +417,13 @@ namespace System.Net
                        if (isRead)
                                throw new NotSupportedException ("This stream does not allow writing");
 
-                       IAsyncResult res = BeginWrite (buffer, offset, size, null, null);
+                       AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
+                       WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
+                       if (!res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
+                               cnc.Close (true);
+                               throw new IOException ("Write timed out.");
+                       }
+
                        EndWrite (res);
                }
 
@@ -372,16 +438,13 @@ namespace System.Net
 
                        if (!allowBuffering || sendChunked) {
                                headersSent = true;
-                               try {
-                                       cnc.Write (buffer, offset, size);
-                               } catch (IOException) {
-                                       if (cnc.Connected)
-                                               throw;
-
-                                       if (!cnc.TryReconnect ())
-                                               throw;
+                               if (!cnc.Connected)
+                                       throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
 
-                                       cnc.Write (buffer, offset, size);
+                               cnc.Write (buffer, offset, size);
+                               if (!initRead) {
+                                       initRead = true;
+                                       WebConnection.InitRead (cnc);
                                }
                        } else {
                                headers = new byte [size];
@@ -389,6 +452,10 @@ namespace System.Net
                        }
                }
 
+               internal bool RequestWritten {
+                       get { return requestWritten; }
+               }
+
                internal void WriteRequest ()
                {
                        if (requestWritten)
@@ -406,32 +473,22 @@ namespace System.Net
                        byte [] bytes = writeBuffer.GetBuffer ();
                        int length = (int) writeBuffer.Length;
                        if (request.ContentLength != -1 && request.ContentLength < length) {
-                               throw new ProtocolViolationException ("Specified Content-Length is less than the " +
-                                                                     "number of bytes to write");
+                               throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
+                                                       WebExceptionStatus.ServerProtocolViolation, null);
                        }
 
                        request.InternalContentLength = length;
                        request.SendRequestHeaders ();
                        requestWritten = true;
-                       while (true) {
-                               cnc.Write (headers, 0, headers.Length);
-                               if (!cnc.Connected) {
-                                       if (!cnc.TryReconnect ())
-                                               return;
+                       cnc.Write (headers, 0, headers.Length);
+                       if (!cnc.Connected)
+                               throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
 
-                                       continue;
-                               }
-                               headersSent = true;
-
-                               if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
-                                       return;
-
-                               cnc.Write (bytes, 0, length);
-                               if (!cnc.Connected && cnc.TryReconnect ())
-                                       continue;
+                       headersSent = true;
+                       if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
+                               return;
 
-                               break;
-                       }
+                       cnc.Write (bytes, 0, length);
                }
 
                internal void InternalClose ()
@@ -448,7 +505,23 @@ namespace System.Net
                                return;
                        }
 
-                       if (isRead || !allowBuffering || disposed)
+                       if (isRead) {
+                               if (!nextReadCalled) {
+                                       CheckComplete ();
+                                       // If we have not read all the contents
+                                       if (!nextReadCalled)
+                                               cnc.Close (true);
+                               }
+                               return;
+                       } else if (!allowBuffering) {
+                               if (!initRead) {
+                                       initRead = true;
+                                       WebConnection.InitRead (cnc);
+                               }
+                               return;
+                       }
+
+                       if (disposed)
                                return;
 
                        disposed = true;
@@ -458,18 +531,12 @@ namespace System.Net
                                throw new IOException ("Cannot close the stream until all bytes are written");
 
                        WriteRequest ();
+                       if (!initRead) {
+                               initRead = true;
+                               WebConnection.InitRead (cnc);
+                       }
                }
 
-               internal void ResetWriteBuffer ()
-               {
-                       if (!allowBuffering)
-                               return;
-
-                       writeBuffer = new MemoryStream ();
-                       requestWritten = false;
-                       headersSent = false;
-               }
-               
                public override long Seek (long a, SeekOrigin b)
                {
                        throw new NotSupportedException ();