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