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;
52 ManualResetEvent pending;
55 MemoryStream writeBuffer;
60 object locker = new object ();
63 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 != "") {
82 contentLength = Int32.Parse (clength);
83 if (contentLength == 0 && !IsNtlmAuth ()) {
87 contentLength = Int32.MaxValue;
90 contentLength = Int32.MaxValue;
94 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
96 read_timeout = request.ReadWriteTimeout;
97 write_timeout = read_timeout;
100 this.request = request;
101 allowBuffering = request.InternalAllowBuffering;
102 sendChunked = request.SendChunked;
103 if (allowBuffering) {
104 writeBuffer = new MemoryStream ();
105 max_buffer_size = request.ContentLength;
107 max_buffer_size = -1;
111 pending = new ManualResetEvent (true);
116 bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
117 string header_name = (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate";
118 string authHeader = cnc.Data.Headers [header_name];
119 return (authHeader != null && authHeader.IndexOf ("NTLM") != -1);
122 internal void CheckResponseInBuffer ()
124 if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
130 internal WebConnection Connection {
134 public override bool CanTimeout {
149 throw new ArgumentOutOfRangeException ("value");
150 read_timeout = value;
159 return write_timeout;
164 throw new ArgumentOutOfRangeException ("value");
165 write_timeout = value;
169 internal bool CompleteRequestWritten {
170 get { return complete_request_written; }
173 internal bool SendChunked {
174 set { sendChunked = value; }
177 internal byte [] ReadBuffer {
178 set { readBuffer = value; }
181 internal int ReadBufferOffset {
182 set { readBufferOffset = value;}
185 internal int ReadBufferSize {
186 set { readBufferSize = value; }
189 internal byte[] WriteBuffer {
190 get { return writeBuffer.GetBuffer (); }
193 internal int WriteBufferLength {
194 get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
197 internal void ForceCompletion ()
199 if (!nextReadCalled) {
200 if (contentLength == Int32.MaxValue)
202 nextReadCalled = true;
207 internal void CheckComplete ()
209 bool nrc = nextReadCalled;
210 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
211 nextReadCalled = true;
216 internal void ReadAll ()
218 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
219 if (isRead && !nextReadCalled) {
220 nextReadCalled = true;
228 if (totalRead >= contentLength)
232 int diff = readBufferSize - readBufferOffset;
235 if (contentLength == Int32.MaxValue) {
236 MemoryStream ms = new MemoryStream ();
237 byte [] buffer = null;
238 if (readBuffer != null && diff > 0) {
239 ms.Write (readBuffer, readBufferOffset, diff);
240 if (readBufferSize >= 8192)
245 buffer = new byte [8192];
248 while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
249 ms.Write (buffer, 0, read);
252 new_size = (int) ms.Length;
253 contentLength = new_size;
255 new_size = contentLength - totalRead;
256 b = new byte [new_size];
257 if (readBuffer != null && diff > 0) {
261 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
264 int remaining = new_size - diff;
266 while (remaining > 0 && r != 0) {
267 r = cnc.Read (b, diff, remaining);
274 readBufferOffset = 0;
275 readBufferSize = new_size;
277 nextReadCalled = true;
283 void WriteCallbackWrapper (IAsyncResult r)
285 WebAsyncResult result;
286 if (r.AsyncState != null) {
287 result = (WebAsyncResult) r.AsyncState;
288 result.InnerAsyncResult = r;
289 result.DoCallback ();
295 void ReadCallbackWrapper (IAsyncResult r)
297 WebAsyncResult result;
298 if (r.AsyncState != null) {
299 result = (WebAsyncResult) r.AsyncState;
300 result.InnerAsyncResult = r;
301 result.DoCallback ();
307 public override int Read (byte [] buffer, int offset, int size)
310 throw new NotSupportedException ("this stream does not allow reading");
312 if (totalRead >= contentLength)
315 AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
316 WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
317 if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
318 nextReadCalled = true;
320 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
323 return EndRead (res);
326 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
327 AsyncCallback cb, object state)
330 throw new NotSupportedException ("this stream does not allow reading");
333 throw new ArgumentNullException ("buffer");
335 int length = buffer.Length;
336 if (size < 0 || offset < 0 || length < offset || length - offset < size)
337 throw new ArgumentOutOfRangeException ();
344 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
345 if (totalRead >= contentLength) {
346 result.SetCompleted (true, -1);
347 result.DoCallback ();
351 int remaining = readBufferSize - readBufferOffset;
353 int copy = (remaining > size) ? size : remaining;
354 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
355 readBufferOffset += copy;
359 if (size == 0 || totalRead >= contentLength) {
360 result.SetCompleted (true, copy);
361 result.DoCallback ();
364 result.NBytes = copy;
368 cb = new AsyncCallback (ReadCallbackWrapper);
370 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
371 size = contentLength - totalRead;
374 result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
376 result.SetCompleted (true, result.NBytes);
377 result.DoCallback ();
382 public override int EndRead (IAsyncResult r)
384 WebAsyncResult result = (WebAsyncResult) r;
385 if (result.EndCalled) {
386 int xx = result.NBytes;
387 return (xx >= 0) ? xx : 0;
390 result.EndCalled = true;
392 if (!result.IsCompleted) {
395 nbytes = cnc.EndRead (result);
396 } catch (Exception exc) {
399 if (pendingReads == 0)
403 nextReadCalled = true;
405 result.SetCompleted (false, exc);
415 result.SetCompleted (false, nbytes + result.NBytes);
416 result.DoCallback ();
418 contentLength = totalRead;
423 if (pendingReads == 0)
427 if (totalRead >= contentLength && !nextReadCalled)
430 int nb = result.NBytes;
431 return (nb >= 0) ? nb : 0;
434 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
435 AsyncCallback cb, object state)
438 throw new NotSupportedException ("this stream does not allow writing");
441 throw new ArgumentNullException ("buffer");
443 int length = buffer.Length;
444 if (size < 0 || offset < 0 || length < offset || length - offset < size)
445 throw new ArgumentOutOfRangeException ();
454 WebAsyncResult result = new WebAsyncResult (cb, state);
455 if (allowBuffering) {
456 if (max_buffer_size >= 0) {
457 long avail = max_buffer_size - writeBuffer.Length;
460 throw new ProtocolViolationException (
461 "The number of bytes to be written is greater than " +
462 "the specified ContentLength.");
465 writeBuffer.Write (buffer, offset, size);
467 result.SetCompleted (true, 0);
468 result.DoCallback ();
473 AsyncCallback callback = null;
475 callback = new AsyncCallback (WriteCallbackWrapper);
480 string cSize = String.Format ("{0:X}\r\n", size);
481 byte [] head = Encoding.ASCII.GetBytes (cSize);
482 int chunkSize = 2 + size + head.Length;
483 byte [] newBuffer = new byte [chunkSize];
484 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
485 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
486 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
493 result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
497 public override void EndWrite (IAsyncResult r)
500 throw new ArgumentNullException ("r");
502 WebAsyncResult result = r as WebAsyncResult;
504 throw new ArgumentException ("Invalid IAsyncResult");
506 if (result.EndCalled)
509 result.EndCalled = true;
511 if (allowBuffering && !sendChunked)
514 if (result.GotException)
515 throw result.Exception;
518 cnc.EndWrite (result.InnerAsyncResult);
519 result.SetCompleted (false, 0);
520 } catch (Exception e) {
521 result.SetCompleted (false, e);
527 if (pendingWrites == 0)
533 public override void Write (byte [] buffer, int offset, int size)
536 throw new NotSupportedException ("This stream does not allow writing");
538 AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
539 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
540 if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
541 nextReadCalled = true;
543 throw new IOException ("Write timed out.");
549 public override void Flush ()
553 internal void SetHeaders (byte [] buffer, int offset, int size)
558 if (!allowBuffering || sendChunked) {
561 throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
564 if (!cnc.Write (buffer, offset, size))
565 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
569 WebConnection.InitRead (cnc);
572 headers = new byte [size];
573 Buffer.BlockCopy (buffer, offset, headers, 0, size);
577 internal bool RequestWritten {
578 get { return requestWritten; }
581 internal void WriteRequest ()
587 request.SendRequestHeaders ();
588 requestWritten = true;
592 if (!allowBuffering || writeBuffer == null)
595 byte [] bytes = writeBuffer.GetBuffer ();
596 int length = (int) writeBuffer.Length;
597 if (request.ContentLength != -1 && request.ContentLength < length) {
598 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
599 WebExceptionStatus.ServerProtocolViolation, null);
602 request.InternalContentLength = length;
603 request.SendRequestHeaders ();
604 requestWritten = true;
607 // For small requests, make a copy, it will reduce the traffic, for large
608 // requests, the NoDelay bit on the socket should take effect (set in WebConnection).
610 if (headers.Length + length < 8192){
611 byte[] b = new byte [headers.Length + length];
613 Buffer.BlockCopy (headers, 0, b, 0, headers.Length);
614 Buffer.BlockCopy (bytes, 0, b, headers.Length, length);
616 if (!cnc.Write (b, 0, b.Length))
617 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
620 complete_request_written = true;
624 WebConnection.InitRead (cnc);
627 if (!cnc.Write (headers, 0, headers.Length))
628 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
631 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
634 IAsyncResult result = null;
636 result = cnc.BeginWrite (bytes, 0, length, null, null);
640 WebConnection.InitRead (cnc);
644 complete_request_written = cnc.EndWrite (result);
646 complete_request_written = true;
650 internal void InternalClose ()
655 internal void ForceCloseConnection ()
663 public override void Close ()
667 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
668 cnc.Write (chunk, 0, chunk.Length);
673 if (!nextReadCalled) {
675 // If we have not read all the contents
676 if (!nextReadCalled) {
677 nextReadCalled = true;
682 } else if (!allowBuffering) {
683 complete_request_written = true;
686 WebConnection.InitRead (cnc);
694 long length = request.ContentLength;
696 // writeBuffer could be null if KillBuffer was already called.
697 if (writeBuffer != null && length != -1 && length > writeBuffer.Length)
698 throw new WebException ("Cannot close the stream until all bytes are written", WebExceptionStatus.RequestCanceled);
704 internal void KillBuffer ()
709 public override long Seek (long a, SeekOrigin b)
711 throw new NotSupportedException ();
714 public override void SetLength (long a)
716 throw new NotSupportedException ();
719 public override bool CanSeek {
720 get { return false; }
723 public override bool CanRead {
724 get { return isRead; }
727 public override bool CanWrite {
728 get { return !isRead; }
731 public override long Length {
732 get { throw new NotSupportedException (); }
735 public override long Position {
736 get { throw new NotSupportedException (); }
737 set { throw new NotSupportedException (); }