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