Merged into single file, added assertions
[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)
72                 {
73                         isRead = true;
74                         cb_wrapper = new AsyncCallback (ReadCallbackWrapper);
75                         pending = new ManualResetEvent (true);
76                         this.request = cnc.Data.request;
77                         read_timeout = request.ReadWriteTimeout;
78                         write_timeout = read_timeout;
79                         this.cnc = cnc;
80                         string contentType = cnc.Data.Headers ["Transfer-Encoding"];
81                         bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
82                         string clength = cnc.Data.Headers ["Content-Length"];
83                         if (!chunkedRead && clength != null && clength != "") {
84                                 try {
85                                         contentLength = Int32.Parse (clength);
86                                         if (contentLength == 0 && !IsNtlmAuth ()) {
87                                                 ReadAll ();
88                                         }
89                                 } catch {
90                                         contentLength = Int32.MaxValue;
91                                 }
92                         } else {
93                                 contentLength = Int32.MaxValue;
94                         }
95
96                         // Negative numbers?
97                         if (!Int32.TryParse (clength, out stream_length))
98                                 stream_length = -1;
99                 }
100
101                 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
102                 {
103                         read_timeout = request.ReadWriteTimeout;
104                         write_timeout = read_timeout;
105                         isRead = false;
106                         cb_wrapper = new AsyncCallback (WriteCallbackWrapper);
107                         this.cnc = cnc;
108                         this.request = request;
109                         allowBuffering = request.InternalAllowBuffering;
110                         sendChunked = request.SendChunked;
111                         if (sendChunked)
112                                 pending = new ManualResetEvent (true);
113                         else if (allowBuffering)
114                                 writeBuffer = new MemoryStream ();
115                 }
116
117                 bool IsNtlmAuth ()
118                 {
119                         bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
120                         string header_name = (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate";
121                         string authHeader = cnc.Data.Headers [header_name];
122                         return (authHeader != null && authHeader.IndexOf ("NTLM", StringComparison.Ordinal) != -1);
123                 }
124
125                 internal void CheckResponseInBuffer ()
126                 {
127                         if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
128                                 if (!IsNtlmAuth ())
129                                         ReadAll ();
130                         }
131                 }
132
133                 internal HttpWebRequest Request {
134                         get { return request; }
135                 }
136
137                 internal WebConnection Connection {
138                         get { return cnc; }
139                 }
140                 public override bool CanTimeout {
141                         get { return true; }
142                 }
143
144                 public override int ReadTimeout {
145                         get {
146                                 return read_timeout;
147                         }
148
149                         set {
150                                 if (value < -1)
151                                         throw new ArgumentOutOfRangeException ("value");
152                                 read_timeout = value;
153                         }
154                 }
155
156                 public override int WriteTimeout {
157                         get {
158                                 return write_timeout;
159                         }
160
161                         set {
162                                 if (value < -1)
163                                         throw new ArgumentOutOfRangeException ("value");
164                                 write_timeout = value;
165                         }
166                 }
167
168                 internal bool CompleteRequestWritten {
169                         get { return complete_request_written; }
170                 }
171
172                 internal bool SendChunked {
173                         set { sendChunked = value; }
174                 }
175
176                 internal byte [] ReadBuffer {
177                         set { readBuffer = value; }
178                 }
179
180                 internal int ReadBufferOffset {
181                         set { readBufferOffset = value;}
182                 }
183                 
184                 internal int ReadBufferSize {
185                         set { readBufferSize = value; }
186                 }
187                 
188                 internal byte[] WriteBuffer {
189                         get { return writeBuffer.GetBuffer (); }
190                 }
191
192                 internal int WriteBufferLength {
193                         get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
194                 }
195
196                 internal void ForceCompletion ()
197                 {
198                         if (!nextReadCalled) {
199                                 if (contentLength == Int32.MaxValue)
200                                         contentLength = 0;
201                                 nextReadCalled = true;
202                                 cnc.NextRead ();
203                         }
204                 }
205                 
206                 internal void CheckComplete ()
207                 {
208                         bool nrc = nextReadCalled;
209                         if (!nrc && readBufferSize - readBufferOffset == contentLength) {
210                                 nextReadCalled = true;
211                                 cnc.NextRead ();
212                         }
213                 }
214
215                 internal void ReadAll ()
216                 {
217                         if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
218                                 if (isRead && !nextReadCalled) {
219                                         nextReadCalled = true;
220                                         cnc.NextRead ();
221                                 }
222                                 return;
223                         }
224
225                         pending.WaitOne ();
226                         lock (locker) {
227                                 if (totalRead >= contentLength)
228                                         return;
229                                 
230                                 byte [] b = null;
231                                 int diff = readBufferSize - readBufferOffset;
232                                 int new_size;
233
234                                 if (contentLength == Int32.MaxValue) {
235                                         MemoryStream ms = new MemoryStream ();
236                                         byte [] buffer = null;
237                                         if (readBuffer != null && diff > 0) {
238                                                 ms.Write (readBuffer, readBufferOffset, diff);
239                                                 if (readBufferSize >= 8192)
240                                                         buffer = readBuffer;
241                                         }
242
243                                         if (buffer == null)
244                                                 buffer = new byte [8192];
245
246                                         int read;
247                                         while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
248                                                 ms.Write (buffer, 0, read);
249
250                                         b = ms.GetBuffer ();
251                                         new_size = (int) ms.Length;
252                                         contentLength = new_size;
253                                 } else {
254                                         new_size = contentLength - totalRead;
255                                         b = new byte [new_size];
256                                         if (readBuffer != null && diff > 0) {
257                                                 if (diff > new_size)
258                                                         diff = new_size;
259
260                                                 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
261                                         }
262                                         
263                                         int remaining = new_size - diff;
264                                         int r = -1;
265                                         while (remaining > 0 && r != 0) {
266                                                 r = cnc.Read (request, b, diff, remaining);
267                                                 remaining -= r;
268                                                 diff += r;
269                                         }
270                                 }
271
272                                 readBuffer = b;
273                                 readBufferOffset = 0;
274                                 readBufferSize = new_size;
275                                 totalRead = 0;
276                                 nextReadCalled = true;
277                         }
278
279                         cnc.NextRead ();
280                 }
281
282                 void WriteCallbackWrapper (IAsyncResult r)
283                 {
284                         WebAsyncResult result = r as WebAsyncResult;
285                         if (result != null && result.AsyncWriteAll)
286                                 return;
287
288                         if (r.AsyncState != null) {
289                                 result = (WebAsyncResult) r.AsyncState;
290                                 result.InnerAsyncResult = r;
291                                 result.DoCallback ();
292                         } else {
293                                 try {
294                                         EndWrite (r);
295                                 } catch {
296                                 }
297                         }
298                 }
299
300                 void ReadCallbackWrapper (IAsyncResult r)
301                 {
302                         WebAsyncResult result;
303                         if (r.AsyncState != null) {
304                                 result = (WebAsyncResult) r.AsyncState;
305                                 result.InnerAsyncResult = r;
306                                 result.DoCallback ();
307                         } else {
308                                 try {
309                                         EndRead (r);
310                                 } catch {
311                                 }
312                         }
313                 }
314
315                 public override int Read (byte [] buffer, int offset, int size)
316                 {
317                         AsyncCallback cb = cb_wrapper;
318                         WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
319                         if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
320                                 nextReadCalled = true;
321                                 cnc.Close (true);
322                                 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
323                         }
324
325                         return EndRead (res);
326                 }
327
328                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
329                                                         AsyncCallback cb, object state)
330                 {
331                         if (!isRead)
332                                 throw new NotSupportedException ("this stream does not allow reading");
333
334                         if (buffer == null)
335                                 throw new ArgumentNullException ("buffer");
336
337                         int length = buffer.Length;
338                         if (offset < 0 || length < offset)
339                                 throw new ArgumentOutOfRangeException ("offset");
340                         if (size < 0 || (length - offset) < size)
341                                 throw new ArgumentOutOfRangeException ("size");
342
343                         lock (locker) {
344                                 pendingReads++;
345                                 pending.Reset ();
346                         }
347
348                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
349                         if (totalRead >= contentLength) {
350                                 result.SetCompleted (true, -1);
351                                 result.DoCallback ();
352                                 return result;
353                         }
354                         
355                         int remaining = readBufferSize - readBufferOffset;
356                         if (remaining > 0) {
357                                 int copy = (remaining > size) ? size : remaining;
358                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
359                                 readBufferOffset += copy;
360                                 offset += copy;
361                                 size -= copy;
362                                 totalRead += copy;
363                                 if (size == 0 || totalRead >= contentLength) {
364                                         result.SetCompleted (true, copy);
365                                         result.DoCallback ();
366                                         return result;
367                                 }
368                                 result.NBytes = copy;
369                         }
370
371                         if (cb != null)
372                                 cb = cb_wrapper;
373
374                         if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
375                                 size = contentLength - totalRead;
376
377                         if (!read_eof) {
378                                 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
379                         } else {
380                                 result.SetCompleted (true, result.NBytes);
381                                 result.DoCallback ();
382                         }
383                         return result;
384                 }
385
386                 public override int EndRead (IAsyncResult r)
387                 {
388                         WebAsyncResult result = (WebAsyncResult) r;
389                         if (result.EndCalled) {
390                                 int xx = result.NBytes;
391                                 return (xx >= 0) ? xx : 0;
392                         }
393
394                         result.EndCalled = true;
395
396                         if (!result.IsCompleted) {
397                                 int nbytes = -1;
398                                 try {
399                                         nbytes = cnc.EndRead (request, result);
400                                 } catch (Exception exc) {
401                                         lock (locker) {
402                                                 pendingReads--;
403                                                 if (pendingReads == 0)
404                                                         pending.Set ();
405                                         }
406
407                                         nextReadCalled = true;
408                                         cnc.Close (true);
409                                         result.SetCompleted (false, exc);
410                                         result.DoCallback ();
411                                         throw;
412                                 }
413
414                                 if (nbytes < 0) {
415                                         nbytes = 0;
416                                         read_eof = true;
417                                 }
418
419                                 totalRead += nbytes;
420                                 result.SetCompleted (false, nbytes + result.NBytes);
421                                 result.DoCallback ();
422                                 if (nbytes == 0)
423                                         contentLength = totalRead;
424                         }
425
426                         lock (locker) {
427                                 pendingReads--;
428                                 if (pendingReads == 0)
429                                         pending.Set ();
430                         }
431
432                         if (totalRead >= contentLength && !nextReadCalled)
433                                 ReadAll ();
434
435                         int nb = result.NBytes;
436                         return (nb >= 0) ? nb : 0;
437                 }
438
439                 void WriteRequestAsyncCB (IAsyncResult r)
440                 {
441                         WebAsyncResult result = (WebAsyncResult) r.AsyncState;
442                         try {
443                                 cnc.EndWrite2 (request, r);
444                                 result.SetCompleted (false, 0);
445                                 if (!initRead) {
446                                         initRead = true;
447                                         WebConnection.InitRead (cnc);
448                                 }
449                         } catch (Exception e) {
450                                 KillBuffer ();
451                                 nextReadCalled = true;
452                                 cnc.Close (true);
453                                 if (e is System.Net.Sockets.SocketException)
454                                         e = new IOException ("Error writing request", e);
455                                 result.SetCompleted (false, e);
456                         }
457                         complete_request_written = true;
458                         result.DoCallback ();
459                 }
460
461                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
462                                                         AsyncCallback cb, object state)
463                 {
464                         if (request.Aborted)
465                                 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
466
467                         if (isRead)
468                                 throw new NotSupportedException ("this stream does not allow writing");
469
470                         if (buffer == null)
471                                 throw new ArgumentNullException ("buffer");
472
473                         int length = buffer.Length;
474                         if (offset < 0 || length < offset)
475                                 throw new ArgumentOutOfRangeException ("offset");
476                         if (size < 0 || (length - offset) < size)
477                                 throw new ArgumentOutOfRangeException ("size");
478
479                         if (sendChunked) {
480                                 lock (locker) {
481                                         pendingWrites++;
482                                         pending.Reset ();
483                                 }
484                         }
485
486                         WebAsyncResult result = new WebAsyncResult (cb, state);
487                         if (!sendChunked)
488                                 CheckWriteOverflow (request.ContentLength, totalWritten, size);
489                         if (allowBuffering && !sendChunked) {
490                                 if (writeBuffer == null)
491                                         writeBuffer = new MemoryStream ();
492                                 writeBuffer.Write (buffer, offset, size);
493                                 totalWritten += size;
494                                 if (request.ContentLength > 0 && totalWritten == request.ContentLength) {
495                                         try {
496                                                 result.AsyncWriteAll = true;
497                                                 result.InnerAsyncResult = WriteRequestAsync (new AsyncCallback (WriteRequestAsyncCB), result);
498                                                 if (result.InnerAsyncResult == null) {
499                                                         if (!result.IsCompleted)
500                                                                 result.SetCompleted (true, 0);
501                                                         result.DoCallback ();
502                                                 }
503                                         } catch (Exception exc) {
504                                                 result.SetCompleted (true, exc);
505                                                 result.DoCallback ();
506                                         }
507                                 } else {
508                                         result.SetCompleted (true, 0);
509                                         result.DoCallback ();
510                                 }
511                                 return result;
512                         }
513
514                         AsyncCallback callback = null;
515                         if (cb != null)
516                                 callback = cb_wrapper;
517
518                         if (sendChunked) {
519                                 WriteRequest ();
520
521                                 string cSize = String.Format ("{0:X}\r\n", size);
522                                 byte [] head = Encoding.ASCII.GetBytes (cSize);
523                                 int chunkSize = 2 + size + head.Length;
524                                 byte [] newBuffer = new byte [chunkSize];
525                                 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
526                                 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
527                                 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
528
529                                 buffer = newBuffer;
530                                 offset = 0;
531                                 size = chunkSize;
532                         }
533
534                         try {
535                                 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
536                         } catch (Exception) {
537                                 if (!IgnoreIOErrors)
538                                         throw;
539                                 result.SetCompleted (true, 0);
540                                 result.DoCallback ();
541                         }
542                         totalWritten += size;
543                         return result;
544                 }
545
546                 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
547                 {
548                         if (contentLength == -1)
549                                 return;
550
551                         long avail = contentLength - totalWritten;
552                         if (size > avail) {
553                                 KillBuffer ();
554                                 nextReadCalled = true;
555                                 cnc.Close (true);
556                                 throw new ProtocolViolationException (
557                                         "The number of bytes to be written is greater than " +
558                                         "the specified ContentLength.");
559                         }
560                 }
561
562                 public override void EndWrite (IAsyncResult r)
563                 {
564                         if (r == null)
565                                 throw new ArgumentNullException ("r");
566
567                         WebAsyncResult result = r as WebAsyncResult;
568                         if (result == null)
569                                 throw new ArgumentException ("Invalid IAsyncResult");
570
571                         if (result.EndCalled)
572                                 return;
573
574                         result.EndCalled = true;
575                         if (result.AsyncWriteAll) {
576                                 result.WaitUntilComplete ();
577                                 if (result.GotException)
578                                         throw result.Exception;
579                                 return;
580                         }
581
582                         if (allowBuffering && !sendChunked)
583                                 return;
584
585                         if (result.GotException)
586                                 throw result.Exception;
587
588                         try {
589                                 cnc.EndWrite2 (request, result.InnerAsyncResult);
590                                 result.SetCompleted (false, 0);
591                                 result.DoCallback ();
592                         } catch (Exception e) {
593                                 if (IgnoreIOErrors)
594                                         result.SetCompleted (false, 0);
595                                 else
596                                         result.SetCompleted (false, e);
597                                 result.DoCallback ();
598                                 if (!IgnoreIOErrors)
599                                         throw;
600                         } finally {
601                                 if (sendChunked) {
602                                         lock (locker) {
603                                                 pendingWrites--;
604                                                 if (pendingWrites == 0)
605                                                         pending.Set ();
606                                         }
607                                 }
608                         }
609                 }
610                 
611                 public override void Write (byte [] buffer, int offset, int size)
612                 {
613                         AsyncCallback cb = cb_wrapper;
614                         WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
615                         if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
616                                 KillBuffer ();
617                                 nextReadCalled = true;
618                                 cnc.Close (true);
619                                 throw new IOException ("Write timed out.");
620                         }
621
622                         EndWrite (res);
623                 }
624
625                 public override void Flush ()
626                 {
627                 }
628
629                 internal void SetHeaders (byte [] buffer)
630                 {
631                         if (headersSent)
632                                 return;
633
634                         headers = buffer;
635                         long cl = request.ContentLength;
636                         string method = request.Method;
637                         bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
638                                                 method == "TRACE");
639                         bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
640                                        method == "COPY" || method == "MOVE" || method == "LOCK" ||
641                                        method == "UNLOCK");
642                         if (sendChunked || cl > -1 || no_writestream || webdav) {
643                                 WriteHeaders ();
644                                 if (!initRead) {
645                                         initRead = true;
646                                         WebConnection.InitRead (cnc);
647                                 }
648                                 if (!sendChunked && cl == 0)
649                                         requestWritten = true;
650                         }
651                 }
652
653                 internal bool RequestWritten {
654                         get { return requestWritten; }
655                 }
656
657                 IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
658                 {
659                         requestWritten = true;
660                         byte [] bytes = writeBuffer.GetBuffer ();
661                         int length = (int) writeBuffer.Length;
662                         // Headers already written to the stream
663                         return (length > 0) ? cnc.BeginWrite (request, bytes, 0, length, cb, state) : null;
664                 }
665
666                 void WriteHeaders ()
667                 {
668                         if (headersSent)
669                                 return;
670
671                         headersSent = true;
672                         string err_msg = null;
673                         if (!cnc.Write (request, headers, 0, headers.Length, ref err_msg))
674                                 throw new WebException ("Error writing request: " + err_msg, null, WebExceptionStatus.SendFailure, null);
675                 }
676
677                 internal void WriteRequest ()
678                 {
679                         if (requestWritten)
680                                 return;
681
682                         requestWritten = true;
683                         if (sendChunked)
684                                 return;
685
686                         if (!allowBuffering || writeBuffer == null)
687                                 return;
688
689                         byte [] bytes = writeBuffer.GetBuffer ();
690                         int length = (int) writeBuffer.Length;
691                         if (request.ContentLength != -1 && request.ContentLength < length) {
692                                 nextReadCalled = true;
693                                 cnc.Close (true);
694                                 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
695                                                         WebExceptionStatus.ServerProtocolViolation, null);
696                         }
697
698                         if (!headersSent) {
699                                 string method = request.Method;
700                                 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
701                                                         method == "TRACE");
702                                 if (!no_writestream)
703                                         request.InternalContentLength = length;
704                                 request.SendRequestHeaders (true);
705                         }
706                         WriteHeaders ();
707                         if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
708                                 return;
709                                 
710                         IAsyncResult result = null;
711                         if (length > 0)
712                                 result = cnc.BeginWrite (request, bytes, 0, length, null, null);
713                         
714                         if (!initRead) {
715                                 initRead = true;
716                                 WebConnection.InitRead (cnc);
717                         }
718
719                         if (length > 0) 
720                                 complete_request_written = cnc.EndWrite (request, result);
721                         else
722                                 complete_request_written = true;
723                 }
724
725                 internal void InternalClose ()
726                 {
727                         disposed = true;
728                 }
729
730                 public override void Close ()
731                 {
732                         if (sendChunked) {
733                                 if (disposed)
734                                         return;
735                                 disposed = true;
736                                 pending.WaitOne ();
737                                 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
738                                 string err_msg = null;
739                                 cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
740                                 return;
741                         }
742
743                         if (isRead) {
744                                 if (!nextReadCalled) {
745                                         CheckComplete ();
746                                         // If we have not read all the contents
747                                         if (!nextReadCalled) {
748                                                 nextReadCalled = true;
749                                                 cnc.Close (true);
750                                         }
751                                 }
752                                 return;
753                         } else if (!allowBuffering) {
754                                 complete_request_written = true;
755                                 if (!initRead) {
756                                         initRead = true;
757                                         WebConnection.InitRead (cnc);
758                                 }
759                                 return;
760                         }
761
762                         if (disposed || requestWritten)
763                                 return;
764
765                         long length = request.ContentLength;
766
767                         if (!sendChunked && length != -1 && totalWritten != length) {
768                                 IOException io = new IOException ("Cannot close the stream until all bytes are written");
769                                 nextReadCalled = true;
770                                 cnc.Close (true);
771                                 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
772                         }
773
774                         // Commented out the next line to fix xamarin bug #1512
775                         //WriteRequest ();
776                         disposed = true;
777                 }
778
779                 internal void KillBuffer ()
780                 {
781                         writeBuffer = null;
782                 }
783
784                 public override long Seek (long a, SeekOrigin b)
785                 {
786                         throw new NotSupportedException ();
787                 }
788                 
789                 public override void SetLength (long a)
790                 {
791                         throw new NotSupportedException ();
792                 }
793                 
794                 public override bool CanSeek {
795                         get { return false; }
796                 }
797
798                 public override bool CanRead {
799                         get { return !disposed && isRead; }
800                 }
801
802                 public override bool CanWrite {
803                         get { return !disposed && !isRead; }
804                 }
805
806                 public override long Length {
807                         get {
808                                 if (!isRead)
809                                         throw new NotSupportedException ();
810                                 return stream_length;
811                         }
812                 }
813
814                 public override long Position {
815                         get { throw new NotSupportedException (); }
816                         set { throw new NotSupportedException (); }
817                 }
818         }
819 }
820