Merge pull request #1237 from esdrubal/xdocument
[mono.git] / mcs / class / System / System.Net / WebConnectionStream.cs
1 //
2 // System.Net.WebConnectionStream
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
8 // (C) 2004 Novell, Inc (http://www.novell.com)
9 //
10
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.IO;
33 using System.Text;
34 using System.Threading;
35
36 namespace System.Net
37 {
38         class WebConnectionStream : Stream
39         {
40                 static byte [] crlf = new byte [] { 13, 10 };
41                 bool isRead;
42                 WebConnection cnc;
43                 HttpWebRequest request;
44                 byte [] readBuffer;
45                 int readBufferOffset;
46                 int readBufferSize;
47                 int stream_length; // -1 when CL not present
48                 int contentLength;
49                 int totalRead;
50                 internal long totalWritten;
51                 bool nextReadCalled;
52                 int pendingReads;
53                 int pendingWrites;
54                 ManualResetEvent pending;
55                 bool allowBuffering;
56                 bool sendChunked;
57                 MemoryStream writeBuffer;
58                 bool requestWritten;
59                 byte [] headers;
60                 bool disposed;
61                 bool headersSent;
62                 object locker = new object ();
63                 bool initRead;
64                 bool read_eof;
65                 bool complete_request_written;
66                 int read_timeout;
67                 int write_timeout;
68                 AsyncCallback cb_wrapper; // Calls to ReadCallbackWrapper or WriteCallbacWrapper
69                 internal bool IgnoreIOErrors;
70
71                 public WebConnectionStream (WebConnection cnc, WebConnectionData data)
72                 {          
73                         if (data == null)
74                                 throw new InvalidOperationException ("data was not initialized");
75                         if (data.Headers == null)
76                                 throw new InvalidOperationException ("data.Headers was not initialized");
77                         if (data.request == null)
78                                 throw new InvalidOperationException ("data.request was not initialized");
79                         isRead = true;
80                         cb_wrapper = new AsyncCallback (ReadCallbackWrapper);
81                         pending = new ManualResetEvent (true);
82                         this.request = data.request;
83                         read_timeout = request.ReadWriteTimeout;
84                         write_timeout = read_timeout;
85                         this.cnc = cnc;
86                         string contentType = data.Headers ["Transfer-Encoding"];
87                         bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
88                         string clength = data.Headers ["Content-Length"];
89                         if (!chunkedRead && clength != null && clength != "") {
90                                 try {
91                                         contentLength = Int32.Parse (clength);
92                                         if (contentLength == 0 && !IsNtlmAuth ()) {
93                                                 ReadAll ();
94                                         }
95                                 } catch {
96                                         contentLength = Int32.MaxValue;
97                                 }
98                         } else {
99                                 contentLength = Int32.MaxValue;
100                         }
101
102                         // Negative numbers?
103                         if (!Int32.TryParse (clength, out stream_length))
104                                 stream_length = -1;
105                 }
106
107                 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
108                 {
109                         read_timeout = request.ReadWriteTimeout;
110                         write_timeout = read_timeout;
111                         isRead = false;
112                         cb_wrapper = new AsyncCallback (WriteCallbackWrapper);
113                         this.cnc = cnc;
114                         this.request = request;
115                         allowBuffering = request.InternalAllowBuffering;
116                         sendChunked = request.SendChunked;
117                         if (sendChunked)
118                                 pending = new ManualResetEvent (true);
119                         else if (allowBuffering)
120                                 writeBuffer = new MemoryStream ();
121                 }
122
123                 bool CheckAuthHeader (string headerName)
124                 {
125                         var authHeader = cnc.Data.Headers [headerName];
126                         return (authHeader != null && authHeader.IndexOf ("NTLM", StringComparison.Ordinal) != -1);
127                 }
128
129                 bool IsNtlmAuth ()
130                 {
131                         bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
132                         if (isProxy && CheckAuthHeader ("Proxy-Authenticate"))
133                                 return true;
134                         return CheckAuthHeader ("WWW-Authenticate");
135                 }
136
137                 internal void CheckResponseInBuffer ()
138                 {
139                         if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
140                                 if (!IsNtlmAuth ())
141                                         ReadAll ();
142                         }
143                 }
144
145                 internal HttpWebRequest Request {
146                         get { return request; }
147                 }
148
149                 internal WebConnection Connection {
150                         get { return cnc; }
151                 }
152                 public override bool CanTimeout {
153                         get { return true; }
154                 }
155
156                 public override int ReadTimeout {
157                         get {
158                                 return read_timeout;
159                         }
160
161                         set {
162                                 if (value < -1)
163                                         throw new ArgumentOutOfRangeException ("value");
164                                 read_timeout = value;
165                         }
166                 }
167
168                 public override int WriteTimeout {
169                         get {
170                                 return write_timeout;
171                         }
172
173                         set {
174                                 if (value < -1)
175                                         throw new ArgumentOutOfRangeException ("value");
176                                 write_timeout = value;
177                         }
178                 }
179
180                 internal bool CompleteRequestWritten {
181                         get { return complete_request_written; }
182                 }
183
184                 internal bool SendChunked {
185                         set { sendChunked = value; }
186                 }
187
188                 internal byte [] ReadBuffer {
189                         set { readBuffer = value; }
190                 }
191
192                 internal int ReadBufferOffset {
193                         set { readBufferOffset = value; }
194                 }
195                 
196                 internal int ReadBufferSize {
197                         set { readBufferSize = value; }
198                 }
199                 
200                 internal byte[] WriteBuffer {
201                         get { return writeBuffer.GetBuffer (); }
202                 }
203
204                 internal int WriteBufferLength {
205                         get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
206                 }
207
208                 internal void ForceCompletion ()
209                 {
210                         if (!nextReadCalled) {
211                                 if (contentLength == Int32.MaxValue)
212                                         contentLength = 0;
213                                 nextReadCalled = true;
214                                 cnc.NextRead ();
215                         }
216                 }
217
218                 internal void CheckComplete ()
219                 {
220                         bool nrc = nextReadCalled;
221                         if (!nrc && readBufferSize - readBufferOffset == contentLength) {
222                                 nextReadCalled = true;
223                                 cnc.NextRead ();
224                         }
225                 }
226
227                 internal void ReadAll ()
228                 {
229                         if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
230                                 if (isRead && !nextReadCalled) {
231                                         nextReadCalled = true;
232                                         cnc.NextRead ();
233                                 }
234                                 return;
235                         }
236
237                         pending.WaitOne ();
238                         lock (locker) {
239                                 if (totalRead >= contentLength)
240                                         return;
241                                 
242                                 byte [] b = null;
243                                 int diff = readBufferSize - readBufferOffset;
244                                 int new_size;
245
246                                 if (contentLength == Int32.MaxValue) {
247                                         MemoryStream ms = new MemoryStream ();
248                                         byte [] buffer = null;
249                                         if (readBuffer != null && diff > 0) {
250                                                 ms.Write (readBuffer, readBufferOffset, diff);
251                                                 if (readBufferSize >= 8192)
252                                                         buffer = readBuffer;
253                                         }
254
255                                         if (buffer == null)
256                                                 buffer = new byte [8192];
257
258                                         int read;
259                                         while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
260                                                 ms.Write (buffer, 0, read);
261
262                                         b = ms.GetBuffer ();
263                                         new_size = (int) ms.Length;
264                                         contentLength = new_size;
265                                 } else {
266                                         new_size = contentLength - totalRead;
267                                         b = new byte [new_size];
268                                         if (readBuffer != null && diff > 0) {
269                                                 if (diff > new_size)
270                                                         diff = new_size;
271
272                                                 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
273                                         }
274                                         
275                                         int remaining = new_size - diff;
276                                         int r = -1;
277                                         while (remaining > 0 && r != 0) {
278                                                 r = cnc.Read (request, b, diff, remaining);
279                                                 remaining -= r;
280                                                 diff += r;
281                                         }
282                                 }
283
284                                 readBuffer = b;
285                                 readBufferOffset = 0;
286                                 readBufferSize = new_size;
287                                 totalRead = 0;
288                                 nextReadCalled = true;
289                         }
290
291                         cnc.NextRead ();
292                 }
293
294                 void WriteCallbackWrapper (IAsyncResult r)
295                 {
296                         WebAsyncResult result = r as WebAsyncResult;
297                         if (result != null && result.AsyncWriteAll)
298                                 return;
299
300                         if (r.AsyncState != null) {
301                                 result = (WebAsyncResult) r.AsyncState;
302                                 result.InnerAsyncResult = r;
303                                 result.DoCallback ();
304                         } else {
305                                 try {
306                                         EndWrite (r);
307                                 } catch {
308                                 }
309                         }
310                 }
311
312                 void ReadCallbackWrapper (IAsyncResult r)
313                 {
314                         WebAsyncResult result;
315                         if (r.AsyncState != null) {
316                                 result = (WebAsyncResult) r.AsyncState;
317                                 result.InnerAsyncResult = r;
318                                 result.DoCallback ();
319                         } else {
320                                 try {
321                                         EndRead (r);
322                                 } catch {
323                                 }
324                         }
325                 }
326
327                 public override int Read (byte [] buffer, int offset, int size)
328                 {
329                         AsyncCallback cb = cb_wrapper;
330                         WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
331                         if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
332                                 nextReadCalled = true;
333                                 cnc.Close (true);
334                                 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
335                         }
336
337                         return EndRead (res);
338                 }
339
340                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
341                                                         AsyncCallback cb, object state)
342                 {
343                         if (!isRead)
344                                 throw new NotSupportedException ("this stream does not allow reading");
345
346                         if (buffer == null)
347                                 throw new ArgumentNullException ("buffer");
348
349                         int length = buffer.Length;
350                         if (offset < 0 || length < offset)
351                                 throw new ArgumentOutOfRangeException ("offset");
352                         if (size < 0 || (length - offset) < size)
353                                 throw new ArgumentOutOfRangeException ("size");
354
355                         lock (locker) {
356                                 pendingReads++;
357                                 pending.Reset ();
358                         }
359
360                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
361                         if (totalRead >= contentLength) {
362                                 result.SetCompleted (true, -1);
363                                 result.DoCallback ();
364                                 return result;
365                         }
366                         
367                         int remaining = readBufferSize - readBufferOffset;
368                         if (remaining > 0) {
369                                 int copy = (remaining > size) ? size : remaining;
370                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
371                                 readBufferOffset += copy;
372                                 offset += copy;
373                                 size -= copy;
374                                 totalRead += copy;
375                                 if (size == 0 || totalRead >= contentLength) {
376                                         result.SetCompleted (true, copy);
377                                         result.DoCallback ();
378                                         return result;
379                                 }
380                                 result.NBytes = copy;
381                         }
382
383                         if (cb != null)
384                                 cb = cb_wrapper;
385
386                         if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
387                                 size = contentLength - totalRead;
388
389                         if (!read_eof) {
390                                 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
391                         } else {
392                                 result.SetCompleted (true, result.NBytes);
393                                 result.DoCallback ();
394                         }
395                         return result;
396                 }
397
398                 public override int EndRead (IAsyncResult r)
399                 {
400                         WebAsyncResult result = (WebAsyncResult) r;
401                         if (result.EndCalled) {
402                                 int xx = result.NBytes;
403                                 return (xx >= 0) ? xx : 0;
404                         }
405
406                         result.EndCalled = true;
407
408                         if (!result.IsCompleted) {
409                                 int nbytes = -1;
410                                 try {
411                                         nbytes = cnc.EndRead (request, result);
412                                 } catch (Exception exc) {
413                                         lock (locker) {
414                                                 pendingReads--;
415                                                 if (pendingReads == 0)
416                                                         pending.Set ();
417                                         }
418
419                                         nextReadCalled = true;
420                                         cnc.Close (true);
421                                         result.SetCompleted (false, exc);
422                                         result.DoCallback ();
423                                         throw;
424                                 }
425
426                                 if (nbytes < 0) {
427                                         nbytes = 0;
428                                         read_eof = true;
429                                 }
430
431                                 totalRead += nbytes;
432                                 result.SetCompleted (false, nbytes + result.NBytes);
433                                 result.DoCallback ();
434                                 if (nbytes == 0)
435                                         contentLength = totalRead;
436                         }
437
438                         lock (locker) {
439                                 pendingReads--;
440                                 if (pendingReads == 0)
441                                         pending.Set ();
442                         }
443
444                         if (totalRead >= contentLength && !nextReadCalled)
445                                 ReadAll ();
446
447                         int nb = result.NBytes;
448                         return (nb >= 0) ? nb : 0;
449                 }
450
451                 void WriteAsyncCB (IAsyncResult r)
452                 {
453                         WebAsyncResult result = (WebAsyncResult) r.AsyncState;
454                         result.InnerAsyncResult = null;
455
456                         try {
457                                 cnc.EndWrite (request, true, r);
458                                 result.SetCompleted (false, 0);
459                                 if (!initRead) {
460                                         initRead = true;
461                                         WebConnection.InitRead (cnc);
462                                 }
463                         } catch (Exception e) {
464                                 KillBuffer ();
465                                 nextReadCalled = true;
466                                 cnc.Close (true);
467                                 if (e is System.Net.Sockets.SocketException)
468                                         e = new IOException ("Error writing request", e);
469                                 result.SetCompleted (false, e);
470                         }
471
472                         if (allowBuffering && !sendChunked && request.ContentLength > 0 && totalWritten == request.ContentLength)
473                                 complete_request_written = true;
474
475                         result.DoCallback ();
476                 }
477
478                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
479                                                         AsyncCallback cb, object state)
480                 {
481                         if (request.Aborted)
482                                 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
483
484                         if (isRead)
485                                 throw new NotSupportedException ("this stream does not allow writing");
486
487                         if (buffer == null)
488                                 throw new ArgumentNullException ("buffer");
489
490                         int length = buffer.Length;
491                         if (offset < 0 || length < offset)
492                                 throw new ArgumentOutOfRangeException ("offset");
493                         if (size < 0 || (length - offset) < size)
494                                 throw new ArgumentOutOfRangeException ("size");
495
496                         if (sendChunked) {
497                                 lock (locker) {
498                                         pendingWrites++;
499                                         pending.Reset ();
500                                 }
501                         }
502
503                         WebAsyncResult result = new WebAsyncResult (cb, state);
504                         AsyncCallback callback = new AsyncCallback (WriteAsyncCB);
505
506                         if (sendChunked) {
507                                 requestWritten = true;
508
509                                 string cSize = String.Format ("{0:X}\r\n", size);
510                                 byte[] head = Encoding.ASCII.GetBytes (cSize);
511                                 int chunkSize = 2 + size + head.Length;
512                                 byte[] newBuffer = new byte [chunkSize];
513                                 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
514                                 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
515                                 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
516
517                                 if (allowBuffering) {
518                                         if (writeBuffer == null)
519                                                 writeBuffer = new MemoryStream ();
520                                         writeBuffer.Write (buffer, offset, size);
521                                         totalWritten += size;
522                                 }
523
524                                 buffer = newBuffer;
525                                 offset = 0;
526                                 size = chunkSize;
527                         } else {
528                                 CheckWriteOverflow (request.ContentLength, totalWritten, size);
529
530                                 if (allowBuffering) {
531                                         if (writeBuffer == null)
532                                                 writeBuffer = new MemoryStream ();
533                                         writeBuffer.Write (buffer, offset, size);
534                                         totalWritten += size;
535
536                                         if (request.ContentLength <= 0 || totalWritten < request.ContentLength) {
537                                                 result.SetCompleted (true, 0);
538                                                 result.DoCallback ();
539                                                 return result;
540                                         }
541
542                                         result.AsyncWriteAll = true;
543                                         requestWritten = true;
544                                         buffer = writeBuffer.GetBuffer ();
545                                         offset = 0;
546                                         size = (int)totalWritten;
547                                 }
548                         }
549
550                         try {
551                                 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
552                                 if (result.InnerAsyncResult == null) {
553                                         if (!result.IsCompleted)
554                                                 result.SetCompleted (true, 0);
555                                         result.DoCallback ();
556                                 }
557                         } catch (Exception) {
558                                 if (!IgnoreIOErrors)
559                                         throw;
560                                 result.SetCompleted (true, 0);
561                                 result.DoCallback ();
562                         }
563                         totalWritten += size;
564                         return result;
565                 }
566
567                 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
568                 {
569                         if (contentLength == -1)
570                                 return;
571
572                         long avail = contentLength - totalWritten;
573                         if (size > avail) {
574                                 KillBuffer ();
575                                 nextReadCalled = true;
576                                 cnc.Close (true);
577                                 throw new ProtocolViolationException (
578                                         "The number of bytes to be written is greater than " +
579                                         "the specified ContentLength.");
580                         }
581                 }
582
583                 public override void EndWrite (IAsyncResult r)
584                 {
585                         if (r == null)
586                                 throw new ArgumentNullException ("r");
587
588                         WebAsyncResult result = r as WebAsyncResult;
589                         if (result == null)
590                                 throw new ArgumentException ("Invalid IAsyncResult");
591
592                         if (result.EndCalled)
593                                 return;
594
595                         result.EndCalled = true;
596                         if (result.AsyncWriteAll) {
597                                 result.WaitUntilComplete ();
598                                 if (result.GotException)
599                                         throw result.Exception;
600                                 return;
601                         }
602
603                         if (allowBuffering && !sendChunked)
604                                 return;
605
606                         if (result.GotException)
607                                 throw result.Exception;
608
609                         if (sendChunked) {
610                                 lock (locker) {
611                                         pendingWrites--;
612                                         if (pendingWrites == 0)
613                                                 pending.Set ();
614                                 }
615                         }
616                 }
617                 
618                 public override void Write (byte [] buffer, int offset, int size)
619                 {
620                         AsyncCallback cb = cb_wrapper;
621                         WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
622                         if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
623                                 KillBuffer ();
624                                 nextReadCalled = true;
625                                 cnc.Close (true);
626                                 throw new IOException ("Write timed out.");
627                         }
628
629                         EndWrite (res);
630                 }
631
632                 public override void Flush ()
633                 {
634                 }
635
636                 internal void SetHeadersAsync (bool setInternalLength, SimpleAsyncCallback callback)
637                 {
638                         SimpleAsyncResult.Run (r => SetHeadersAsync (r, setInternalLength), callback);
639                 }
640
641                 bool SetHeadersAsync (SimpleAsyncResult result, bool setInternalLength)
642                 {
643                         if (headersSent)
644                                 return false;
645
646                         string method = request.Method;
647                         bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
648                                               method == "TRACE");
649                         bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
650                                       method == "COPY" || method == "MOVE" || method == "LOCK" ||
651                                       method == "UNLOCK");
652
653                         if (setInternalLength && !no_writestream && writeBuffer != null)
654                                 request.InternalContentLength = writeBuffer.Length;
655
656                         if (!(sendChunked || request.ContentLength > -1 || no_writestream || webdav))
657                                 return false;
658
659                         headersSent = true;
660                         headers = request.GetRequestHeaders ();
661
662                         var innerResult = cnc.BeginWrite (request, headers, 0, headers.Length, r => {
663                                 try {
664                                         cnc.EndWrite (request, true, r);
665                                         if (!initRead) {
666                                                 initRead = true;
667                                                 WebConnection.InitRead (cnc);
668                                         }
669                                         var cl = request.ContentLength;
670                                         if (!sendChunked && cl == 0)
671                                                 requestWritten = true;
672                                         result.SetCompleted (false);
673                                 } catch (WebException e) {
674                                         result.SetCompleted (false, e);
675                                 } catch (Exception e) {
676                                         result.SetCompleted (false, new WebException ("Error writing headers", e, WebExceptionStatus.SendFailure));
677                                 }
678                         }, null);
679
680                         return innerResult != null;
681                 }
682
683                 internal bool RequestWritten {
684                         get { return requestWritten; }
685                 }
686
687                 internal SimpleAsyncResult WriteRequestAsync (SimpleAsyncCallback callback)
688                 {
689                         var result = WriteRequestAsync (callback);
690                         try {
691                                 if (!WriteRequestAsync (result))
692                                         result.SetCompleted (true);
693                         } catch (Exception ex) {
694                                 result.SetCompleted (true, ex);
695                         }
696                         return result;
697                 }
698
699                 internal bool WriteRequestAsync (SimpleAsyncResult result)
700                 {
701                         if (requestWritten)
702                                 return false;
703
704                         requestWritten = true;
705                         if (sendChunked || !allowBuffering || writeBuffer == null)
706                                 return false;
707
708                         // Keep the call for a potential side-effect of GetBuffer
709                         var bytes = writeBuffer.GetBuffer ();
710                         var length = (int)writeBuffer.Length;
711                         if (request.ContentLength != -1 && request.ContentLength < length) {
712                                 nextReadCalled = true;
713                                 cnc.Close (true);
714                                 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
715                                         WebExceptionStatus.ServerProtocolViolation, null);
716                         }
717
718                         SetHeadersAsync (true, inner => {
719                                 if (inner.GotException) {
720                                         result.SetCompleted (inner.CompletedSynchronously, inner.Exception);
721                                         return;
722                                 }
723
724                                 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100) {
725                                         result.SetCompleted (inner.CompletedSynchronously);
726                                         return;
727                                 }
728
729                                 if (!initRead) {
730                                         initRead = true;
731                                         WebConnection.InitRead (cnc);
732                                 }
733
734                                 if (length == 0) {
735                                         complete_request_written = true;
736                                         result.SetCompleted (inner.CompletedSynchronously);
737                                         return;
738                                 }
739
740                                 cnc.BeginWrite (request, bytes, 0, length, r => {
741                                         try {
742                                                 complete_request_written = cnc.EndWrite (request, false, r);
743                                                 result.SetCompleted (false);
744                                         } catch (Exception exc) {
745                                                 result.SetCompleted (false, exc);
746                                         }
747                                 }, null);
748                         });
749
750                         return true;
751                 }
752
753                 internal void InternalClose ()
754                 {
755                         disposed = true;
756                 }
757
758                 internal bool GetResponseOnClose {
759                         get; set;
760                 }
761
762                 public override void Close ()
763                 {
764                         if (GetResponseOnClose) {
765                                 if (disposed)
766                                         return;
767                                 disposed = true;
768                                 var response = (HttpWebResponse)request.GetResponse ();
769                                 response.ReadAll ();
770                                 response.Close ();
771                                 return;
772                         }
773
774                         if (sendChunked) {
775                                 if (disposed)
776                                         return;
777                                 disposed = true;
778                                 pending.WaitOne ();
779                                 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
780                                 string err_msg = null;
781                                 cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
782                                 return;
783                         }
784
785                         if (isRead) {
786                                 if (!nextReadCalled) {
787                                         CheckComplete ();
788                                         // If we have not read all the contents
789                                         if (!nextReadCalled) {
790                                                 nextReadCalled = true;
791                                                 cnc.Close (true);
792                                         }
793                                 }
794                                 return;
795                         } else if (!allowBuffering) {
796                                 complete_request_written = true;
797                                 if (!initRead) {
798                                         initRead = true;
799                                         WebConnection.InitRead (cnc);
800                                 }
801                                 return;
802                         }
803
804                         if (disposed || requestWritten)
805                                 return;
806
807                         long length = request.ContentLength;
808
809                         if (!sendChunked && length != -1 && totalWritten != length) {
810                                 IOException io = new IOException ("Cannot close the stream until all bytes are written");
811                                 nextReadCalled = true;
812                                 cnc.Close (true);
813                                 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
814                         }
815
816                         // Commented out the next line to fix xamarin bug #1512
817                         //WriteRequest ();
818                         disposed = true;
819                 }
820
821                 internal void KillBuffer ()
822                 {
823                         writeBuffer = null;
824                 }
825
826                 public override long Seek (long a, SeekOrigin b)
827                 {
828                         throw new NotSupportedException ();
829                 }
830                 
831                 public override void SetLength (long a)
832                 {
833                         throw new NotSupportedException ();
834                 }
835                 
836                 public override bool CanSeek {
837                         get { return false; }
838                 }
839
840                 public override bool CanRead {
841                         get { return !disposed && isRead; }
842                 }
843
844                 public override bool CanWrite {
845                         get { return !disposed && !isRead; }
846                 }
847
848                 public override long Length {
849                         get {
850                                 if (!isRead)
851                                         throw new NotSupportedException ();
852                                 return stream_length;
853                         }
854                 }
855
856                 public override long Position {
857                         get { throw new NotSupportedException (); }
858                         set { throw new NotSupportedException (); }
859                 }
860         }
861 }
862