2 // System.Net.WebConnectionStream
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
8 // (C) 2004 Novell, Inc (http://www.novell.com)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
34 using System.Threading;
38 class WebConnectionStream : Stream
40 static byte [] crlf = new byte [] { 13, 10 };
43 HttpWebRequest request;
53 ManualResetEvent pending;
56 MemoryStream writeBuffer;
61 object locker = new object ();
64 bool complete_request_written;
68 public WebConnectionStream (WebConnection cnc)
71 pending = new ManualResetEvent (true);
72 this.request = cnc.Data.request;
73 read_timeout = request.ReadWriteTimeout;
74 write_timeout = read_timeout;
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 != "") {
81 contentLength = Int32.Parse (clength);
82 if (contentLength == 0 && !IsNtlmAuth ()) {
86 contentLength = Int32.MaxValue;
89 contentLength = Int32.MaxValue;
93 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
95 read_timeout = request.ReadWriteTimeout;
96 write_timeout = read_timeout;
99 this.request = request;
100 allowBuffering = request.InternalAllowBuffering;
101 sendChunked = request.SendChunked;
103 pending = new ManualResetEvent (true);
104 else if (allowBuffering)
105 writeBuffer = new MemoryStream ();
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);
116 internal void CheckResponseInBuffer ()
118 if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
124 internal HttpWebRequest Request {
125 get { return request; }
128 internal WebConnection Connection {
132 public override bool CanTimeout {
147 throw new ArgumentOutOfRangeException ("value");
148 read_timeout = value;
157 return write_timeout;
162 throw new ArgumentOutOfRangeException ("value");
163 write_timeout = value;
167 internal bool CompleteRequestWritten {
168 get { return complete_request_written; }
171 internal bool SendChunked {
172 set { sendChunked = value; }
175 internal byte [] ReadBuffer {
176 set { readBuffer = value; }
179 internal int ReadBufferOffset {
180 set { readBufferOffset = value;}
183 internal int ReadBufferSize {
184 set { readBufferSize = value; }
187 internal byte[] WriteBuffer {
188 get { return writeBuffer.GetBuffer (); }
191 internal int WriteBufferLength {
192 get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
195 internal void ForceCompletion ()
197 if (!nextReadCalled) {
198 if (contentLength == Int32.MaxValue)
200 nextReadCalled = true;
205 internal void CheckComplete ()
207 bool nrc = nextReadCalled;
208 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
209 nextReadCalled = true;
214 internal void ReadAll ()
216 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
217 if (isRead && !nextReadCalled) {
218 nextReadCalled = true;
226 if (totalRead >= contentLength)
230 int diff = readBufferSize - readBufferOffset;
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)
243 buffer = new byte [8192];
246 while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
247 ms.Write (buffer, 0, read);
250 new_size = (int) ms.Length;
251 contentLength = new_size;
253 new_size = contentLength - totalRead;
254 b = new byte [new_size];
255 if (readBuffer != null && diff > 0) {
259 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
262 int remaining = new_size - diff;
264 while (remaining > 0 && r != 0) {
265 r = cnc.Read (request, b, diff, remaining);
272 readBufferOffset = 0;
273 readBufferSize = new_size;
275 nextReadCalled = true;
281 void WriteCallbackWrapper (IAsyncResult r)
283 WebAsyncResult result = r as WebAsyncResult;
284 if (result != null && result.AsyncWriteAll)
287 if (r.AsyncState != null) {
288 result = (WebAsyncResult) r.AsyncState;
289 result.InnerAsyncResult = r;
290 result.DoCallback ();
296 void ReadCallbackWrapper (IAsyncResult r)
298 WebAsyncResult result;
299 if (r.AsyncState != null) {
300 result = (WebAsyncResult) r.AsyncState;
301 result.InnerAsyncResult = r;
302 result.DoCallback ();
308 public override int Read (byte [] buffer, int offset, int size)
311 throw new NotSupportedException ("this stream does not allow reading");
313 if (totalRead >= contentLength)
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;
321 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
324 return EndRead (res);
327 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
328 AsyncCallback cb, object state)
331 throw new NotSupportedException ("this stream does not allow reading");
334 throw new ArgumentNullException ("buffer");
336 int length = buffer.Length;
337 if (size < 0 || offset < 0 || length < offset || length - offset < size)
338 throw new ArgumentOutOfRangeException ();
345 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
346 if (totalRead >= contentLength) {
347 result.SetCompleted (true, -1);
348 result.DoCallback ();
352 int remaining = readBufferSize - readBufferOffset;
354 int copy = (remaining > size) ? size : remaining;
355 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
356 readBufferOffset += copy;
360 if (size == 0 || totalRead >= contentLength) {
361 result.SetCompleted (true, copy);
362 result.DoCallback ();
365 result.NBytes = copy;
369 cb = new AsyncCallback (ReadCallbackWrapper);
371 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
372 size = contentLength - totalRead;
375 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
377 result.SetCompleted (true, result.NBytes);
378 result.DoCallback ();
383 public override int EndRead (IAsyncResult r)
385 WebAsyncResult result = (WebAsyncResult) r;
386 if (result.EndCalled) {
387 int xx = result.NBytes;
388 return (xx >= 0) ? xx : 0;
391 result.EndCalled = true;
393 if (!result.IsCompleted) {
396 nbytes = cnc.EndRead (request, result);
397 } catch (Exception exc) {
400 if (pendingReads == 0)
404 nextReadCalled = true;
406 result.SetCompleted (false, exc);
416 result.SetCompleted (false, nbytes + result.NBytes);
417 result.DoCallback ();
419 contentLength = totalRead;
424 if (pendingReads == 0)
428 if (totalRead >= contentLength && !nextReadCalled)
431 int nb = result.NBytes;
432 return (nb >= 0) ? nb : 0;
435 void WriteRequestAsyncCB (IAsyncResult r)
437 WebAsyncResult result = (WebAsyncResult) r.AsyncState;
439 cnc.EndWrite2 (request, r);
440 result.SetCompleted (false, 0);
443 WebConnection.InitRead (cnc);
445 } catch (Exception e) {
447 nextReadCalled = true;
449 if (e is System.Net.Sockets.SocketException)
450 e = new IOException ("Error writing request", e);
451 result.SetCompleted (false, e);
453 complete_request_written = true;
454 result.DoCallback ();
457 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
458 AsyncCallback cb, object state)
461 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
464 throw new NotSupportedException ("this stream does not allow writing");
467 throw new ArgumentNullException ("buffer");
469 int length = buffer.Length;
470 if (size < 0 || offset < 0 || length < offset || length - offset < size)
471 throw new ArgumentOutOfRangeException ();
480 WebAsyncResult result = new WebAsyncResult (cb, state);
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) {
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 ();
497 } catch (Exception exc) {
498 result.SetCompleted (true, exc);
499 result.DoCallback ();
502 result.SetCompleted (true, 0);
503 result.DoCallback ();
508 AsyncCallback callback = null;
510 callback = new AsyncCallback (WriteCallbackWrapper);
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);
528 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
529 totalWritten += size;
533 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
535 if (contentLength == -1)
538 long avail = contentLength - totalWritten;
541 nextReadCalled = true;
543 throw new ProtocolViolationException (
544 "The number of bytes to be written is greater than " +
545 "the specified ContentLength.");
549 public override void EndWrite (IAsyncResult r)
552 throw new ArgumentNullException ("r");
554 WebAsyncResult result = r as WebAsyncResult;
556 throw new ArgumentException ("Invalid IAsyncResult");
558 if (result.EndCalled)
561 result.EndCalled = true;
562 if (result.AsyncWriteAll) {
563 result.WaitUntilComplete ();
564 if (result.GotException)
565 throw result.Exception;
569 if (allowBuffering && !sendChunked)
572 if (result.GotException)
573 throw result.Exception;
576 cnc.EndWrite (request, result.InnerAsyncResult);
577 result.SetCompleted (false, 0);
578 } catch (Exception e) {
579 result.SetCompleted (false, e);
585 if (pendingWrites == 0)
592 public override void Write (byte [] buffer, int offset, int size)
595 throw new NotSupportedException ("This stream does not allow writing");
597 AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
598 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
599 if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
601 nextReadCalled = true;
603 throw new IOException ("Write timed out.");
609 public override void Flush ()
613 internal void SetHeaders (byte [] buffer, int offset, int size)
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) {
628 WebConnection.InitRead (cnc);
630 if (!sendChunked && cl == 0)
635 internal bool RequestWritten {
636 get { return requestWritten; }
639 IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
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;
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);
659 internal void WriteRequest ()
665 requestWritten = true;
669 if (!allowBuffering || writeBuffer == null)
672 byte [] bytes = writeBuffer.GetBuffer ();
673 int length = (int) writeBuffer.Length;
674 if (request.ContentLength != -1 && request.ContentLength < length) {
675 nextReadCalled = true;
677 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
678 WebExceptionStatus.ServerProtocolViolation, null);
682 string method = request.Method;
683 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
684 method == "TRACE" || method == "DELETE");
686 request.InternalContentLength = length;
687 request.SendRequestHeaders ();
690 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
693 IAsyncResult result = null;
695 result = cnc.BeginWrite (request, bytes, 0, length, null, null);
699 WebConnection.InitRead (cnc);
703 complete_request_written = cnc.EndWrite (request, result);
705 complete_request_written = true;
708 internal void InternalClose ()
713 public override void Close ()
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);
727 if (!nextReadCalled) {
729 // If we have not read all the contents
730 if (!nextReadCalled) {
731 nextReadCalled = true;
736 } else if (!allowBuffering) {
737 complete_request_written = true;
740 WebConnection.InitRead (cnc);
745 if (disposed || requestWritten)
748 long length = request.ContentLength;
750 if (!sendChunked && length != -1 && totalWritten != length) {
751 IOException io = new IOException ("Cannot close the stream until all bytes are written");
752 nextReadCalled = true;
754 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
761 internal void KillBuffer ()
766 public override long Seek (long a, SeekOrigin b)
768 throw new NotSupportedException ();
771 public override void SetLength (long a)
773 throw new NotSupportedException ();
776 public override bool CanSeek {
777 get { return false; }
780 public override bool CanRead {
781 get { return isRead; }
784 public override bool CanWrite {
785 get { return !isRead; }
788 public override long Length {
789 get { throw new NotSupportedException (); }
792 public override long Position {
793 get { throw new NotSupportedException (); }
794 set { throw new NotSupportedException (); }