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;
47 int stream_length; // -1 when CL not present
50 internal long totalWritten;
54 ManualResetEvent pending;
57 MemoryStream writeBuffer;
62 object locker = new object ();
65 bool complete_request_written;
68 AsyncCallback cb_wrapper; // Calls to ReadCallbackWrapper or WriteCallbacWrapper
69 internal bool IgnoreIOErrors;
71 public WebConnectionStream (WebConnection cnc)
74 cb_wrapper = new AsyncCallback (ReadCallbackWrapper);
75 pending = new ManualResetEvent (true);
76 this.request = cnc.Data.request;
77 read_timeout = request.ReadWriteTimeout;
78 write_timeout = read_timeout;
80 string contentType = cnc.Data.Headers ["Transfer-Encoding"];
81 bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
82 string clength = cnc.Data.Headers ["Content-Length"];
83 if (!chunkedRead && clength != null && clength != "") {
85 contentLength = Int32.Parse (clength);
86 if (contentLength == 0 && !IsNtlmAuth ()) {
90 contentLength = Int32.MaxValue;
93 contentLength = Int32.MaxValue;
97 if (!Int32.TryParse (clength, out stream_length))
101 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
103 read_timeout = request.ReadWriteTimeout;
104 write_timeout = read_timeout;
106 cb_wrapper = new AsyncCallback (WriteCallbackWrapper);
108 this.request = request;
109 allowBuffering = request.InternalAllowBuffering;
110 sendChunked = request.SendChunked;
112 pending = new ManualResetEvent (true);
113 else if (allowBuffering)
114 writeBuffer = new MemoryStream ();
119 bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
120 string header_name = (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate";
121 string authHeader = cnc.Data.Headers [header_name];
122 return (authHeader != null && authHeader.IndexOf ("NTLM", StringComparison.Ordinal) != -1);
125 internal void CheckResponseInBuffer ()
127 if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
133 internal HttpWebRequest Request {
134 get { return request; }
137 internal WebConnection Connection {
141 public override bool CanTimeout {
156 throw new ArgumentOutOfRangeException ("value");
157 read_timeout = value;
166 return write_timeout;
171 throw new ArgumentOutOfRangeException ("value");
172 write_timeout = value;
176 internal bool CompleteRequestWritten {
177 get { return complete_request_written; }
180 internal bool SendChunked {
181 set { sendChunked = value; }
184 internal byte [] ReadBuffer {
185 set { readBuffer = value; }
188 internal int ReadBufferOffset {
189 set { readBufferOffset = value;}
192 internal int ReadBufferSize {
193 set { readBufferSize = value; }
196 internal byte[] WriteBuffer {
197 get { return writeBuffer.GetBuffer (); }
200 internal int WriteBufferLength {
201 get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
204 internal void ForceCompletion ()
206 if (!nextReadCalled) {
207 if (contentLength == Int32.MaxValue)
209 nextReadCalled = true;
214 internal void CheckComplete ()
216 bool nrc = nextReadCalled;
217 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
218 nextReadCalled = true;
223 internal void ReadAll ()
225 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
226 if (isRead && !nextReadCalled) {
227 nextReadCalled = true;
235 if (totalRead >= contentLength)
239 int diff = readBufferSize - readBufferOffset;
242 if (contentLength == Int32.MaxValue) {
243 MemoryStream ms = new MemoryStream ();
244 byte [] buffer = null;
245 if (readBuffer != null && diff > 0) {
246 ms.Write (readBuffer, readBufferOffset, diff);
247 if (readBufferSize >= 8192)
252 buffer = new byte [8192];
255 while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
256 ms.Write (buffer, 0, read);
259 new_size = (int) ms.Length;
260 contentLength = new_size;
262 new_size = contentLength - totalRead;
263 b = new byte [new_size];
264 if (readBuffer != null && diff > 0) {
268 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
271 int remaining = new_size - diff;
273 while (remaining > 0 && r != 0) {
274 r = cnc.Read (request, b, diff, remaining);
281 readBufferOffset = 0;
282 readBufferSize = new_size;
284 nextReadCalled = true;
290 void WriteCallbackWrapper (IAsyncResult r)
292 WebAsyncResult result = r as WebAsyncResult;
293 if (result != null && result.AsyncWriteAll)
296 if (r.AsyncState != null) {
297 result = (WebAsyncResult) r.AsyncState;
298 result.InnerAsyncResult = r;
299 result.DoCallback ();
308 void ReadCallbackWrapper (IAsyncResult r)
310 WebAsyncResult result;
311 if (r.AsyncState != null) {
312 result = (WebAsyncResult) r.AsyncState;
313 result.InnerAsyncResult = r;
314 result.DoCallback ();
323 public override int Read (byte [] buffer, int offset, int size)
325 AsyncCallback cb = cb_wrapper;
326 WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
327 if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
328 nextReadCalled = true;
330 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
333 return EndRead (res);
336 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
337 AsyncCallback cb, object state)
340 throw new NotSupportedException ("this stream does not allow reading");
343 throw new ArgumentNullException ("buffer");
345 int length = buffer.Length;
346 if (offset < 0 || length < offset)
347 throw new ArgumentOutOfRangeException ("offset");
348 if (size < 0 || (length - offset) < size)
349 throw new ArgumentOutOfRangeException ("size");
356 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
357 if (totalRead >= contentLength) {
358 result.SetCompleted (true, -1);
359 result.DoCallback ();
363 int remaining = readBufferSize - readBufferOffset;
365 int copy = (remaining > size) ? size : remaining;
366 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
367 readBufferOffset += copy;
371 if (size == 0 || totalRead >= contentLength) {
372 result.SetCompleted (true, copy);
373 result.DoCallback ();
376 result.NBytes = copy;
382 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
383 size = contentLength - totalRead;
386 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
388 result.SetCompleted (true, result.NBytes);
389 result.DoCallback ();
394 public override int EndRead (IAsyncResult r)
396 WebAsyncResult result = (WebAsyncResult) r;
397 if (result.EndCalled) {
398 int xx = result.NBytes;
399 return (xx >= 0) ? xx : 0;
402 result.EndCalled = true;
404 if (!result.IsCompleted) {
407 nbytes = cnc.EndRead (request, result);
408 } catch (Exception exc) {
411 if (pendingReads == 0)
415 nextReadCalled = true;
417 result.SetCompleted (false, exc);
418 result.DoCallback ();
428 result.SetCompleted (false, nbytes + result.NBytes);
429 result.DoCallback ();
431 contentLength = totalRead;
436 if (pendingReads == 0)
440 if (totalRead >= contentLength && !nextReadCalled)
443 int nb = result.NBytes;
444 return (nb >= 0) ? nb : 0;
447 void WriteRequestAsyncCB (IAsyncResult r)
449 WebAsyncResult result = (WebAsyncResult) r.AsyncState;
451 cnc.EndWrite2 (request, r);
452 result.SetCompleted (false, 0);
455 WebConnection.InitRead (cnc);
457 } catch (Exception e) {
459 nextReadCalled = true;
461 if (e is System.Net.Sockets.SocketException)
462 e = new IOException ("Error writing request", e);
463 result.SetCompleted (false, e);
465 complete_request_written = true;
466 result.DoCallback ();
469 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
470 AsyncCallback cb, object state)
473 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
476 throw new NotSupportedException ("this stream does not allow writing");
479 throw new ArgumentNullException ("buffer");
481 int length = buffer.Length;
482 if (offset < 0 || length < offset)
483 throw new ArgumentOutOfRangeException ("offset");
484 if (size < 0 || (length - offset) < size)
485 throw new ArgumentOutOfRangeException ("size");
494 WebAsyncResult result = new WebAsyncResult (cb, state);
496 CheckWriteOverflow (request.ContentLength, totalWritten, size);
497 if (allowBuffering && !sendChunked) {
498 if (writeBuffer == null)
499 writeBuffer = new MemoryStream ();
500 writeBuffer.Write (buffer, offset, size);
501 totalWritten += size;
502 if (request.ContentLength > 0 && totalWritten == request.ContentLength) {
504 result.AsyncWriteAll = true;
505 result.InnerAsyncResult = WriteRequestAsync (new AsyncCallback (WriteRequestAsyncCB), result);
506 if (result.InnerAsyncResult == null) {
507 if (!result.IsCompleted)
508 result.SetCompleted (true, 0);
509 result.DoCallback ();
511 } catch (Exception exc) {
512 result.SetCompleted (true, exc);
513 result.DoCallback ();
516 result.SetCompleted (true, 0);
517 result.DoCallback ();
522 AsyncCallback callback = null;
524 callback = cb_wrapper;
529 string cSize = String.Format ("{0:X}\r\n", size);
530 byte [] head = Encoding.ASCII.GetBytes (cSize);
531 int chunkSize = 2 + size + head.Length;
532 byte [] newBuffer = new byte [chunkSize];
533 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
534 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
535 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
543 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
544 } catch (Exception) {
547 result.SetCompleted (true, 0);
548 result.DoCallback ();
550 totalWritten += size;
554 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
556 if (contentLength == -1)
559 long avail = contentLength - totalWritten;
562 nextReadCalled = true;
564 throw new ProtocolViolationException (
565 "The number of bytes to be written is greater than " +
566 "the specified ContentLength.");
570 public override void EndWrite (IAsyncResult r)
573 throw new ArgumentNullException ("r");
575 WebAsyncResult result = r as WebAsyncResult;
577 throw new ArgumentException ("Invalid IAsyncResult");
579 if (result.EndCalled)
582 result.EndCalled = true;
583 if (result.AsyncWriteAll) {
584 result.WaitUntilComplete ();
585 if (result.GotException)
586 throw result.Exception;
590 if (allowBuffering && !sendChunked)
593 if (result.GotException)
594 throw result.Exception;
597 cnc.EndWrite2 (request, result.InnerAsyncResult);
598 result.SetCompleted (false, 0);
599 result.DoCallback ();
600 } catch (Exception e) {
602 result.SetCompleted (false, 0);
604 result.SetCompleted (false, e);
605 result.DoCallback ();
612 if (pendingWrites == 0)
619 public override void Write (byte [] buffer, int offset, int size)
621 AsyncCallback cb = cb_wrapper;
622 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
623 if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
625 nextReadCalled = true;
627 throw new IOException ("Write timed out.");
633 public override void Flush ()
637 internal void SetHeaders (byte [] buffer)
643 long cl = request.ContentLength;
644 string method = request.Method;
645 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
646 method == "TRACE" || method == "DELETE");
647 if (sendChunked || cl > -1 || no_writestream) {
651 WebConnection.InitRead (cnc);
653 if (!sendChunked && cl == 0)
654 requestWritten = true;
658 internal bool RequestWritten {
659 get { return requestWritten; }
662 IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
664 requestWritten = true;
665 byte [] bytes = writeBuffer.GetBuffer ();
666 int length = (int) writeBuffer.Length;
667 // Headers already written to the stream
668 return (length > 0) ? cnc.BeginWrite (request, bytes, 0, length, cb, state) : null;
677 string err_msg = null;
678 if (!cnc.Write (request, headers, 0, headers.Length, ref err_msg))
679 throw new WebException ("Error writing request: " + err_msg, null, WebExceptionStatus.SendFailure, null);
682 internal void WriteRequest ()
687 requestWritten = true;
691 if (!allowBuffering || writeBuffer == null)
694 byte [] bytes = writeBuffer.GetBuffer ();
695 int length = (int) writeBuffer.Length;
696 if (request.ContentLength != -1 && request.ContentLength < length) {
697 nextReadCalled = true;
699 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
700 WebExceptionStatus.ServerProtocolViolation, null);
704 string method = request.Method;
705 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
706 method == "TRACE" || method == "DELETE");
708 request.InternalContentLength = length;
709 request.SendRequestHeaders (true);
712 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
715 IAsyncResult result = null;
717 result = cnc.BeginWrite (request, bytes, 0, length, null, null);
721 WebConnection.InitRead (cnc);
725 complete_request_written = cnc.EndWrite (request, result);
727 complete_request_written = true;
730 internal void InternalClose ()
735 public override void Close ()
742 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
743 string err_msg = null;
744 cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
749 if (!nextReadCalled) {
751 // If we have not read all the contents
752 if (!nextReadCalled) {
753 nextReadCalled = true;
758 } else if (!allowBuffering) {
759 complete_request_written = true;
762 WebConnection.InitRead (cnc);
767 if (disposed || requestWritten)
770 long length = request.ContentLength;
772 if (!sendChunked && length != -1 && totalWritten != length) {
773 IOException io = new IOException ("Cannot close the stream until all bytes are written");
774 nextReadCalled = true;
776 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
779 // Commented out the next line to fix xamarin bug #1512
784 internal void KillBuffer ()
789 public override long Seek (long a, SeekOrigin b)
791 throw new NotSupportedException ();
794 public override void SetLength (long a)
796 throw new NotSupportedException ();
799 public override bool CanSeek {
800 get { return false; }
803 public override bool CanRead {
804 get { return !disposed && isRead; }
807 public override bool CanWrite {
808 get { return !disposed && !isRead; }
811 public override long Length {
814 throw new NotSupportedException ();
815 return stream_length;
819 public override long Position {
820 get { throw new NotSupportedException (); }
821 set { throw new NotSupportedException (); }