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;
67 AsyncCallback cb_wrapper; // Calls to ReadCallbackWrapper or WriteCallbacWrapper
69 public WebConnectionStream (WebConnection cnc)
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;
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 != "") {
83 contentLength = Int32.Parse (clength);
84 if (contentLength == 0 && !IsNtlmAuth ()) {
88 contentLength = Int32.MaxValue;
91 contentLength = Int32.MaxValue;
95 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
97 read_timeout = request.ReadWriteTimeout;
98 write_timeout = read_timeout;
100 cb_wrapper = new AsyncCallback (WriteCallbackWrapper);
102 this.request = request;
103 allowBuffering = request.InternalAllowBuffering;
104 sendChunked = request.SendChunked;
106 pending = new ManualResetEvent (true);
107 else if (allowBuffering)
108 writeBuffer = new MemoryStream ();
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);
119 internal void CheckResponseInBuffer ()
121 if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
127 internal HttpWebRequest Request {
128 get { return request; }
131 internal WebConnection Connection {
135 public override bool CanTimeout {
150 throw new ArgumentOutOfRangeException ("value");
151 read_timeout = value;
160 return write_timeout;
165 throw new ArgumentOutOfRangeException ("value");
166 write_timeout = value;
170 internal bool CompleteRequestWritten {
171 get { return complete_request_written; }
174 internal bool SendChunked {
175 set { sendChunked = value; }
178 internal byte [] ReadBuffer {
179 set { readBuffer = value; }
182 internal int ReadBufferOffset {
183 set { readBufferOffset = value;}
186 internal int ReadBufferSize {
187 set { readBufferSize = value; }
190 internal byte[] WriteBuffer {
191 get { return writeBuffer.GetBuffer (); }
194 internal int WriteBufferLength {
195 get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
198 internal void ForceCompletion ()
200 if (!nextReadCalled) {
201 if (contentLength == Int32.MaxValue)
203 nextReadCalled = true;
208 internal void CheckComplete ()
210 bool nrc = nextReadCalled;
211 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
212 nextReadCalled = true;
217 internal void ReadAll ()
219 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
220 if (isRead && !nextReadCalled) {
221 nextReadCalled = true;
229 if (totalRead >= contentLength)
233 int diff = readBufferSize - readBufferOffset;
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)
246 buffer = new byte [8192];
249 while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
250 ms.Write (buffer, 0, read);
253 new_size = (int) ms.Length;
254 contentLength = new_size;
256 new_size = contentLength - totalRead;
257 b = new byte [new_size];
258 if (readBuffer != null && diff > 0) {
262 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
265 int remaining = new_size - diff;
267 while (remaining > 0 && r != 0) {
268 r = cnc.Read (request, b, diff, remaining);
275 readBufferOffset = 0;
276 readBufferSize = new_size;
278 nextReadCalled = true;
284 void WriteCallbackWrapper (IAsyncResult r)
286 WebAsyncResult result = r as WebAsyncResult;
287 if (result != null && result.AsyncWriteAll)
290 if (r.AsyncState != null) {
291 result = (WebAsyncResult) r.AsyncState;
292 result.InnerAsyncResult = r;
293 result.DoCallback ();
299 void ReadCallbackWrapper (IAsyncResult r)
301 WebAsyncResult result;
302 if (r.AsyncState != null) {
303 result = (WebAsyncResult) r.AsyncState;
304 result.InnerAsyncResult = r;
305 result.DoCallback ();
314 public override int Read (byte [] buffer, int offset, int size)
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;
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 (offset < 0 || length < offset)
338 throw new ArgumentOutOfRangeException ("offset");
339 if (size < 0 || (length - offset) < size)
340 throw new ArgumentOutOfRangeException ("size");
347 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
348 if (totalRead >= contentLength) {
349 result.SetCompleted (true, -1);
350 result.DoCallback ();
354 int remaining = readBufferSize - readBufferOffset;
356 int copy = (remaining > size) ? size : remaining;
357 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
358 readBufferOffset += copy;
362 if (size == 0 || totalRead >= contentLength) {
363 result.SetCompleted (true, copy);
364 result.DoCallback ();
367 result.NBytes = copy;
373 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
374 size = contentLength - totalRead;
377 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
379 result.SetCompleted (true, result.NBytes);
380 result.DoCallback ();
385 public override int EndRead (IAsyncResult r)
387 WebAsyncResult result = (WebAsyncResult) r;
388 if (result.EndCalled) {
389 int xx = result.NBytes;
390 return (xx >= 0) ? xx : 0;
393 result.EndCalled = true;
395 if (!result.IsCompleted) {
398 nbytes = cnc.EndRead (request, result);
399 } catch (Exception exc) {
402 if (pendingReads == 0)
406 nextReadCalled = true;
408 result.SetCompleted (false, exc);
409 result.DoCallback ();
419 result.SetCompleted (false, nbytes + result.NBytes);
420 result.DoCallback ();
422 contentLength = totalRead;
427 if (pendingReads == 0)
431 if (totalRead >= contentLength && !nextReadCalled)
434 int nb = result.NBytes;
435 return (nb >= 0) ? nb : 0;
438 void WriteRequestAsyncCB (IAsyncResult r)
440 WebAsyncResult result = (WebAsyncResult) r.AsyncState;
442 cnc.EndWrite2 (request, r);
443 result.SetCompleted (false, 0);
446 WebConnection.InitRead (cnc);
448 } catch (Exception e) {
450 nextReadCalled = true;
452 if (e is System.Net.Sockets.SocketException)
453 e = new IOException ("Error writing request", e);
454 result.SetCompleted (false, e);
456 complete_request_written = true;
457 result.DoCallback ();
460 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
461 AsyncCallback cb, object state)
464 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
467 throw new NotSupportedException ("this stream does not allow writing");
470 throw new ArgumentNullException ("buffer");
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");
485 WebAsyncResult result = new WebAsyncResult (cb, state);
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) {
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 ();
502 } catch (Exception exc) {
503 result.SetCompleted (true, exc);
504 result.DoCallback ();
507 result.SetCompleted (true, 0);
508 result.DoCallback ();
513 AsyncCallback callback = null;
515 callback = cb_wrapper;
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);
533 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
534 totalWritten += size;
538 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
540 if (contentLength == -1)
543 long avail = contentLength - totalWritten;
546 nextReadCalled = true;
548 throw new ProtocolViolationException (
549 "The number of bytes to be written is greater than " +
550 "the specified ContentLength.");
554 public override void EndWrite (IAsyncResult r)
557 throw new ArgumentNullException ("r");
559 WebAsyncResult result = r as WebAsyncResult;
561 throw new ArgumentException ("Invalid IAsyncResult");
563 if (result.EndCalled)
566 result.EndCalled = true;
567 if (result.AsyncWriteAll) {
568 result.WaitUntilComplete ();
569 if (result.GotException)
570 throw result.Exception;
574 if (allowBuffering && !sendChunked)
577 if (result.GotException)
578 throw result.Exception;
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 ();
592 if (pendingWrites == 0)
599 public override void Write (byte [] buffer, int offset, int size)
601 AsyncCallback cb = cb_wrapper;
602 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
603 if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
605 nextReadCalled = true;
607 throw new IOException ("Write timed out.");
613 public override void Flush ()
617 internal void SetHeaders (byte [] 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) {
631 WebConnection.InitRead (cnc);
633 if (!sendChunked && cl == 0)
634 requestWritten = true;
638 internal bool RequestWritten {
639 get { return requestWritten; }
642 IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
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;
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);
662 internal void WriteRequest ()
667 requestWritten = true;
671 if (!allowBuffering || writeBuffer == null)
674 byte [] bytes = writeBuffer.GetBuffer ();
675 int length = (int) writeBuffer.Length;
676 if (request.ContentLength != -1 && request.ContentLength < length) {
677 nextReadCalled = true;
679 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
680 WebExceptionStatus.ServerProtocolViolation, null);
684 string method = request.Method;
685 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
686 method == "TRACE" || method == "DELETE");
688 request.InternalContentLength = length;
689 request.SendRequestHeaders (true);
692 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
695 IAsyncResult result = null;
697 result = cnc.BeginWrite (request, bytes, 0, length, null, null);
701 WebConnection.InitRead (cnc);
705 complete_request_written = cnc.EndWrite (request, result);
707 complete_request_written = true;
710 internal void InternalClose ()
715 public override void Close ()
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);
729 if (!nextReadCalled) {
731 // If we have not read all the contents
732 if (!nextReadCalled) {
733 nextReadCalled = true;
738 } else if (!allowBuffering) {
739 complete_request_written = true;
742 WebConnection.InitRead (cnc);
747 if (disposed || requestWritten)
750 long length = request.ContentLength;
752 if (!sendChunked && length != -1 && totalWritten != length) {
753 IOException io = new IOException ("Cannot close the stream until all bytes are written");
754 nextReadCalled = true;
756 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
763 internal void KillBuffer ()
768 public override long Seek (long a, SeekOrigin b)
770 throw new NotSupportedException ();
773 public override void SetLength (long a)
775 throw new NotSupportedException ();
778 public override bool CanSeek {
779 get { return false; }
782 public override bool CanRead {
783 get { return !disposed && isRead; }
786 public override bool CanWrite {
787 get { return !disposed && !isRead; }
790 public override long Length {
791 get { throw new NotSupportedException (); }
794 public override long Position {
795 get { throw new NotSupportedException (); }
796 set { throw new NotSupportedException (); }