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 != "") {
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;
104 writeBuffer = new MemoryStream ();
106 pending = new ManualResetEvent (true);
111 bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
112 string header_name = (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate";
113 string authHeader = cnc.Data.Headers [header_name];
114 return (authHeader != null && authHeader.IndexOf ("NTLM") != -1);
117 internal void CheckResponseInBuffer ()
119 if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
125 internal WebConnection Connection {
129 public override bool CanTimeout {
144 throw new ArgumentOutOfRangeException ("value");
145 read_timeout = value;
154 return write_timeout;
159 throw new ArgumentOutOfRangeException ("value");
160 write_timeout = value;
164 internal bool CompleteRequestWritten {
165 get { return complete_request_written; }
168 internal bool SendChunked {
169 set { sendChunked = value; }
172 internal byte [] ReadBuffer {
173 set { readBuffer = value; }
176 internal int ReadBufferOffset {
177 set { readBufferOffset = value;}
180 internal int ReadBufferSize {
181 set { readBufferSize = value; }
184 internal byte[] WriteBuffer {
185 get { return writeBuffer.GetBuffer (); }
188 internal int WriteBufferLength {
189 get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
192 internal void ForceCompletion ()
194 if (!nextReadCalled) {
195 if (contentLength == Int32.MaxValue)
197 nextReadCalled = true;
202 internal void CheckComplete ()
204 bool nrc = nextReadCalled;
205 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
206 nextReadCalled = true;
211 internal void ReadAll ()
213 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
214 if (isRead && !nextReadCalled) {
215 nextReadCalled = true;
223 if (totalRead >= contentLength)
227 int diff = readBufferSize - readBufferOffset;
230 if (contentLength == Int32.MaxValue) {
231 MemoryStream ms = new MemoryStream ();
232 byte [] buffer = null;
233 if (readBuffer != null && diff > 0) {
234 ms.Write (readBuffer, readBufferOffset, diff);
235 if (readBufferSize >= 8192)
240 buffer = new byte [8192];
243 while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
244 ms.Write (buffer, 0, read);
247 new_size = (int) ms.Length;
248 contentLength = new_size;
250 new_size = contentLength - totalRead;
251 b = new byte [new_size];
252 if (readBuffer != null && diff > 0) {
256 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
259 int remaining = new_size - diff;
261 while (remaining > 0 && r != 0) {
262 r = cnc.Read (b, diff, remaining);
269 readBufferOffset = 0;
270 readBufferSize = new_size;
272 nextReadCalled = true;
278 void WriteCallbackWrapper (IAsyncResult r)
280 WebAsyncResult result;
281 if (r.AsyncState != null) {
282 result = (WebAsyncResult) r.AsyncState;
283 result.InnerAsyncResult = r;
284 result.DoCallback ();
290 void ReadCallbackWrapper (IAsyncResult r)
292 WebAsyncResult result;
293 if (r.AsyncState != null) {
294 result = (WebAsyncResult) r.AsyncState;
295 result.InnerAsyncResult = r;
296 result.DoCallback ();
302 public override int Read (byte [] buffer, int offset, int size)
305 throw new NotSupportedException ("this stream does not allow reading");
307 if (totalRead >= contentLength)
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 (size < 0 || offset < 0 || length < offset || length - offset < size)
332 throw new ArgumentOutOfRangeException ();
339 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
340 if (totalRead >= contentLength) {
341 result.SetCompleted (true, -1);
342 result.DoCallback ();
346 int remaining = readBufferSize - readBufferOffset;
348 int copy = (remaining > size) ? size : remaining;
349 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
350 readBufferOffset += copy;
354 if (size == 0 || totalRead >= contentLength) {
355 result.SetCompleted (true, copy);
356 result.DoCallback ();
359 result.NBytes = copy;
363 cb = new AsyncCallback (ReadCallbackWrapper);
365 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
366 size = contentLength - totalRead;
369 result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
371 result.SetCompleted (true, result.NBytes);
372 result.DoCallback ();
377 public override int EndRead (IAsyncResult r)
379 WebAsyncResult result = (WebAsyncResult) r;
380 if (result.EndCalled) {
381 int xx = result.NBytes;
382 return (xx >= 0) ? xx : 0;
385 result.EndCalled = true;
387 if (!result.IsCompleted) {
390 nbytes = cnc.EndRead (result);
391 } catch (Exception exc) {
394 if (pendingReads == 0)
398 nextReadCalled = true;
400 result.SetCompleted (false, exc);
410 result.SetCompleted (false, nbytes + result.NBytes);
411 result.DoCallback ();
413 contentLength = totalRead;
418 if (pendingReads == 0)
422 if (totalRead >= contentLength && !nextReadCalled)
425 int nb = result.NBytes;
426 return (nb >= 0) ? nb : 0;
429 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
430 AsyncCallback cb, object state)
433 throw new NotSupportedException ("this stream does not allow writing");
436 throw new ArgumentNullException ("buffer");
438 int length = buffer.Length;
439 if (size < 0 || offset < 0 || length < offset || length - offset < size)
440 throw new ArgumentOutOfRangeException ();
449 WebAsyncResult result = new WebAsyncResult (cb, state);
451 CheckWriteOverflow (request.ContentLength, totalWritten, size);
452 if (allowBuffering) {
453 writeBuffer.Write (buffer, offset, size);
454 totalWritten += size;
456 result.SetCompleted (true, 0);
457 result.DoCallback ();
462 AsyncCallback callback = null;
464 callback = new AsyncCallback (WriteCallbackWrapper);
469 string cSize = String.Format ("{0:X}\r\n", size);
470 byte [] head = Encoding.ASCII.GetBytes (cSize);
471 int chunkSize = 2 + size + head.Length;
472 byte [] newBuffer = new byte [chunkSize];
473 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
474 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
475 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
482 result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
483 totalWritten += size;
487 static void CheckWriteOverflow (long contentLength, long totalWritten, long size)
489 if (contentLength == -1)
492 long avail = contentLength - totalWritten;
494 throw new ProtocolViolationException (
495 "The number of bytes to be written is greater than " +
496 "the specified ContentLength.");
499 public override void EndWrite (IAsyncResult r)
502 throw new ArgumentNullException ("r");
504 WebAsyncResult result = r as WebAsyncResult;
506 throw new ArgumentException ("Invalid IAsyncResult");
508 if (result.EndCalled)
511 result.EndCalled = true;
513 if (allowBuffering && !sendChunked)
516 if (result.GotException)
517 throw result.Exception;
520 cnc.EndWrite (result.InnerAsyncResult);
521 result.SetCompleted (false, 0);
522 } catch (Exception e) {
523 result.SetCompleted (false, e);
529 if (pendingWrites == 0)
535 public override void Write (byte [] buffer, int offset, int size)
538 throw new NotSupportedException ("This stream does not allow writing");
540 AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
541 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
542 if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
543 nextReadCalled = true;
545 throw new IOException ("Write timed out.");
551 public override void Flush ()
555 internal void SetHeaders (byte [] buffer, int offset, int size)
560 if (!allowBuffering || sendChunked) {
563 throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
566 if (!cnc.Write (buffer, offset, size))
567 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
571 WebConnection.InitRead (cnc);
574 headers = new byte [size];
575 Buffer.BlockCopy (buffer, offset, headers, 0, size);
579 internal bool RequestWritten {
580 get { return requestWritten; }
583 internal void WriteRequest ()
589 request.SendRequestHeaders ();
590 requestWritten = true;
594 if (!allowBuffering || writeBuffer == null)
597 byte [] bytes = writeBuffer.GetBuffer ();
598 int length = (int) writeBuffer.Length;
599 if (request.ContentLength != -1 && request.ContentLength < length) {
600 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
601 WebExceptionStatus.ServerProtocolViolation, null);
604 request.InternalContentLength = length;
605 request.SendRequestHeaders ();
606 requestWritten = true;
609 // For small requests, make a copy, it will reduce the traffic, for large
610 // requests, the NoDelay bit on the socket should take effect (set in WebConnection).
612 if (headers.Length + length < 8192){
613 byte[] b = new byte [headers.Length + length];
615 Buffer.BlockCopy (headers, 0, b, 0, headers.Length);
616 Buffer.BlockCopy (bytes, 0, b, headers.Length, length);
618 if (!cnc.Write (b, 0, b.Length))
619 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
622 complete_request_written = true;
626 WebConnection.InitRead (cnc);
629 if (!cnc.Write (headers, 0, headers.Length))
630 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
633 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
636 IAsyncResult result = null;
638 result = cnc.BeginWrite (bytes, 0, length, null, null);
642 WebConnection.InitRead (cnc);
646 complete_request_written = cnc.EndWrite (result);
648 complete_request_written = true;
652 internal void InternalClose ()
657 internal void ForceCloseConnection ()
665 public override void Close ()
669 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
670 cnc.Write (chunk, 0, chunk.Length);
675 if (!nextReadCalled) {
677 // If we have not read all the contents
678 if (!nextReadCalled) {
679 nextReadCalled = true;
684 } else if (!allowBuffering) {
685 complete_request_written = true;
688 WebConnection.InitRead (cnc);
696 long length = request.ContentLength;
698 // writeBuffer could be null if KillBuffer was already called.
699 if (writeBuffer != null && length != -1 && length > writeBuffer.Length) {
700 IOException io = new IOException ("Cannot close the stream until all bytes are written");
701 nextReadCalled = true;
703 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
710 internal void KillBuffer ()
715 public override long Seek (long a, SeekOrigin b)
717 throw new NotSupportedException ();
720 public override void SetLength (long a)
722 throw new NotSupportedException ();
725 public override bool CanSeek {
726 get { return false; }
729 public override bool CanRead {
730 get { return isRead; }
733 public override bool CanWrite {
734 get { return !isRead; }
737 public override long Length {
738 get { throw new NotSupportedException (); }
741 public override long Position {
742 get { throw new NotSupportedException (); }
743 set { throw new NotSupportedException (); }