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);
80 contentLength = Int32.MaxValue;
83 contentLength = Int32.MaxValue;
87 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
91 this.request = request;
92 allowBuffering = request.InternalAllowBuffering;
93 sendChunked = request.SendChunked;
95 writeBuffer = new MemoryStream ();
96 max_buffer_size = request.ContentLength;
102 pending = new ManualResetEvent (true);
105 public override bool CanTimeout {
110 internal bool CompleteRequestWritten {
111 get { return complete_request_written; }
114 internal bool SendChunked {
115 set { sendChunked = value; }
118 internal byte [] ReadBuffer {
119 set { readBuffer = value; }
122 internal int ReadBufferOffset {
123 set { readBufferOffset = value;}
126 internal int ReadBufferSize {
127 set { readBufferSize = value; }
130 internal byte[] WriteBuffer {
131 get { return writeBuffer.GetBuffer (); }
134 internal int WriteBufferLength {
135 get { return (int) writeBuffer.Length; }
138 internal void ForceCompletion ()
140 nextReadCalled = true;
144 internal void CheckComplete ()
146 bool nrc = nextReadCalled;
147 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
148 nextReadCalled = true;
153 internal void ReadAll ()
155 if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
156 if (isRead && !nextReadCalled) {
157 nextReadCalled = true;
165 if (totalRead >= contentLength)
169 int diff = readBufferSize - readBufferOffset;
172 if (contentLength == Int32.MaxValue) {
173 MemoryStream ms = new MemoryStream ();
174 byte [] buffer = null;
175 if (readBuffer != null && diff > 0) {
176 ms.Write (readBuffer, readBufferOffset, diff);
177 if (readBufferSize >= 8192)
182 buffer = new byte [8192];
185 while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
186 ms.Write (buffer, 0, read);
189 new_size = (int) ms.Length;
190 contentLength = new_size;
192 new_size = contentLength - totalRead;
193 b = new byte [new_size];
194 if (readBuffer != null && diff > 0) {
198 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
201 int remaining = new_size - diff;
203 while (remaining > 0 && r != 0) {
204 r = cnc.Read (b, diff, remaining);
211 readBufferOffset = 0;
212 readBufferSize = new_size;
214 nextReadCalled = true;
220 void WriteCallbackWrapper (IAsyncResult r)
222 WebAsyncResult result;
223 if (r.AsyncState != null) {
224 result = (WebAsyncResult) r.AsyncState;
225 result.InnerAsyncResult = r;
226 result.DoCallback ();
232 void ReadCallbackWrapper (IAsyncResult r)
234 WebAsyncResult result;
235 if (r.AsyncState != null) {
236 result = (WebAsyncResult) r.AsyncState;
237 result.InnerAsyncResult = r;
238 result.DoCallback ();
244 public override int Read (byte [] buffer, int offset, int size)
247 throw new NotSupportedException ("this stream does not allow reading");
249 if (totalRead >= contentLength)
252 AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
253 WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
254 if (!res.IsCompleted && !res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
255 nextReadCalled = true;
257 throw new WebException ("The operation has timed out.",
258 WebExceptionStatus.Timeout);
261 return EndRead (res);
264 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
265 AsyncCallback cb, object state)
268 throw new NotSupportedException ("this stream does not allow reading");
271 throw new ArgumentNullException ("buffer");
273 int length = buffer.Length;
274 if (size < 0 || offset < 0 || length < offset || length - offset < size)
275 throw new ArgumentOutOfRangeException ();
282 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
283 if (totalRead >= contentLength) {
284 result.SetCompleted (true, -1);
285 result.DoCallback ();
289 int remaining = readBufferSize - readBufferOffset;
291 int copy = (remaining > size) ? size : remaining;
292 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
293 readBufferOffset += copy;
297 if (size == 0 || totalRead >= contentLength) {
298 result.SetCompleted (true, copy);
299 result.DoCallback ();
302 result.NBytes = copy;
306 cb = new AsyncCallback (ReadCallbackWrapper);
308 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
309 size = contentLength - totalRead;
312 result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
314 result.SetCompleted (true, result.NBytes);
315 result.DoCallback ();
320 public override int EndRead (IAsyncResult r)
322 WebAsyncResult result = (WebAsyncResult) r;
323 if (result.EndCalled) {
324 int xx = result.NBytes;
325 return (xx >= 0) ? xx : 0;
328 result.EndCalled = true;
330 if (!result.IsCompleted) {
333 nbytes = cnc.EndRead (result);
334 } catch (Exception exc) {
337 if (pendingReads == 0)
341 nextReadCalled = true;
343 result.SetCompleted (false, exc);
353 result.SetCompleted (false, nbytes + result.NBytes);
354 result.DoCallback ();
356 contentLength = totalRead;
361 if (pendingReads == 0)
365 if (totalRead >= contentLength && !nextReadCalled)
368 int nb = result.NBytes;
369 return (nb >= 0) ? nb : 0;
372 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
373 AsyncCallback cb, object state)
376 throw new NotSupportedException ("this stream does not allow writing");
379 throw new ArgumentNullException ("buffer");
381 int length = buffer.Length;
382 if (size < 0 || offset < 0 || length < offset || length - offset < size)
383 throw new ArgumentOutOfRangeException ();
392 WebAsyncResult result = new WebAsyncResult (cb, state);
393 if (allowBuffering) {
394 if (max_buffer_size >= 0) {
395 long avail = max_buffer_size - writeBuffer.Length;
398 throw new ProtocolViolationException (
399 "The number of bytes to be written is greater than " +
400 "the specified ContentLength.");
403 writeBuffer.Write (buffer, offset, size);
405 result.SetCompleted (true, 0);
406 result.DoCallback ();
411 AsyncCallback callback = null;
413 callback = new AsyncCallback (WriteCallbackWrapper);
418 string cSize = String.Format ("{0:X}\r\n", size);
419 byte [] head = Encoding.ASCII.GetBytes (cSize);
420 int chunkSize = 2 + size + head.Length;
421 byte [] newBuffer = new byte [chunkSize];
422 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
423 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
424 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
431 result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
435 public override void EndWrite (IAsyncResult r)
438 throw new ArgumentNullException ("r");
440 WebAsyncResult result = r as WebAsyncResult;
442 throw new ArgumentException ("Invalid IAsyncResult");
444 if (result.EndCalled)
447 result.EndCalled = true;
449 if (allowBuffering && !sendChunked)
452 if (result.GotException)
453 throw result.Exception;
456 cnc.EndWrite (result.InnerAsyncResult);
457 result.SetCompleted (false, 0);
458 } catch (Exception e) {
459 result.SetCompleted (false, e);
465 if (pendingWrites == 0)
471 public override void Write (byte [] buffer, int offset, int size)
474 throw new NotSupportedException ("This stream does not allow writing");
476 AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
477 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
478 if (!res.IsCompleted && !res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
479 nextReadCalled = true;
481 throw new IOException ("Write timed out.");
487 public override void Flush ()
491 internal void SetHeaders (byte [] buffer, int offset, int size)
496 if (!allowBuffering || sendChunked) {
499 throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
502 if (!cnc.Write (buffer, offset, size))
503 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
507 WebConnection.InitRead (cnc);
510 headers = new byte [size];
511 Buffer.BlockCopy (buffer, offset, headers, 0, size);
515 internal bool RequestWritten {
516 get { return requestWritten; }
519 internal void WriteRequest ()
525 request.SendRequestHeaders ();
526 requestWritten = true;
530 if (!allowBuffering || writeBuffer == null)
533 byte [] bytes = writeBuffer.GetBuffer ();
534 int length = (int) writeBuffer.Length;
535 if (request.ContentLength != -1 && request.ContentLength < length) {
536 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
537 WebExceptionStatus.ServerProtocolViolation, null);
540 request.InternalContentLength = length;
541 request.SendRequestHeaders ();
542 requestWritten = true;
545 // For small requests, make a copy, it will reduce the traffic, for large
546 // requests, the NoDelay bit on the socket should take effect (set in WebConnection).
548 if (headers.Length + length < 8192){
549 byte[] b = new byte [headers.Length + length];
551 Buffer.BlockCopy (headers, 0, b, 0, headers.Length);
552 Buffer.BlockCopy (bytes, 0, b, headers.Length, length);
554 if (!cnc.Write (b, 0, b.Length))
555 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
558 complete_request_written = true;
562 WebConnection.InitRead (cnc);
565 if (!cnc.Write (headers, 0, headers.Length))
566 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
569 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
572 IAsyncResult result = null;
574 result = cnc.BeginWrite (bytes, 0, length, null, null);
578 WebConnection.InitRead (cnc);
582 complete_request_written = cnc.EndWrite (result);
584 complete_request_written = true;
588 internal void InternalClose ()
593 internal void ForceCloseConnection ()
601 public override void Close ()
605 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
606 cnc.Write (chunk, 0, chunk.Length);
611 if (!nextReadCalled) {
613 // If we have not read all the contents
614 if (!nextReadCalled) {
615 nextReadCalled = true;
620 } else if (!allowBuffering) {
621 complete_request_written = true;
624 WebConnection.InitRead (cnc);
632 long length = request.ContentLength;
633 if (length != -1 && length > writeBuffer.Length)
634 throw new IOException ("Cannot close the stream until all bytes are written");
640 internal void KillBuffer ()
645 public override long Seek (long a, SeekOrigin b)
647 throw new NotSupportedException ();
650 public override void SetLength (long a)
652 throw new NotSupportedException ();
655 public override bool CanSeek {
656 get { return false; }
659 public override bool CanRead {
660 get { return isRead; }
663 public override bool CanWrite {
664 get { return !isRead; }
667 public override long Length {
668 get { throw new NotSupportedException (); }
671 public override long Position {
672 get { throw new NotSupportedException (); }
673 set { throw new NotSupportedException (); }