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)
310 AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
311 WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
312 if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
313 nextReadCalled = true;
315 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
318 return EndRead (res);
321 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
322 AsyncCallback cb, object state)
325 throw new NotSupportedException ("this stream does not allow reading");
328 throw new ArgumentNullException ("buffer");
330 int length = buffer.Length;
331 if (offset < 0 || length < offset)
332 throw new ArgumentOutOfRangeException ("offset");
333 if (size < 0 || (length - offset) < size)
334 throw new ArgumentOutOfRangeException ("size");
341 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
342 if (totalRead >= contentLength) {
343 result.SetCompleted (true, -1);
344 result.DoCallback ();
348 int remaining = readBufferSize - readBufferOffset;
350 int copy = (remaining > size) ? size : remaining;
351 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
352 readBufferOffset += copy;
356 if (size == 0 || totalRead >= contentLength) {
357 result.SetCompleted (true, copy);
358 result.DoCallback ();
361 result.NBytes = copy;
365 cb = new AsyncCallback (ReadCallbackWrapper);
367 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
368 size = contentLength - totalRead;
371 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
373 result.SetCompleted (true, result.NBytes);
374 result.DoCallback ();
379 public override int EndRead (IAsyncResult r)
381 WebAsyncResult result = (WebAsyncResult) r;
382 if (result.EndCalled) {
383 int xx = result.NBytes;
384 return (xx >= 0) ? xx : 0;
387 result.EndCalled = true;
389 if (!result.IsCompleted) {
392 nbytes = cnc.EndRead (request, result);
393 } catch (Exception exc) {
396 if (pendingReads == 0)
400 nextReadCalled = true;
402 result.SetCompleted (false, exc);
412 result.SetCompleted (false, nbytes + result.NBytes);
413 result.DoCallback ();
415 contentLength = totalRead;
420 if (pendingReads == 0)
424 if (totalRead >= contentLength && !nextReadCalled)
427 int nb = result.NBytes;
428 return (nb >= 0) ? nb : 0;
431 void WriteRequestAsyncCB (IAsyncResult r)
433 WebAsyncResult result = (WebAsyncResult) r.AsyncState;
435 cnc.EndWrite2 (request, r);
436 result.SetCompleted (false, 0);
439 WebConnection.InitRead (cnc);
441 } catch (Exception e) {
443 nextReadCalled = true;
445 if (e is System.Net.Sockets.SocketException)
446 e = new IOException ("Error writing request", e);
447 result.SetCompleted (false, e);
449 complete_request_written = true;
450 result.DoCallback ();
453 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
454 AsyncCallback cb, object state)
457 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
460 throw new NotSupportedException ("this stream does not allow writing");
463 throw new ArgumentNullException ("buffer");
465 int length = buffer.Length;
466 if (offset < 0 || length < offset)
467 throw new ArgumentOutOfRangeException ("offset");
468 if (size < 0 || (length - offset) < size)
469 throw new ArgumentOutOfRangeException ("size");
478 WebAsyncResult result = new WebAsyncResult (cb, state);
480 CheckWriteOverflow (request.ContentLength, totalWritten, size);
481 if (allowBuffering && !sendChunked) {
482 if (writeBuffer == null)
483 writeBuffer = new MemoryStream ();
484 writeBuffer.Write (buffer, offset, size);
485 totalWritten += size;
486 if (request.ContentLength > 0 && totalWritten == request.ContentLength) {
488 result.AsyncWriteAll = true;
489 result.InnerAsyncResult = WriteRequestAsync (new AsyncCallback (WriteRequestAsyncCB), result);
490 if (result.InnerAsyncResult == null) {
491 if (!result.IsCompleted)
492 result.SetCompleted (true, 0);
493 result.DoCallback ();
495 } catch (Exception exc) {
496 result.SetCompleted (true, exc);
497 result.DoCallback ();
500 result.SetCompleted (true, 0);
501 result.DoCallback ();
506 AsyncCallback callback = null;
508 callback = new AsyncCallback (WriteCallbackWrapper);
513 string cSize = String.Format ("{0:X}\r\n", size);
514 byte [] head = Encoding.ASCII.GetBytes (cSize);
515 int chunkSize = 2 + size + head.Length;
516 byte [] newBuffer = new byte [chunkSize];
517 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
518 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
519 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
526 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
527 totalWritten += size;
531 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
533 if (contentLength == -1)
536 long avail = contentLength - totalWritten;
539 nextReadCalled = true;
541 throw new ProtocolViolationException (
542 "The number of bytes to be written is greater than " +
543 "the specified ContentLength.");
547 public override void EndWrite (IAsyncResult r)
550 throw new ArgumentNullException ("r");
552 WebAsyncResult result = r as WebAsyncResult;
554 throw new ArgumentException ("Invalid IAsyncResult");
556 if (result.EndCalled)
559 result.EndCalled = true;
560 if (result.AsyncWriteAll) {
561 result.WaitUntilComplete ();
562 if (result.GotException)
563 throw result.Exception;
567 if (allowBuffering && !sendChunked)
570 if (result.GotException)
571 throw result.Exception;
574 cnc.EndWrite (request, result.InnerAsyncResult);
575 result.SetCompleted (false, 0);
576 } catch (Exception e) {
577 result.SetCompleted (false, e);
583 if (pendingWrites == 0)
590 public override void Write (byte [] buffer, int offset, int size)
592 AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
593 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
594 if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
596 nextReadCalled = true;
598 throw new IOException ("Write timed out.");
604 public override void Flush ()
608 internal void SetHeaders (byte [] buffer)
614 long cl = request.ContentLength;
615 string method = request.Method;
616 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
617 method == "TRACE" || method == "DELETE");
618 if (sendChunked || cl > -1 || no_writestream) {
622 WebConnection.InitRead (cnc);
624 if (!sendChunked && cl == 0)
629 internal bool RequestWritten {
630 get { return requestWritten; }
633 IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
635 requestWritten = true;
636 byte [] bytes = writeBuffer.GetBuffer ();
637 int length = (int) writeBuffer.Length;
638 // Headers already written to the stream
639 return (length > 0) ? cnc.BeginWrite (request, bytes, 0, length, cb, state) : null;
648 string err_msg = null;
649 if (!cnc.Write (request, headers, 0, headers.Length, ref err_msg))
650 throw new WebException ("Error writing request: " + err_msg, null, WebExceptionStatus.SendFailure, null);
653 internal void WriteRequest ()
658 requestWritten = true;
662 if (!allowBuffering || writeBuffer == null)
665 byte [] bytes = writeBuffer.GetBuffer ();
666 int length = (int) writeBuffer.Length;
667 if (request.ContentLength != -1 && request.ContentLength < length) {
668 nextReadCalled = true;
670 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
671 WebExceptionStatus.ServerProtocolViolation, null);
675 string method = request.Method;
676 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
677 method == "TRACE" || method == "DELETE");
679 request.InternalContentLength = length;
680 request.SendRequestHeaders ();
683 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
686 IAsyncResult result = null;
688 result = cnc.BeginWrite (request, bytes, 0, length, null, null);
692 WebConnection.InitRead (cnc);
696 complete_request_written = cnc.EndWrite (request, result);
698 complete_request_written = true;
701 internal void InternalClose ()
706 public override void Close ()
713 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
714 string err_msg = null;
715 cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
720 if (!nextReadCalled) {
722 // If we have not read all the contents
723 if (!nextReadCalled) {
724 nextReadCalled = true;
729 } else if (!allowBuffering) {
730 complete_request_written = true;
733 WebConnection.InitRead (cnc);
738 if (disposed || requestWritten)
741 long length = request.ContentLength;
743 if (!sendChunked && length != -1 && totalWritten != length) {
744 IOException io = new IOException ("Cannot close the stream until all bytes are written");
745 nextReadCalled = true;
747 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
754 internal void KillBuffer ()
759 public override long Seek (long a, SeekOrigin b)
761 throw new NotSupportedException ();
764 public override void SetLength (long a)
766 throw new NotSupportedException ();
769 public override bool CanSeek {
770 get { return false; }
773 public override bool CanRead {
774 get { return !disposed && isRead; }
777 public override bool CanWrite {
778 get { return !disposed && !isRead; }
781 public override long Length {
782 get { throw new NotSupportedException (); }
785 public override long Position {
786 get { throw new NotSupportedException (); }
787 set { throw new NotSupportedException (); }