Merge branch 'sgen-disable-gc'
[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 contentLength;
48                 int totalRead;
49                 internal long totalWritten;
50                 bool nextReadCalled;
51                 int pendingReads;
52                 int pendingWrites;
53                 ManualResetEvent pending;
54                 bool allowBuffering;
55                 bool sendChunked;
56                 MemoryStream writeBuffer;
57                 bool requestWritten;
58                 byte [] headers;
59                 bool disposed;
60                 bool headersSent;
61                 object locker = new object ();
62                 bool initRead;
63                 bool read_eof;
64                 bool complete_request_written;
65                 int read_timeout;
66                 int write_timeout;
67                 AsyncCallback cb_wrapper; // Calls to ReadCallbackWrapper or WriteCallbacWrapper
68                 internal bool IgnoreIOErrors;
69
70                 public WebConnectionStream (WebConnection cnc)
71                 {
72                         isRead = true;
73                         cb_wrapper = new AsyncCallback (ReadCallbackWrapper);
74                         pending = new ManualResetEvent (true);
75                         this.request = cnc.Data.request;
76                         read_timeout = request.ReadWriteTimeout;
77                         write_timeout = read_timeout;
78                         this.cnc = cnc;
79                         string contentType = cnc.Data.Headers ["Transfer-Encoding"];
80                         bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
81                         string clength = cnc.Data.Headers ["Content-Length"];
82                         if (!chunkedRead && clength != null && clength != "") {
83                                 try {
84                                         contentLength = Int32.Parse (clength);
85                                         if (contentLength == 0 && !IsNtlmAuth ()) {
86                                                 ReadAll ();
87                                         }
88                                 } catch {
89                                         contentLength = Int32.MaxValue;
90                                 }
91                         } else {
92                                 contentLength = Int32.MaxValue;
93                         }
94                 }
95
96                 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
97                 {
98                         read_timeout = request.ReadWriteTimeout;
99                         write_timeout = read_timeout;
100                         isRead = false;
101                         cb_wrapper = new AsyncCallback (WriteCallbackWrapper);
102                         this.cnc = cnc;
103                         this.request = request;
104                         allowBuffering = request.InternalAllowBuffering;
105                         sendChunked = request.SendChunked;
106                         if (sendChunked)
107                                 pending = new ManualResetEvent (true);
108                         else if (allowBuffering)
109                                 writeBuffer = new MemoryStream ();
110                 }
111
112                 bool IsNtlmAuth ()
113                 {
114                         bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
115                         string header_name = (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate";
116                         string authHeader = cnc.Data.Headers [header_name];
117                         return (authHeader != null && authHeader.IndexOf ("NTLM", StringComparison.Ordinal) != -1);
118                 }
119
120                 internal void CheckResponseInBuffer ()
121                 {
122                         if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
123                                 if (!IsNtlmAuth ())
124                                         ReadAll ();
125                         }
126                 }
127
128                 internal HttpWebRequest Request {
129                         get { return request; }
130                 }
131
132                 internal WebConnection Connection {
133                         get { return cnc; }
134                 }
135 #if NET_2_0
136                 public override bool CanTimeout {
137                         get { return true; }
138                 }
139 #endif
140
141 #if NET_2_0
142                 public override
143 #endif
144                 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 #if NET_2_0
157                 public override
158 #endif
159                 int WriteTimeout {
160                         get {
161                                 return write_timeout;
162                         }
163
164                         set {
165                                 if (value < -1)
166                                         throw new ArgumentOutOfRangeException ("value");
167                                 write_timeout = value;
168                         }
169                 }
170
171                 internal bool CompleteRequestWritten {
172                         get { return complete_request_written; }
173                 }
174
175                 internal bool SendChunked {
176                         set { sendChunked = value; }
177                 }
178
179                 internal byte [] ReadBuffer {
180                         set { readBuffer = value; }
181                 }
182
183                 internal int ReadBufferOffset {
184                         set { readBufferOffset = value;}
185                 }
186                 
187                 internal int ReadBufferSize {
188                         set { readBufferSize = value; }
189                 }
190                 
191                 internal byte[] WriteBuffer {
192                         get { return writeBuffer.GetBuffer (); }
193                 }
194
195                 internal int WriteBufferLength {
196                         get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
197                 }
198
199                 internal void ForceCompletion ()
200                 {
201                         if (!nextReadCalled) {
202                                 if (contentLength == Int32.MaxValue)
203                                         contentLength = 0;
204                                 nextReadCalled = true;
205                                 cnc.NextRead ();
206                         }
207                 }
208                 
209                 internal void CheckComplete ()
210                 {
211                         bool nrc = nextReadCalled;
212                         if (!nrc && readBufferSize - readBufferOffset == contentLength) {
213                                 nextReadCalled = true;
214                                 cnc.NextRead ();
215                         }
216                 }
217
218                 internal void ReadAll ()
219                 {
220                         if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
221                                 if (isRead && !nextReadCalled) {
222                                         nextReadCalled = true;
223                                         cnc.NextRead ();
224                                 }
225                                 return;
226                         }
227
228                         pending.WaitOne ();
229                         lock (locker) {
230                                 if (totalRead >= contentLength)
231                                         return;
232                                 
233                                 byte [] b = null;
234                                 int diff = readBufferSize - readBufferOffset;
235                                 int new_size;
236
237                                 if (contentLength == Int32.MaxValue) {
238                                         MemoryStream ms = new MemoryStream ();
239                                         byte [] buffer = null;
240                                         if (readBuffer != null && diff > 0) {
241                                                 ms.Write (readBuffer, readBufferOffset, diff);
242                                                 if (readBufferSize >= 8192)
243                                                         buffer = readBuffer;
244                                         }
245
246                                         if (buffer == null)
247                                                 buffer = new byte [8192];
248
249                                         int read;
250                                         while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
251                                                 ms.Write (buffer, 0, read);
252
253                                         b = ms.GetBuffer ();
254                                         new_size = (int) ms.Length;
255                                         contentLength = new_size;
256                                 } else {
257                                         new_size = contentLength - totalRead;
258                                         b = new byte [new_size];
259                                         if (readBuffer != null && diff > 0) {
260                                                 if (diff > new_size)
261                                                         diff = new_size;
262
263                                                 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
264                                         }
265                                         
266                                         int remaining = new_size - diff;
267                                         int r = -1;
268                                         while (remaining > 0 && r != 0) {
269                                                 r = cnc.Read (request, b, diff, remaining);
270                                                 remaining -= r;
271                                                 diff += r;
272                                         }
273                                 }
274
275                                 readBuffer = b;
276                                 readBufferOffset = 0;
277                                 readBufferSize = new_size;
278                                 totalRead = 0;
279                                 nextReadCalled = true;
280                         }
281
282                         cnc.NextRead ();
283                 }
284
285                 void WriteCallbackWrapper (IAsyncResult r)
286                 {
287                         WebAsyncResult result = r as WebAsyncResult;
288                         if (result != null && result.AsyncWriteAll)
289                                 return;
290
291                         if (r.AsyncState != null) {
292                                 result = (WebAsyncResult) r.AsyncState;
293                                 result.InnerAsyncResult = r;
294                                 result.DoCallback ();
295                         } else {
296                                 try {
297                                         EndWrite (r);
298                                 } catch {
299                                 }
300                         }
301                 }
302
303                 void ReadCallbackWrapper (IAsyncResult r)
304                 {
305                         WebAsyncResult result;
306                         if (r.AsyncState != null) {
307                                 result = (WebAsyncResult) r.AsyncState;
308                                 result.InnerAsyncResult = r;
309                                 result.DoCallback ();
310                         } else {
311                                 try {
312                                         EndRead (r);
313                                 } catch {
314                                 }
315                         }
316                 }
317
318                 public override int Read (byte [] buffer, int offset, int size)
319                 {
320                         AsyncCallback cb = cb_wrapper;
321                         WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
322                         if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
323                                 nextReadCalled = true;
324                                 cnc.Close (true);
325                                 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
326                         }
327
328                         return EndRead (res);
329                 }
330
331                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
332                                                         AsyncCallback cb, object state)
333                 {
334                         if (!isRead)
335                                 throw new NotSupportedException ("this stream does not allow reading");
336
337                         if (buffer == null)
338                                 throw new ArgumentNullException ("buffer");
339
340                         int length = buffer.Length;
341                         if (offset < 0 || length < offset)
342                                 throw new ArgumentOutOfRangeException ("offset");
343                         if (size < 0 || (length - offset) < size)
344                                 throw new ArgumentOutOfRangeException ("size");
345
346                         lock (locker) {
347                                 pendingReads++;
348                                 pending.Reset ();
349                         }
350
351                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
352                         if (totalRead >= contentLength) {
353                                 result.SetCompleted (true, -1);
354                                 result.DoCallback ();
355                                 return result;
356                         }
357                         
358                         int remaining = readBufferSize - readBufferOffset;
359                         if (remaining > 0) {
360                                 int copy = (remaining > size) ? size : remaining;
361                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
362                                 readBufferOffset += copy;
363                                 offset += copy;
364                                 size -= copy;
365                                 totalRead += copy;
366                                 if (size == 0 || totalRead >= contentLength) {
367                                         result.SetCompleted (true, copy);
368                                         result.DoCallback ();
369                                         return result;
370                                 }
371                                 result.NBytes = copy;
372                         }
373
374                         if (cb != null)
375                                 cb = cb_wrapper;
376
377                         if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
378                                 size = contentLength - totalRead;
379
380                         if (!read_eof) {
381                                 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
382                         } else {
383                                 result.SetCompleted (true, result.NBytes);
384                                 result.DoCallback ();
385                         }
386                         return result;
387                 }
388
389                 public override int EndRead (IAsyncResult r)
390                 {
391                         WebAsyncResult result = (WebAsyncResult) r;
392                         if (result.EndCalled) {
393                                 int xx = result.NBytes;
394                                 return (xx >= 0) ? xx : 0;
395                         }
396
397                         result.EndCalled = true;
398
399                         if (!result.IsCompleted) {
400                                 int nbytes = -1;
401                                 try {
402                                         nbytes = cnc.EndRead (request, result);
403                                 } catch (Exception exc) {
404                                         lock (locker) {
405                                                 pendingReads--;
406                                                 if (pendingReads == 0)
407                                                         pending.Set ();
408                                         }
409
410                                         nextReadCalled = true;
411                                         cnc.Close (true);
412                                         result.SetCompleted (false, exc);
413                                         result.DoCallback ();
414                                         throw;
415                                 }
416
417                                 if (nbytes < 0) {
418                                         nbytes = 0;
419                                         read_eof = true;
420                                 }
421
422                                 totalRead += nbytes;
423                                 result.SetCompleted (false, nbytes + result.NBytes);
424                                 result.DoCallback ();
425                                 if (nbytes == 0)
426                                         contentLength = totalRead;
427                         }
428
429                         lock (locker) {
430                                 pendingReads--;
431                                 if (pendingReads == 0)
432                                         pending.Set ();
433                         }
434
435                         if (totalRead >= contentLength && !nextReadCalled)
436                                 ReadAll ();
437
438                         int nb = result.NBytes;
439                         return (nb >= 0) ? nb : 0;
440                 }
441
442                 void WriteRequestAsyncCB (IAsyncResult r)
443                 {
444                         WebAsyncResult result = (WebAsyncResult) r.AsyncState;
445                         try {
446                                 cnc.EndWrite2 (request, r);
447                                 result.SetCompleted (false, 0);
448                                 if (!initRead) {
449                                         initRead = true;
450                                         WebConnection.InitRead (cnc);
451                                 }
452                         } catch (Exception e) {
453                                 KillBuffer ();
454                                 nextReadCalled = true;
455                                 cnc.Close (true);
456                                 if (e is System.Net.Sockets.SocketException)
457                                         e = new IOException ("Error writing request", e);
458                                 result.SetCompleted (false, e);
459                         }
460                         complete_request_written = true;
461                         result.DoCallback ();
462                 }
463
464                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
465                                                         AsyncCallback cb, object state)
466                 {
467                         if (request.Aborted)
468                                 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
469
470                         if (isRead)
471                                 throw new NotSupportedException ("this stream does not allow writing");
472
473                         if (buffer == null)
474                                 throw new ArgumentNullException ("buffer");
475
476                         int length = buffer.Length;
477                         if (offset < 0 || length < offset)
478                                 throw new ArgumentOutOfRangeException ("offset");
479                         if (size < 0 || (length - offset) < size)
480                                 throw new ArgumentOutOfRangeException ("size");
481
482                         if (sendChunked) {
483                                 lock (locker) {
484                                         pendingWrites++;
485                                         pending.Reset ();
486                                 }
487                         }
488
489                         WebAsyncResult result = new WebAsyncResult (cb, state);
490                         if (!sendChunked)
491                                 CheckWriteOverflow (request.ContentLength, totalWritten, size);
492                         if (allowBuffering && !sendChunked) {
493                                 if (writeBuffer == null)
494                                         writeBuffer = new MemoryStream ();
495                                 writeBuffer.Write (buffer, offset, size);
496                                 totalWritten += size;
497                                 if (request.ContentLength > 0 && totalWritten == request.ContentLength) {
498                                         try {
499                                                 result.AsyncWriteAll = true;
500                                                 result.InnerAsyncResult = WriteRequestAsync (new AsyncCallback (WriteRequestAsyncCB), result);
501                                                 if (result.InnerAsyncResult == null) {
502                                                         if (!result.IsCompleted)
503                                                                 result.SetCompleted (true, 0);
504                                                         result.DoCallback ();
505                                                 }
506                                         } catch (Exception exc) {
507                                                 result.SetCompleted (true, exc);
508                                                 result.DoCallback ();
509                                         }
510                                 } else {
511                                         result.SetCompleted (true, 0);
512                                         result.DoCallback ();
513                                 }
514                                 return result;
515                         }
516
517                         AsyncCallback callback = null;
518                         if (cb != null)
519                                 callback = cb_wrapper;
520
521                         if (sendChunked) {
522                                 WriteRequest ();
523
524                                 string cSize = String.Format ("{0:X}\r\n", size);
525                                 byte [] head = Encoding.ASCII.GetBytes (cSize);
526                                 int chunkSize = 2 + size + head.Length;
527                                 byte [] newBuffer = new byte [chunkSize];
528                                 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
529                                 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
530                                 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
531
532                                 buffer = newBuffer;
533                                 offset = 0;
534                                 size = chunkSize;
535                         }
536
537                         try {
538                                 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
539                         } catch (Exception) {
540                                 if (!IgnoreIOErrors)
541                                         throw;
542                                 result.SetCompleted (true, 0);
543                                 result.DoCallback ();
544                         }
545                         totalWritten += size;
546                         return result;
547                 }
548
549                 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
550                 {
551                         if (contentLength == -1)
552                                 return;
553
554                         long avail = contentLength - totalWritten;
555                         if (size > avail) {
556                                 KillBuffer ();
557                                 nextReadCalled = true;
558                                 cnc.Close (true);
559                                 throw new ProtocolViolationException (
560                                         "The number of bytes to be written is greater than " +
561                                         "the specified ContentLength.");
562                         }
563                 }
564
565                 public override void EndWrite (IAsyncResult r)
566                 {
567                         if (r == null)
568                                 throw new ArgumentNullException ("r");
569
570                         WebAsyncResult result = r as WebAsyncResult;
571                         if (result == null)
572                                 throw new ArgumentException ("Invalid IAsyncResult");
573
574                         if (result.EndCalled)
575                                 return;
576
577                         result.EndCalled = true;
578                         if (result.AsyncWriteAll) {
579                                 result.WaitUntilComplete ();
580                                 if (result.GotException)
581                                         throw result.Exception;
582                                 return;
583                         }
584
585                         if (allowBuffering && !sendChunked)
586                                 return;
587
588                         if (result.GotException)
589                                 throw result.Exception;
590
591                         try {
592                                 cnc.EndWrite2 (request, result.InnerAsyncResult);
593                                 result.SetCompleted (false, 0);
594                                 result.DoCallback ();
595                         } catch (Exception e) {
596                                 if (IgnoreIOErrors)
597                                         result.SetCompleted (false, 0);
598                                 else
599                                         result.SetCompleted (false, e);
600                                 result.DoCallback ();
601                                 if (!IgnoreIOErrors)
602                                         throw;
603                         } finally {
604                                 if (sendChunked) {
605                                         lock (locker) {
606                                                 pendingWrites--;
607                                                 if (pendingWrites == 0)
608                                                         pending.Set ();
609                                         }
610                                 }
611                         }
612                 }
613                 
614                 public override void Write (byte [] buffer, int offset, int size)
615                 {
616                         AsyncCallback cb = cb_wrapper;
617                         WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
618                         if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
619                                 KillBuffer ();
620                                 nextReadCalled = true;
621                                 cnc.Close (true);
622                                 throw new IOException ("Write timed out.");
623                         }
624
625                         EndWrite (res);
626                 }
627
628                 public override void Flush ()
629                 {
630                 }
631
632                 internal void SetHeaders (byte [] buffer)
633                 {
634                         if (headersSent)
635                                 return;
636
637                         headers = buffer;
638                         long cl = request.ContentLength;
639                         string method = request.Method;
640                         bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
641                                                 method == "TRACE" || method == "DELETE");
642                         if (sendChunked || cl > -1 || no_writestream) {
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" || method == "DELETE");
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                         WriteRequest ();
775                         disposed = true;
776                 }
777
778                 internal void KillBuffer ()
779                 {
780                         writeBuffer = null;
781                 }
782
783                 public override long Seek (long a, SeekOrigin b)
784                 {
785                         throw new NotSupportedException ();
786                 }
787                 
788                 public override void SetLength (long a)
789                 {
790                         throw new NotSupportedException ();
791                 }
792                 
793                 public override bool CanSeek {
794                         get { return false; }
795                 }
796
797                 public override bool CanRead {
798                         get { return !disposed && isRead; }
799                 }
800
801                 public override bool CanWrite {
802                         get { return !disposed && !isRead; }
803                 }
804
805                 public override long Length {
806                         get { throw new NotSupportedException (); }
807                 }
808
809                 public override long Position {
810                         get { throw new NotSupportedException (); }
811                         set { throw new NotSupportedException (); }
812                 }
813         }
814 }
815