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, WebConnectionData data)
74 throw new InvalidOperationException ("data was not initialized");
75 if (data.Headers == null)
76 throw new InvalidOperationException ("data.Headers was not initialized");
77 if (data.request == null)
78 throw new InvalidOperationException ("data.request was not initialized");
80 cb_wrapper = new AsyncCallback (ReadCallbackWrapper);
81 pending = new ManualResetEvent (true);
82 this.request = data.request;
83 read_timeout = request.ReadWriteTimeout;
84 write_timeout = read_timeout;
86 string contentType = data.Headers ["Transfer-Encoding"];
87 bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
88 string clength = data.Headers ["Content-Length"];
89 if (!chunkedRead && clength != null && clength != "") {
91 contentLength = Int32.Parse (clength);
92 if (contentLength == 0 && !IsNtlmAuth ()) {
96 contentLength = Int32.MaxValue;
99 contentLength = Int32.MaxValue;
103 if (!Int32.TryParse (clength, out stream_length))
107 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
109 read_timeout = request.ReadWriteTimeout;
110 write_timeout = read_timeout;
112 cb_wrapper = new AsyncCallback (WriteCallbackWrapper);
114 this.request = request;
115 allowBuffering = request.InternalAllowBuffering;
116 sendChunked = request.SendChunked;
118 pending = new ManualResetEvent (true);
119 else if (allowBuffering)
120 writeBuffer = new MemoryStream ();
125 bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
126 string header_name = (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate";
127 string authHeader = cnc.Data.Headers [header_name];
128 return (authHeader != null && authHeader.IndexOf ("NTLM", StringComparison.Ordinal) != -1);
131 internal void CheckResponseInBuffer ()
133 if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
139 internal HttpWebRequest Request {
140 get { return request; }
143 internal WebConnection Connection {
146 public override bool CanTimeout {
150 public override int ReadTimeout {
157 throw new ArgumentOutOfRangeException ("value");
158 read_timeout = value;
162 public override int WriteTimeout {
164 return write_timeout;
169 throw new ArgumentOutOfRangeException ("value");
170 write_timeout = value;
174 internal bool CompleteRequestWritten {
175 get { return complete_request_written; }
178 internal bool SendChunked {
179 set { sendChunked = value; }
182 internal byte [] ReadBuffer {
183 set { readBuffer = value; }
186 internal int ReadBufferOffset {
187 set { readBufferOffset = value;}
190 internal int ReadBufferSize {
191 set { readBufferSize = value; }
194 internal byte[] WriteBuffer {
195 get { return writeBuffer.GetBuffer (); }
198 internal int WriteBufferLength {
199 get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
202 internal void ForceCompletion ()
204 if (!nextReadCalled) {
205 if (contentLength == Int32.MaxValue)
207 nextReadCalled = true;
212 internal void CheckComplete ()
214 bool nrc = nextReadCalled;
215 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
216 nextReadCalled = true;
221 internal void ReadAll ()
223 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
224 if (isRead && !nextReadCalled) {
225 nextReadCalled = true;
233 if (totalRead >= contentLength)
237 int diff = readBufferSize - readBufferOffset;
240 if (contentLength == Int32.MaxValue) {
241 MemoryStream ms = new MemoryStream ();
242 byte [] buffer = null;
243 if (readBuffer != null && diff > 0) {
244 ms.Write (readBuffer, readBufferOffset, diff);
245 if (readBufferSize >= 8192)
250 buffer = new byte [8192];
253 while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
254 ms.Write (buffer, 0, read);
257 new_size = (int) ms.Length;
258 contentLength = new_size;
260 new_size = contentLength - totalRead;
261 b = new byte [new_size];
262 if (readBuffer != null && diff > 0) {
266 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
269 int remaining = new_size - diff;
271 while (remaining > 0 && r != 0) {
272 r = cnc.Read (request, b, diff, remaining);
279 readBufferOffset = 0;
280 readBufferSize = new_size;
282 nextReadCalled = true;
288 void WriteCallbackWrapper (IAsyncResult r)
290 WebAsyncResult result = r as WebAsyncResult;
291 if (result != null && result.AsyncWriteAll)
294 if (r.AsyncState != null) {
295 result = (WebAsyncResult) r.AsyncState;
296 result.InnerAsyncResult = r;
297 result.DoCallback ();
306 void ReadCallbackWrapper (IAsyncResult r)
308 WebAsyncResult result;
309 if (r.AsyncState != null) {
310 result = (WebAsyncResult) r.AsyncState;
311 result.InnerAsyncResult = r;
312 result.DoCallback ();
321 public override int Read (byte [] buffer, int offset, int size)
323 AsyncCallback cb = cb_wrapper;
324 WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
325 if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
326 nextReadCalled = true;
328 throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
331 return EndRead (res);
334 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
335 AsyncCallback cb, object state)
338 throw new NotSupportedException ("this stream does not allow reading");
341 throw new ArgumentNullException ("buffer");
343 int length = buffer.Length;
344 if (offset < 0 || length < offset)
345 throw new ArgumentOutOfRangeException ("offset");
346 if (size < 0 || (length - offset) < size)
347 throw new ArgumentOutOfRangeException ("size");
354 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
355 if (totalRead >= contentLength) {
356 result.SetCompleted (true, -1);
357 result.DoCallback ();
361 int remaining = readBufferSize - readBufferOffset;
363 int copy = (remaining > size) ? size : remaining;
364 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
365 readBufferOffset += copy;
369 if (size == 0 || totalRead >= contentLength) {
370 result.SetCompleted (true, copy);
371 result.DoCallback ();
374 result.NBytes = copy;
380 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
381 size = contentLength - totalRead;
384 result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
386 result.SetCompleted (true, result.NBytes);
387 result.DoCallback ();
392 public override int EndRead (IAsyncResult r)
394 WebAsyncResult result = (WebAsyncResult) r;
395 if (result.EndCalled) {
396 int xx = result.NBytes;
397 return (xx >= 0) ? xx : 0;
400 result.EndCalled = true;
402 if (!result.IsCompleted) {
405 nbytes = cnc.EndRead (request, result);
406 } catch (Exception exc) {
409 if (pendingReads == 0)
413 nextReadCalled = true;
415 result.SetCompleted (false, exc);
416 result.DoCallback ();
426 result.SetCompleted (false, nbytes + result.NBytes);
427 result.DoCallback ();
429 contentLength = totalRead;
434 if (pendingReads == 0)
438 if (totalRead >= contentLength && !nextReadCalled)
441 int nb = result.NBytes;
442 return (nb >= 0) ? nb : 0;
445 void WriteRequestAsyncCB (IAsyncResult r)
447 WebAsyncResult result = (WebAsyncResult) r.AsyncState;
449 cnc.EndWrite2 (request, r);
450 result.SetCompleted (false, 0);
453 WebConnection.InitRead (cnc);
455 } catch (Exception e) {
457 nextReadCalled = true;
459 if (e is System.Net.Sockets.SocketException)
460 e = new IOException ("Error writing request", e);
461 result.SetCompleted (false, e);
463 complete_request_written = true;
464 result.DoCallback ();
467 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
468 AsyncCallback cb, object state)
471 throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
474 throw new NotSupportedException ("this stream does not allow writing");
477 throw new ArgumentNullException ("buffer");
479 int length = buffer.Length;
480 if (offset < 0 || length < offset)
481 throw new ArgumentOutOfRangeException ("offset");
482 if (size < 0 || (length - offset) < size)
483 throw new ArgumentOutOfRangeException ("size");
492 WebAsyncResult result = new WebAsyncResult (cb, state);
494 CheckWriteOverflow (request.ContentLength, totalWritten, size);
495 if (allowBuffering && !sendChunked) {
496 if (writeBuffer == null)
497 writeBuffer = new MemoryStream ();
498 writeBuffer.Write (buffer, offset, size);
499 totalWritten += size;
500 if (request.ContentLength > 0 && totalWritten == request.ContentLength) {
502 result.AsyncWriteAll = true;
503 result.InnerAsyncResult = WriteRequestAsync (new AsyncCallback (WriteRequestAsyncCB), result);
504 if (result.InnerAsyncResult == null) {
505 if (!result.IsCompleted)
506 result.SetCompleted (true, 0);
507 result.DoCallback ();
509 } catch (Exception exc) {
510 result.SetCompleted (true, exc);
511 result.DoCallback ();
514 result.SetCompleted (true, 0);
515 result.DoCallback ();
520 AsyncCallback callback = null;
522 callback = cb_wrapper;
527 string cSize = String.Format ("{0:X}\r\n", size);
528 byte [] head = Encoding.ASCII.GetBytes (cSize);
529 int chunkSize = 2 + size + head.Length;
530 byte [] newBuffer = new byte [chunkSize];
531 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
532 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
533 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
541 result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
542 } catch (Exception) {
545 result.SetCompleted (true, 0);
546 result.DoCallback ();
548 totalWritten += size;
552 void CheckWriteOverflow (long contentLength, long totalWritten, long size)
554 if (contentLength == -1)
557 long avail = contentLength - totalWritten;
560 nextReadCalled = true;
562 throw new ProtocolViolationException (
563 "The number of bytes to be written is greater than " +
564 "the specified ContentLength.");
568 public override void EndWrite (IAsyncResult r)
571 throw new ArgumentNullException ("r");
573 WebAsyncResult result = r as WebAsyncResult;
575 throw new ArgumentException ("Invalid IAsyncResult");
577 if (result.EndCalled)
580 result.EndCalled = true;
581 if (result.AsyncWriteAll) {
582 result.WaitUntilComplete ();
583 if (result.GotException)
584 throw result.Exception;
588 if (allowBuffering && !sendChunked)
591 if (result.GotException)
592 throw result.Exception;
595 cnc.EndWrite2 (request, result.InnerAsyncResult);
596 result.SetCompleted (false, 0);
597 result.DoCallback ();
598 } catch (Exception e) {
600 result.SetCompleted (false, 0);
602 result.SetCompleted (false, e);
603 result.DoCallback ();
610 if (pendingWrites == 0)
617 public override void Write (byte [] buffer, int offset, int size)
619 AsyncCallback cb = cb_wrapper;
620 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
621 if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
623 nextReadCalled = true;
625 throw new IOException ("Write timed out.");
631 public override void Flush ()
635 internal void SetHeaders (byte [] buffer)
641 long cl = request.ContentLength;
642 string method = request.Method;
643 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
645 bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
646 method == "COPY" || method == "MOVE" || method == "LOCK" ||
648 if (sendChunked || cl > -1 || no_writestream || webdav) {
652 WebConnection.InitRead (cnc);
654 if (!sendChunked && cl == 0)
655 requestWritten = true;
659 internal bool RequestWritten {
660 get { return requestWritten; }
663 IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
665 requestWritten = true;
666 byte [] bytes = writeBuffer.GetBuffer ();
667 int length = (int) writeBuffer.Length;
668 // Headers already written to the stream
669 return (length > 0) ? cnc.BeginWrite (request, bytes, 0, length, cb, state) : null;
678 string err_msg = null;
679 if (!cnc.Write (request, headers, 0, headers.Length, ref err_msg))
680 throw new WebException ("Error writing request: " + err_msg, null, WebExceptionStatus.SendFailure, null);
683 internal void WriteRequest ()
688 requestWritten = true;
692 if (!allowBuffering || writeBuffer == null)
695 byte [] bytes = writeBuffer.GetBuffer ();
696 int length = (int) writeBuffer.Length;
697 if (request.ContentLength != -1 && request.ContentLength < length) {
698 nextReadCalled = true;
700 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
701 WebExceptionStatus.ServerProtocolViolation, null);
705 string method = request.Method;
706 bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
709 request.InternalContentLength = length;
710 request.SendRequestHeaders (true);
713 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
716 IAsyncResult result = null;
718 result = cnc.BeginWrite (request, bytes, 0, length, null, null);
722 WebConnection.InitRead (cnc);
726 complete_request_written = cnc.EndWrite (request, result);
728 complete_request_written = true;
731 internal void InternalClose ()
736 public override void Close ()
743 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
744 string err_msg = null;
745 cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
750 if (!nextReadCalled) {
752 // If we have not read all the contents
753 if (!nextReadCalled) {
754 nextReadCalled = true;
759 } else if (!allowBuffering) {
760 complete_request_written = true;
763 WebConnection.InitRead (cnc);
768 if (disposed || requestWritten)
771 long length = request.ContentLength;
773 if (!sendChunked && length != -1 && totalWritten != length) {
774 IOException io = new IOException ("Cannot close the stream until all bytes are written");
775 nextReadCalled = true;
777 throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
780 // Commented out the next line to fix xamarin bug #1512
785 internal void KillBuffer ()
790 public override long Seek (long a, SeekOrigin b)
792 throw new NotSupportedException ();
795 public override void SetLength (long a)
797 throw new NotSupportedException ();
800 public override bool CanSeek {
801 get { return false; }
804 public override bool CanRead {
805 get { return !disposed && isRead; }
808 public override bool CanWrite {
809 get { return !disposed && !isRead; }
812 public override long Length {
815 throw new NotSupportedException ();
816 return stream_length;
820 public override long Position {
821 get { throw new NotSupportedException (); }
822 set { throw new NotSupportedException (); }