2009-07-02 Gonzalo Paniagua Javier <gonzalo@novell.com>
[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                         if (!isRead)
311                                 throw new NotSupportedException ("this stream does not allow reading");
312
313                         if (totalRead >= contentLength)
314                                 return 0;
315
316                         AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
317                         WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
318                         if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
319                                 nextReadCalled = true;
320                                 cnc.Close (true);
321                                 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
322                         }
323
324                         return EndRead (res);
325                 }
326
327                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
328                                                         AsyncCallback cb, object state)
329                 {
330                         if (!isRead)
331                                 throw new NotSupportedException ("this stream does not allow reading");
332
333                         if (buffer == null)
334                                 throw new ArgumentNullException ("buffer");
335
336                         int length = buffer.Length;
337                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
338                                 throw new ArgumentOutOfRangeException ();
339
340                         lock (locker) {
341                                 pendingReads++;
342                                 pending.Reset ();
343                         }
344
345                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
346                         if (totalRead >= contentLength) {
347                                 result.SetCompleted (true, -1);
348                                 result.DoCallback ();
349                                 return result;
350                         }
351                         
352                         int remaining = readBufferSize - readBufferOffset;
353                         if (remaining > 0) {
354                                 int copy = (remaining > size) ? size : remaining;
355                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
356                                 readBufferOffset += copy;
357                                 offset += copy;
358                                 size -= copy;
359                                 totalRead += copy;
360                                 if (size == 0 || totalRead >= contentLength) {
361                                         result.SetCompleted (true, copy);
362                                         result.DoCallback ();
363                                         return result;
364                                 }
365                                 result.NBytes = copy;
366                         }
367
368                         if (cb != null)
369                                 cb = new AsyncCallback (ReadCallbackWrapper);
370
371                         if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
372                                 size = contentLength - totalRead;
373
374                         if (!read_eof) {
375                                 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
376                         } else {
377                                 result.SetCompleted (true, result.NBytes);
378                                 result.DoCallback ();
379                         }
380                         return result;
381                 }
382
383                 public override int EndRead (IAsyncResult r)
384                 {
385                         WebAsyncResult result = (WebAsyncResult) r;
386                         if (result.EndCalled) {
387                                 int xx = result.NBytes;
388                                 return (xx >= 0) ? xx : 0;
389                         }
390
391                         result.EndCalled = true;
392
393                         if (!result.IsCompleted) {
394                                 int nbytes = -1;
395                                 try {
396                                         nbytes = cnc.EndRead (request, result);
397                                 } catch (Exception exc) {
398                                         lock (locker) {
399                                                 pendingReads--;
400                                                 if (pendingReads == 0)
401                                                         pending.Set ();
402                                         }
403
404                                         nextReadCalled = true;
405                                         cnc.Close (true);
406                                         result.SetCompleted (false, exc);
407                                         throw;
408                                 }
409
410                                 if (nbytes < 0) {
411                                         nbytes = 0;
412                                         read_eof = true;
413                                 }
414
415                                 totalRead += nbytes;
416                                 result.SetCompleted (false, nbytes + result.NBytes);
417                                 result.DoCallback ();
418                                 if (nbytes == 0)
419                                         contentLength = totalRead;
420                         }
421
422                         lock (locker) {
423                                 pendingReads--;
424                                 if (pendingReads == 0)
425                                         pending.Set ();
426                         }
427
428                         if (totalRead >= contentLength && !nextReadCalled)
429                                 ReadAll ();
430
431                         int nb = result.NBytes;
432                         return (nb >= 0) ? nb : 0;
433                 }
434
435                 void WriteRequestAsyncCB (IAsyncResult r)
436                 {
437                         WebAsyncResult result = (WebAsyncResult) r.AsyncState;
438                         try {
439                                 cnc.EndWrite2 (request, r);
440                                 result.SetCompleted (false, 0);
441                                 if (!initRead) {
442                                         initRead = true;
443                                         WebConnection.InitRead (cnc);
444                                 }
445                         } catch (Exception e) {
446                                 KillBuffer ();
447                                 nextReadCalled = true;
448                                 cnc.Close (true);
449                                 if (e is System.Net.Sockets.SocketException)
450                                         e = new IOException ("Error writing request", e);
451                                 result.SetCompleted (false, e);
452                         }
453                         complete_request_written = true;
454                         result.DoCallback ();
455                 }
456
457                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
458                                                         AsyncCallback cb, object state)
459                 {
460                         if (request.Aborted)
461                                 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
462
463                         if (isRead)
464                                 throw new NotSupportedException ("this stream does not allow writing");
465
466                         if (buffer == null)
467                                 throw new ArgumentNullException ("buffer");
468
469                         int length = buffer.Length;
470                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
471                                 throw new ArgumentOutOfRangeException ();
472
473                         if (sendChunked) {
474                                 lock (locker) {
475                                         pendingWrites++;
476                                         pending.Reset ();
477                                 }
478                         }
479
480                         WebAsyncResult result = new WebAsyncResult (cb, state);
481                         if (!sendChunked)
482                                 CheckWriteOverflow (request.ContentLength, totalWritten, size);
483                         if (allowBuffering && !sendChunked) {
484                                 if (writeBuffer == null)
485                                         writeBuffer = new MemoryStream ();
486                                 writeBuffer.Write (buffer, offset, size);
487                                 totalWritten += size;
488                                 if (request.ContentLength > 0 && totalWritten == request.ContentLength) {
489                                         try {
490                                                 result.AsyncWriteAll = true;
491                                                 result.InnerAsyncResult = WriteRequestAsync (new AsyncCallback (WriteRequestAsyncCB), result);
492                                                 if (result.InnerAsyncResult == null) {
493                                                         if (!result.IsCompleted)
494                                                                 result.SetCompleted (true, 0);
495                                                         result.DoCallback ();
496                                                 }
497                                         } catch (Exception exc) {
498                                                 result.SetCompleted (true, exc);
499                                                 result.DoCallback ();
500                                         }
501                                 } else {
502                                         result.SetCompleted (true, 0);
503                                         result.DoCallback ();
504                                 }
505                                 return result;
506                         }
507
508                         AsyncCallback callback = null;
509                         if (cb != null)
510                                 callback = new AsyncCallback (WriteCallbackWrapper);
511
512                         if (sendChunked) {
513                                 WriteRequest ();
514
515                                 string cSize = String.Format ("{0:X}\r\n", size);
516                                 byte [] head = Encoding.ASCII.GetBytes (cSize);
517                                 int chunkSize = 2 + size + head.Length;
518                                 byte [] newBuffer = new byte [chunkSize];
519                                 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
520                                 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
521                                 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
522
523                                 buffer = newBuffer;
524                                 offset = 0;
525                                 size = chunkSize;
526                         }
527
528                         result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
529                         totalWritten += size;
530                         return result;
531                 }
532
533                 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
534                 {
535                         if (contentLength == -1)
536                                 return;
537
538                         long avail = contentLength - totalWritten;
539                         if (size > avail) {
540                                 KillBuffer ();
541                                 nextReadCalled = true;
542                                 cnc.Close (true);
543                                 throw new ProtocolViolationException (
544                                         "The number of bytes to be written is greater than " +
545                                         "the specified ContentLength.");
546                         }
547                 }
548
549                 public override void EndWrite (IAsyncResult r)
550                 {
551                         if (r == null)
552                                 throw new ArgumentNullException ("r");
553
554                         WebAsyncResult result = r as WebAsyncResult;
555                         if (result == null)
556                                 throw new ArgumentException ("Invalid IAsyncResult");
557
558                         if (result.EndCalled)
559                                 return;
560
561                         result.EndCalled = true;
562                         if (result.AsyncWriteAll) {
563                                 result.WaitUntilComplete ();
564                                 if (result.GotException)
565                                         throw result.Exception;
566                                 return;
567                         }
568
569                         if (allowBuffering && !sendChunked)
570                                 return;
571
572                         if (result.GotException)
573                                 throw result.Exception;
574
575                         try {
576                                 cnc.EndWrite (request, result.InnerAsyncResult);
577                                 result.SetCompleted (false, 0);
578                         } catch (Exception e) {
579                                 result.SetCompleted (false, e);
580                                 throw;
581                         } finally {
582                                 if (sendChunked) {
583                                         lock (locker) {
584                                                 pendingWrites--;
585                                                 if (pendingWrites == 0)
586                                                         pending.Set ();
587                                         }
588                                 }
589                         }
590                 }
591                 
592                 public override void Write (byte [] buffer, int offset, int size)
593                 {
594                         if (isRead)
595                                 throw new NotSupportedException ("This stream does not allow writing");
596
597                         AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
598                         WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
599                         if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
600                                 KillBuffer ();
601                                 nextReadCalled = true;
602                                 cnc.Close (true);
603                                 throw new IOException ("Write timed out.");
604                         }
605
606                         EndWrite (res);
607                 }
608
609                 public override void Flush ()
610                 {
611                 }
612
613                 internal void SetHeaders (byte [] buffer, int offset, int size)
614                 {
615                         if (headersSent)
616                                 return;
617
618                         headers = new byte [size];
619                         Buffer.BlockCopy (buffer, offset, headers, 0, size);
620                         long cl = request.ContentLength;
621                         string method = request.Method;
622                         bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
623                                                 method == "TRACE" || method == "DELETE");
624                         if (sendChunked || cl > -1 || no_writestream) {
625                                 WriteHeaders ();
626                                 if (!initRead) {
627                                         initRead = true;
628                                         WebConnection.InitRead (cnc);
629                                 }
630                                 if (!sendChunked && cl == 0)
631                                         Close ();
632                         }
633                 }
634
635                 internal bool RequestWritten {
636                         get { return requestWritten; }
637                 }
638
639                 IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
640                 {
641                         requestWritten = true;
642                         byte [] bytes = writeBuffer.GetBuffer ();
643                         int length = (int) writeBuffer.Length;
644                         // Headers already written to the stream
645                         return (length > 0) ? cnc.BeginWrite (request, bytes, 0, length, cb, state) : null;
646                 }
647
648                 void WriteHeaders ()
649                 {
650                         if (headersSent)
651                                 return;
652
653                         headersSent = true;
654                         string err_msg = null;
655                         if (!cnc.Write (request, headers, 0, headers.Length, ref err_msg))
656                                 throw new WebException ("Error writing request: " + err_msg, null, WebExceptionStatus.SendFailure, null);
657                 }
658
659                 internal void WriteRequest ()
660                 {
661                         if (requestWritten)
662                                 return;
663
664                         if (sendChunked) {
665                                 requestWritten = true;
666                                 return;
667                         }
668
669                         if (!allowBuffering || writeBuffer == null)
670                                 return;
671
672                         byte [] bytes = writeBuffer.GetBuffer ();
673                         int length = (int) writeBuffer.Length;
674                         if (request.ContentLength != -1 && request.ContentLength < length) {
675                                 nextReadCalled = true;
676                                 cnc.Close (true);
677                                 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
678                                                         WebExceptionStatus.ServerProtocolViolation, null);
679                         }
680
681                         if (!headersSent) {
682                                 string method = request.Method;
683                                 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
684                                                         method == "TRACE" || method == "DELETE");
685                                 if (!no_writestream)
686                                         request.InternalContentLength = length;
687                                 request.SendRequestHeaders ();
688                         }
689                         WriteHeaders ();
690                         if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
691                                 return;
692                                 
693                         IAsyncResult result = null;
694                         if (length > 0)
695                                 result = cnc.BeginWrite (request, bytes, 0, length, null, null);
696                         
697                         if (!initRead) {
698                                 initRead = true;
699                                 WebConnection.InitRead (cnc);
700                         }
701
702                         if (length > 0) 
703                                 complete_request_written = cnc.EndWrite (request, result);
704                         else
705                                 complete_request_written = true;
706                 }
707
708                 internal void InternalClose ()
709                 {
710                         disposed = true;
711                 }
712
713                 public override void Close ()
714                 {
715                         if (sendChunked) {
716                                 if (disposed)
717                                         return;
718                                 disposed = true;
719                                 pending.WaitOne ();
720                                 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
721                                 string err_msg = null;
722                                 cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
723                                 return;
724                         }
725
726                         if (isRead) {
727                                 if (!nextReadCalled) {
728                                         CheckComplete ();
729                                         // If we have not read all the contents
730                                         if (!nextReadCalled) {
731                                                 nextReadCalled = true;
732                                                 cnc.Close (true);
733                                         }
734                                 }
735                                 return;
736                         } else if (!allowBuffering) {
737                                 complete_request_written = true;
738                                 if (!initRead) {
739                                         initRead = true;
740                                         WebConnection.InitRead (cnc);
741                                 }
742                                 return;
743                         }
744
745                         if (disposed || requestWritten)
746                                 return;
747
748                         long length = request.ContentLength;
749
750                         if (!sendChunked && length != -1 && totalWritten != length) {
751                                 IOException io = new IOException ("Cannot close the stream until all bytes are written");
752                                 nextReadCalled = true;
753                                 cnc.Close (true);
754                                 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
755                         }
756
757                         WriteRequest ();
758                         disposed = true;
759                 }
760
761                 internal void KillBuffer ()
762                 {
763                         writeBuffer = null;
764                 }
765
766                 public override long Seek (long a, SeekOrigin b)
767                 {
768                         throw new NotSupportedException ();
769                 }
770                 
771                 public override void SetLength (long a)
772                 {
773                         throw new NotSupportedException ();
774                 }
775                 
776                 public override bool CanSeek {
777                         get { return false; }
778                 }
779
780                 public override bool CanRead {
781                         get { return isRead; }
782                 }
783
784                 public override bool CanWrite {
785                         get { return !isRead; }
786                 }
787
788                 public override long Length {
789                         get { throw new NotSupportedException (); }
790                 }
791
792                 public override long Position {
793                         get { throw new NotSupportedException (); }
794                         set { throw new NotSupportedException (); }
795                 }
796         }
797 }
798