[WebConnection] Fix race condition between Close and BeginWrite (#4693)
[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                 long contentLength;
49                 long 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 = Int64.MaxValue;
97                                 }
98                         } else {
99                                 contentLength = Int64.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 == Int64.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                         if (!pending.WaitOne (ReadTimeout))
238                                 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
239                         lock (locker) {
240                                 if (totalRead >= contentLength)
241                                         return;
242                                 
243                                 byte [] b = null;
244                                 int diff = readBufferSize - readBufferOffset;
245                                 int new_size;
246
247                                 if (contentLength == Int64.MaxValue) {
248                                         MemoryStream ms = new MemoryStream ();
249                                         byte [] buffer = null;
250                                         if (readBuffer != null && diff > 0) {
251                                                 ms.Write (readBuffer, readBufferOffset, diff);
252                                                 if (readBufferSize >= 8192)
253                                                         buffer = readBuffer;
254                                         }
255
256                                         if (buffer == null)
257                                                 buffer = new byte [8192];
258
259                                         int read;
260                                         while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
261                                                 ms.Write (buffer, 0, read);
262
263                                         b = ms.GetBuffer ();
264                                         new_size = (int) ms.Length;
265                                         contentLength = new_size;
266                                 } else {
267                                         new_size = (int) (contentLength - totalRead);
268                                         b = new byte [new_size];
269                                         if (readBuffer != null && diff > 0) {
270                                                 if (diff > new_size)
271                                                         diff = new_size;
272
273                                                 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
274                                         }
275                                         
276                                         int remaining = new_size - diff;
277                                         int r = -1;
278                                         while (remaining > 0 && r != 0) {
279                                                 r = cnc.Read (request, b, diff, remaining);
280                                                 remaining -= r;
281                                                 diff += r;
282                                         }
283                                 }
284
285                                 readBuffer = b;
286                                 readBufferOffset = 0;
287                                 readBufferSize = new_size;
288                                 totalRead = 0;
289                                 nextReadCalled = true;
290                         }
291
292                         cnc.NextRead ();
293                 }
294
295                 void WriteCallbackWrapper (IAsyncResult r)
296                 {
297                         WebAsyncResult result = r as WebAsyncResult;
298                         if (result != null && result.AsyncWriteAll)
299                                 return;
300
301                         if (r.AsyncState != null) {
302                                 result = (WebAsyncResult) r.AsyncState;
303                                 result.InnerAsyncResult = r;
304                                 result.DoCallback ();
305                         } else {
306                                 try {
307                                         EndWrite (r);
308                                 } catch {
309                                 }
310                         }
311                 }
312
313                 void ReadCallbackWrapper (IAsyncResult r)
314                 {
315                         WebAsyncResult result;
316                         if (r.AsyncState != null) {
317                                 result = (WebAsyncResult) r.AsyncState;
318                                 result.InnerAsyncResult = r;
319                                 result.DoCallback ();
320                         } else {
321                                 try {
322                                         EndRead (r);
323                                 } catch {
324                                 }
325                         }
326                 }
327
328                 public override int Read (byte [] buffer, int offset, int size)
329                 {
330                         AsyncCallback cb = cb_wrapper;
331                         WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
332                         if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
333                                 nextReadCalled = true;
334                                 cnc.Close (true);
335                                 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
336                         }
337
338                         return EndRead (res);
339                 }
340
341                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
342                                                         AsyncCallback cb, object state)
343                 {
344                         if (!isRead)
345                                 throw new NotSupportedException ("this stream does not allow reading");
346
347                         if (buffer == null)
348                                 throw new ArgumentNullException ("buffer");
349
350                         int length = buffer.Length;
351                         if (offset < 0 || length < offset)
352                                 throw new ArgumentOutOfRangeException ("offset");
353                         if (size < 0 || (length - offset) < size)
354                                 throw new ArgumentOutOfRangeException ("size");
355
356                         lock (locker) {
357                                 pendingReads++;
358                                 pending.Reset ();
359                         }
360
361                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
362                         if (totalRead >= contentLength) {
363                                 result.SetCompleted (true, -1);
364                                 result.DoCallback ();
365                                 return result;
366                         }
367                         
368                         int remaining = readBufferSize - readBufferOffset;
369                         if (remaining > 0) {
370                                 int copy = (remaining > size) ? size : remaining;
371                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
372                                 readBufferOffset += copy;
373                                 offset += copy;
374                                 size -= copy;
375                                 totalRead += copy;
376                                 if (size == 0 || totalRead >= contentLength) {
377                                         result.SetCompleted (true, copy);
378                                         result.DoCallback ();
379                                         return result;
380                                 }
381                                 result.NBytes = copy;
382                         }
383
384                         if (cb != null)
385                                 cb = cb_wrapper;
386
387                         if (contentLength != Int64.MaxValue && contentLength - totalRead < size)
388                                 size = (int)(contentLength - totalRead);
389
390                         if (!read_eof) {
391                                 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
392                         } else {
393                                 result.SetCompleted (true, result.NBytes);
394                                 result.DoCallback ();
395                         }
396                         return result;
397                 }
398
399                 public override int EndRead (IAsyncResult r)
400                 {
401                         WebAsyncResult result = (WebAsyncResult) r;
402                         if (result.EndCalled) {
403                                 int xx = result.NBytes;
404                                 return (xx >= 0) ? xx : 0;
405                         }
406
407                         result.EndCalled = true;
408
409                         if (!result.IsCompleted) {
410                                 int nbytes = -1;
411                                 try {
412                                         nbytes = cnc.EndRead (request, result);
413                                 } catch (Exception exc) {
414                                         lock (locker) {
415                                                 pendingReads--;
416                                                 if (pendingReads == 0)
417                                                         pending.Set ();
418                                         }
419
420                                         nextReadCalled = true;
421                                         cnc.Close (true);
422                                         result.SetCompleted (false, exc);
423                                         result.DoCallback ();
424                                         throw;
425                                 }
426
427                                 if (nbytes < 0) {
428                                         nbytes = 0;
429                                         read_eof = true;
430                                 }
431
432                                 totalRead += nbytes;
433                                 result.SetCompleted (false, nbytes + result.NBytes);
434                                 result.DoCallback ();
435                                 if (nbytes == 0)
436                                         contentLength = totalRead;
437                         }
438
439                         lock (locker) {
440                                 pendingReads--;
441                                 if (pendingReads == 0)
442                                         pending.Set ();
443                         }
444
445                         if (totalRead >= contentLength && !nextReadCalled)
446                                 ReadAll ();
447
448                         int nb = result.NBytes;
449                         return (nb >= 0) ? nb : 0;
450                 }
451
452                 void WriteAsyncCB (IAsyncResult r)
453                 {
454                         WebAsyncResult result = (WebAsyncResult) r.AsyncState;
455                         result.InnerAsyncResult = null;
456
457                         try {
458                                 cnc.EndWrite (request, true, r);
459                                 result.SetCompleted (false, 0);
460                                 if (!initRead) {
461                                         initRead = true;
462                                         cnc.InitRead ();
463                                 }
464                         } catch (Exception e) {
465                                 KillBuffer ();
466                                 nextReadCalled = true;
467                                 cnc.Close (true);
468                                 if (e is System.Net.Sockets.SocketException)
469                                         e = new IOException ("Error writing request", e);
470                                 result.SetCompleted (false, e);
471                         }
472
473                         if (allowBuffering && !sendChunked && request.ContentLength > 0 && totalWritten == request.ContentLength)
474                                 complete_request_written = true;
475
476                         result.DoCallback ();
477                 }
478
479                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
480                                                         AsyncCallback cb, object state)
481                 {
482                         if (request.Aborted)
483                                 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
484
485                         if (isRead)
486                                 throw new NotSupportedException ("this stream does not allow writing");
487
488                         if (buffer == null)
489                                 throw new ArgumentNullException ("buffer");
490
491                         int length = buffer.Length;
492                         if (offset < 0 || length < offset)
493                                 throw new ArgumentOutOfRangeException ("offset");
494                         if (size < 0 || (length - offset) < size)
495                                 throw new ArgumentOutOfRangeException ("size");
496
497                         if (sendChunked) {
498                                 lock (locker) {
499                                         pendingWrites++;
500                                         pending.Reset ();
501                                 }
502                         }
503
504                         WebAsyncResult result = new WebAsyncResult (cb, state);
505                         AsyncCallback callback = new AsyncCallback (WriteAsyncCB);
506
507                         if (sendChunked) {
508                                 requestWritten = true;
509
510                                 string cSize = String.Format ("{0:X}\r\n", size);
511                                 byte[] head = Encoding.ASCII.GetBytes (cSize);
512                                 int chunkSize = 2 + size + head.Length;
513                                 byte[] newBuffer = new byte [chunkSize];
514                                 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
515                                 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
516                                 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
517
518                                 if (allowBuffering) {
519                                         if (writeBuffer == null)
520                                                 writeBuffer = new MemoryStream ();
521                                         writeBuffer.Write (buffer, offset, size);
522                                         totalWritten += size;
523                                 }
524
525                                 buffer = newBuffer;
526                                 offset = 0;
527                                 size = chunkSize;
528                         } else {
529                                 CheckWriteOverflow (request.ContentLength, totalWritten, size);
530
531                                 if (allowBuffering) {
532                                         if (writeBuffer == null)
533                                                 writeBuffer = new MemoryStream ();
534                                         writeBuffer.Write (buffer, offset, size);
535                                         totalWritten += size;
536
537                                         if (request.ContentLength <= 0 || totalWritten < request.ContentLength) {
538                                                 result.SetCompleted (true, 0);
539                                                 result.DoCallback ();
540                                                 return result;
541                                         }
542
543                                         result.AsyncWriteAll = true;
544                                         requestWritten = true;
545                                         buffer = writeBuffer.GetBuffer ();
546                                         offset = 0;
547                                         size = (int)totalWritten;
548                                 }
549                         }
550
551                         try {
552                                 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
553                                 if (result.InnerAsyncResult == null) {
554                                         if (!result.IsCompleted)
555                                                 result.SetCompleted (true, 0);
556                                         result.DoCallback ();
557                                 }
558                         } catch (Exception) {
559                                 if (!IgnoreIOErrors)
560                                         throw;
561                                 result.SetCompleted (true, 0);
562                                 result.DoCallback ();
563                         }
564                         totalWritten += size;
565                         return result;
566                 }
567
568                 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
569                 {
570                         if (contentLength == -1)
571                                 return;
572
573                         long avail = contentLength - totalWritten;
574                         if (size > avail) {
575                                 KillBuffer ();
576                                 nextReadCalled = true;
577                                 cnc.Close (true);
578                                 throw new ProtocolViolationException (
579                                         "The number of bytes to be written is greater than " +
580                                         "the specified ContentLength.");
581                         }
582                 }
583
584                 public override void EndWrite (IAsyncResult r)
585                 {
586                         if (r == null)
587                                 throw new ArgumentNullException ("r");
588
589                         WebAsyncResult result = r as WebAsyncResult;
590                         if (result == null)
591                                 throw new ArgumentException ("Invalid IAsyncResult");
592
593                         if (result.EndCalled)
594                                 return;
595
596                         if (sendChunked) {
597                                 lock (locker) {
598                                         pendingWrites--;
599                                         if (pendingWrites <= 0)
600                                                 pending.Set ();
601                                 }
602                         }
603
604                         result.EndCalled = true;
605                         if (result.AsyncWriteAll) {
606                                 result.WaitUntilComplete ();
607                                 if (result.GotException)
608                                         throw result.Exception;
609                                 return;
610                         }
611
612                         if (allowBuffering && !sendChunked)
613                                 return;
614
615                         if (result.GotException)
616                                 throw result.Exception;
617                 }
618                 
619                 public override void Write (byte [] buffer, int offset, int size)
620                 {
621                         AsyncCallback cb = cb_wrapper;
622                         WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
623                         if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
624                                 KillBuffer ();
625                                 nextReadCalled = true;
626                                 cnc.Close (true);
627                                 throw new IOException ("Write timed out.");
628                         }
629
630                         EndWrite (res);
631                 }
632
633                 public override void Flush ()
634                 {
635                 }
636
637                 internal void SetHeadersAsync (bool setInternalLength, SimpleAsyncCallback callback)
638                 {
639                         SimpleAsyncResult.Run (r => SetHeadersAsync (r, setInternalLength), callback);
640                 }
641
642                 bool SetHeadersAsync (SimpleAsyncResult result, bool setInternalLength)
643                 {
644                         if (headersSent)
645                                 return false;
646
647                         string method = request.Method;
648                         bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
649                                               method == "TRACE");
650                         bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
651                                       method == "COPY" || method == "MOVE" || method == "LOCK" ||
652                                       method == "UNLOCK");
653
654                         if (setInternalLength && !no_writestream && writeBuffer != null)
655                                 request.InternalContentLength = writeBuffer.Length;
656
657                         bool has_content = !no_writestream && (writeBuffer == null || request.ContentLength > -1);
658                         if (!(sendChunked || has_content || no_writestream || webdav))
659                                 return false;
660
661                         headersSent = true;
662                         headers = request.GetRequestHeaders ();
663
664                         var innerResult = cnc.BeginWrite (request, headers, 0, headers.Length, r => {
665                                 try {
666                                         cnc.EndWrite (request, true, r);
667                                         if (!initRead) {
668                                                 initRead = true;
669                                                 cnc.InitRead ();
670                                         }
671                                         var cl = request.ContentLength;
672                                         if (!sendChunked && cl == 0)
673                                                 requestWritten = true;
674                                         result.SetCompleted (false);
675                                 } catch (WebException e) {
676                                         result.SetCompleted (false, e);
677                                 } catch (Exception e) {
678                                         result.SetCompleted (false, new WebException ("Error writing headers", WebExceptionStatus.SendFailure, WebExceptionInternalStatus.RequestFatal, e));
679                                 }
680                         }, null);
681
682                         return innerResult != null;
683                 }
684
685                 internal bool RequestWritten {
686                         get { return requestWritten; }
687                 }
688
689                 internal SimpleAsyncResult WriteRequestAsync (SimpleAsyncCallback callback)
690                 {
691                         var result = WriteRequestAsync (callback);
692                         try {
693                                 if (!WriteRequestAsync (result))
694                                         result.SetCompleted (true);
695                         } catch (Exception ex) {
696                                 result.SetCompleted (true, ex);
697                         }
698                         return result;
699                 }
700
701                 internal bool WriteRequestAsync (SimpleAsyncResult result)
702                 {
703                         if (requestWritten)
704                                 return false;
705
706                         requestWritten = true;
707                         if (sendChunked || !allowBuffering || writeBuffer == null)
708                                 return false;
709
710                         // Keep the call for a potential side-effect of GetBuffer
711                         var bytes = writeBuffer.GetBuffer ();
712                         var length = (int)writeBuffer.Length;
713                         if (request.ContentLength != -1 && request.ContentLength < length) {
714                                 nextReadCalled = true;
715                                 cnc.Close (true);
716                                 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
717                                         WebExceptionStatus.ServerProtocolViolation, null);
718                         }
719
720                         SetHeadersAsync (true, inner => {
721                                 if (inner.GotException) {
722                                         result.SetCompleted (inner.CompletedSynchronouslyPeek, inner.Exception);
723                                         return;
724                                 }
725
726                                 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100) {
727                                         result.SetCompleted (inner.CompletedSynchronouslyPeek);
728                                         return;
729                                 }
730
731                                 if (!initRead) {
732                                         initRead = true;
733                                         cnc.InitRead ();
734                                 }
735
736                                 if (length == 0) {
737                                         complete_request_written = true;
738                                         result.SetCompleted (inner.CompletedSynchronouslyPeek);
739                                         return;
740                                 }
741
742                                 cnc.BeginWrite (request, bytes, 0, length, r => {
743                                         try {
744                                                 complete_request_written = cnc.EndWrite (request, false, r);
745                                                 result.SetCompleted (false);
746                                         } catch (Exception exc) {
747                                                 result.SetCompleted (false, exc);
748                                         }
749                                 }, null);
750                         });
751
752                         return true;
753                 }
754
755                 internal void InternalClose ()
756                 {
757                         disposed = true;
758                 }
759
760                 internal bool GetResponseOnClose {
761                         get; set;
762                 }
763
764                 public override void Close ()
765                 {
766                         if (GetResponseOnClose) {
767                                 if (disposed)
768                                         return;
769                                 disposed = true;
770                                 var response = (HttpWebResponse)request.GetResponse ();
771                                 response.ReadAll ();
772                                 response.Close ();
773                                 return;
774                         }
775
776                         if (sendChunked) {
777                                 if (disposed)
778                                         return;
779                                 disposed = true;
780                                 if (!pending.WaitOne (WriteTimeout)) {
781                                         throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
782                                 }
783                                 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
784                                 string err_msg = null;
785                                 cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
786                                 return;
787                         }
788
789                         if (isRead) {
790                                 if (!nextReadCalled) {
791                                         CheckComplete ();
792                                         // If we have not read all the contents
793                                         if (!nextReadCalled) {
794                                                 nextReadCalled = true;
795                                                 cnc.Close (true);
796                                         }
797                                 }
798                                 return;
799                         } else if (!allowBuffering) {
800                                 complete_request_written = true;
801                                 if (!initRead) {
802                                         initRead = true;
803                                         cnc.InitRead ();
804                                 }
805                                 return;
806                         }
807
808                         if (disposed || requestWritten)
809                                 return;
810
811                         long length = request.ContentLength;
812
813                         if (!sendChunked && length != -1 && totalWritten != length) {
814                                 IOException io = new IOException ("Cannot close the stream until all bytes are written");
815                                 nextReadCalled = true;
816                                 cnc.Close (true);
817                                 throw new WebException ("Request was cancelled.", WebExceptionStatus.RequestCanceled, WebExceptionInternalStatus.RequestFatal, io);
818                         }
819
820                         // Commented out the next line to fix xamarin bug #1512
821                         //WriteRequest ();
822                         disposed = true;
823                 }
824
825                 internal void KillBuffer ()
826                 {
827                         writeBuffer = null;
828                 }
829
830                 public override long Seek (long a, SeekOrigin b)
831                 {
832                         throw new NotSupportedException ();
833                 }
834                 
835                 public override void SetLength (long a)
836                 {
837                         throw new NotSupportedException ();
838                 }
839                 
840                 public override bool CanSeek {
841                         get { return false; }
842                 }
843
844                 public override bool CanRead {
845                         get { return !disposed && isRead; }
846                 }
847
848                 public override bool CanWrite {
849                         get { return !disposed && !isRead; }
850                 }
851
852                 public override long Length {
853                         get {
854                                 if (!isRead)
855                                         throw new NotSupportedException ();
856                                 return stream_length;
857                         }
858                 }
859
860                 public override long Position {
861                         get { throw new NotSupportedException (); }
862                         set { throw new NotSupportedException (); }
863                 }
864         }
865 }
866