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