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;
66 public WebConnectionStream (WebConnection cnc)
69 pending = new ManualResetEvent (true);
70 this.request = cnc.Data.request;
72 string contentType = cnc.Data.Headers ["Transfer-Encoding"];
73 bool chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
74 string clength = cnc.Data.Headers ["Content-Length"];
75 if (!chunkedRead && clength != null && clength != "") {
78 contentLength = Int32.Parse (clength);
79 if (contentLength == 0 && !IsNtlmAuth ()) {
83 contentLength = Int32.MaxValue;
86 contentLength = Int32.MaxValue;
90 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
94 this.request = request;
95 allowBuffering = request.InternalAllowBuffering;
96 sendChunked = request.SendChunked;
98 writeBuffer = new MemoryStream ();
99 max_buffer_size = request.ContentLength;
101 max_buffer_size = -1;
105 pending = new ManualResetEvent (true);
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 WebConnection Connection {
128 public override bool CanTimeout {
133 internal bool CompleteRequestWritten {
134 get { return complete_request_written; }
137 internal bool SendChunked {
138 set { sendChunked = value; }
141 internal byte [] ReadBuffer {
142 set { readBuffer = value; }
145 internal int ReadBufferOffset {
146 set { readBufferOffset = value;}
149 internal int ReadBufferSize {
150 set { readBufferSize = value; }
153 internal byte[] WriteBuffer {
154 get { return writeBuffer.GetBuffer (); }
157 internal int WriteBufferLength {
158 get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
161 internal void ForceCompletion ()
163 if (!nextReadCalled) {
164 nextReadCalled = true;
169 internal void CheckComplete ()
171 bool nrc = nextReadCalled;
172 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
173 nextReadCalled = true;
178 internal void ReadAll ()
180 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
181 if (isRead && !nextReadCalled) {
182 nextReadCalled = true;
190 if (totalRead >= contentLength)
194 int diff = readBufferSize - readBufferOffset;
197 if (contentLength == Int32.MaxValue) {
198 MemoryStream ms = new MemoryStream ();
199 byte [] buffer = null;
200 if (readBuffer != null && diff > 0) {
201 ms.Write (readBuffer, readBufferOffset, diff);
202 if (readBufferSize >= 8192)
207 buffer = new byte [8192];
210 while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
211 ms.Write (buffer, 0, read);
214 new_size = (int) ms.Length;
215 contentLength = new_size;
217 new_size = contentLength - totalRead;
218 b = new byte [new_size];
219 if (readBuffer != null && diff > 0) {
223 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
226 int remaining = new_size - diff;
228 while (remaining > 0 && r != 0) {
229 r = cnc.Read (b, diff, remaining);
236 readBufferOffset = 0;
237 readBufferSize = new_size;
239 nextReadCalled = true;
245 void WriteCallbackWrapper (IAsyncResult r)
247 WebAsyncResult result;
248 if (r.AsyncState != null) {
249 result = (WebAsyncResult) r.AsyncState;
250 result.InnerAsyncResult = r;
251 result.DoCallback ();
257 void ReadCallbackWrapper (IAsyncResult r)
259 WebAsyncResult result;
260 if (r.AsyncState != null) {
261 result = (WebAsyncResult) r.AsyncState;
262 result.InnerAsyncResult = r;
263 result.DoCallback ();
269 public override int Read (byte [] buffer, int offset, int size)
272 throw new NotSupportedException ("this stream does not allow reading");
274 if (totalRead >= contentLength)
277 AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
278 WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
279 if (!res.IsCompleted && !res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
280 nextReadCalled = true;
282 throw new WebException ("The operation has timed out.",
283 WebExceptionStatus.Timeout);
286 return EndRead (res);
289 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
290 AsyncCallback cb, object state)
293 throw new NotSupportedException ("this stream does not allow reading");
296 throw new ArgumentNullException ("buffer");
298 int length = buffer.Length;
299 if (size < 0 || offset < 0 || length < offset || length - offset < size)
300 throw new ArgumentOutOfRangeException ();
307 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
308 if (totalRead >= contentLength) {
309 result.SetCompleted (true, -1);
310 result.DoCallback ();
314 int remaining = readBufferSize - readBufferOffset;
316 int copy = (remaining > size) ? size : remaining;
317 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
318 readBufferOffset += copy;
322 if (size == 0 || totalRead >= contentLength) {
323 result.SetCompleted (true, copy);
324 result.DoCallback ();
327 result.NBytes = copy;
331 cb = new AsyncCallback (ReadCallbackWrapper);
333 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
334 size = contentLength - totalRead;
337 result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
339 result.SetCompleted (true, result.NBytes);
340 result.DoCallback ();
345 public override int EndRead (IAsyncResult r)
347 WebAsyncResult result = (WebAsyncResult) r;
348 if (result.EndCalled) {
349 int xx = result.NBytes;
350 return (xx >= 0) ? xx : 0;
353 result.EndCalled = true;
355 if (!result.IsCompleted) {
358 nbytes = cnc.EndRead (result);
359 } catch (Exception exc) {
362 if (pendingReads == 0)
366 nextReadCalled = true;
368 result.SetCompleted (false, exc);
378 result.SetCompleted (false, nbytes + result.NBytes);
379 result.DoCallback ();
381 contentLength = totalRead;
386 if (pendingReads == 0)
390 if (totalRead >= contentLength && !nextReadCalled)
393 int nb = result.NBytes;
394 return (nb >= 0) ? nb : 0;
397 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
398 AsyncCallback cb, object state)
401 throw new NotSupportedException ("this stream does not allow writing");
404 throw new ArgumentNullException ("buffer");
406 int length = buffer.Length;
407 if (size < 0 || offset < 0 || length < offset || length - offset < size)
408 throw new ArgumentOutOfRangeException ();
417 WebAsyncResult result = new WebAsyncResult (cb, state);
418 if (allowBuffering) {
419 if (max_buffer_size >= 0) {
420 long avail = max_buffer_size - writeBuffer.Length;
423 throw new ProtocolViolationException (
424 "The number of bytes to be written is greater than " +
425 "the specified ContentLength.");
428 writeBuffer.Write (buffer, offset, size);
430 result.SetCompleted (true, 0);
431 result.DoCallback ();
436 AsyncCallback callback = null;
438 callback = new AsyncCallback (WriteCallbackWrapper);
443 string cSize = String.Format ("{0:X}\r\n", size);
444 byte [] head = Encoding.ASCII.GetBytes (cSize);
445 int chunkSize = 2 + size + head.Length;
446 byte [] newBuffer = new byte [chunkSize];
447 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
448 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
449 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
456 result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
460 public override void EndWrite (IAsyncResult r)
463 throw new ArgumentNullException ("r");
465 WebAsyncResult result = r as WebAsyncResult;
467 throw new ArgumentException ("Invalid IAsyncResult");
469 if (result.EndCalled)
472 result.EndCalled = true;
474 if (allowBuffering && !sendChunked)
477 if (result.GotException)
478 throw result.Exception;
481 cnc.EndWrite (result.InnerAsyncResult);
482 result.SetCompleted (false, 0);
483 } catch (Exception e) {
484 result.SetCompleted (false, e);
490 if (pendingWrites == 0)
496 public override void Write (byte [] buffer, int offset, int size)
499 throw new NotSupportedException ("This stream does not allow writing");
501 AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
502 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
503 if (!res.IsCompleted && !res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
504 nextReadCalled = true;
506 throw new IOException ("Write timed out.");
512 public override void Flush ()
516 internal void SetHeaders (byte [] buffer, int offset, int size)
521 if (!allowBuffering || sendChunked) {
524 throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
527 if (!cnc.Write (buffer, offset, size))
528 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
532 WebConnection.InitRead (cnc);
535 headers = new byte [size];
536 Buffer.BlockCopy (buffer, offset, headers, 0, size);
540 internal bool RequestWritten {
541 get { return requestWritten; }
544 internal void WriteRequest ()
550 request.SendRequestHeaders ();
551 requestWritten = true;
555 if (!allowBuffering || writeBuffer == null)
558 byte [] bytes = writeBuffer.GetBuffer ();
559 int length = (int) writeBuffer.Length;
560 if (request.ContentLength != -1 && request.ContentLength < length) {
561 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
562 WebExceptionStatus.ServerProtocolViolation, null);
565 request.InternalContentLength = length;
566 request.SendRequestHeaders ();
567 requestWritten = true;
570 // For small requests, make a copy, it will reduce the traffic, for large
571 // requests, the NoDelay bit on the socket should take effect (set in WebConnection).
573 if (headers.Length + length < 8192){
574 byte[] b = new byte [headers.Length + length];
576 Buffer.BlockCopy (headers, 0, b, 0, headers.Length);
577 Buffer.BlockCopy (bytes, 0, b, headers.Length, length);
579 if (!cnc.Write (b, 0, b.Length))
580 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
583 complete_request_written = true;
587 WebConnection.InitRead (cnc);
590 if (!cnc.Write (headers, 0, headers.Length))
591 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
594 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
597 IAsyncResult result = null;
599 result = cnc.BeginWrite (bytes, 0, length, null, null);
603 WebConnection.InitRead (cnc);
607 complete_request_written = cnc.EndWrite (result);
609 complete_request_written = true;
613 internal void InternalClose ()
618 internal void ForceCloseConnection ()
626 public override void Close ()
630 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
631 cnc.Write (chunk, 0, chunk.Length);
636 if (!nextReadCalled) {
638 // If we have not read all the contents
639 if (!nextReadCalled) {
640 nextReadCalled = true;
645 } else if (!allowBuffering) {
646 complete_request_written = true;
649 WebConnection.InitRead (cnc);
657 long length = request.ContentLength;
658 if (length != -1 && length > writeBuffer.Length)
659 throw new IOException ("Cannot close the stream until all bytes are written");
665 internal void KillBuffer ()
670 public override long Seek (long a, SeekOrigin b)
672 throw new NotSupportedException ();
675 public override void SetLength (long a)
677 throw new NotSupportedException ();
680 public override bool CanSeek {
681 get { return false; }
684 public override bool CanRead {
685 get { return isRead; }
688 public override bool CanWrite {
689 get { return !isRead; }
692 public override long Length {
693 get { throw new NotSupportedException (); }
696 public override long Position {
697 get { throw new NotSupportedException (); }
698 set { throw new NotSupportedException (); }