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 public WebConnectionStream (WebConnection cnc)
66 pending = new ManualResetEvent (true);
67 this.request = cnc.Data.request;
69 string clength = cnc.Data.Headers ["Content-Length"];
70 if (clength != null && clength != "") {
72 contentLength = Int32.Parse (clength);
74 contentLength = Int32.MaxValue;
77 contentLength = Int32.MaxValue;
81 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
85 this.request = request;
86 allowBuffering = request.InternalAllowBuffering;
87 sendChunked = request.SendChunked;
89 writeBuffer = new MemoryStream ();
92 pending = new ManualResetEvent (true);
95 internal bool SendChunked {
96 set { sendChunked = value; }
99 internal byte [] ReadBuffer {
100 set { readBuffer = value; }
103 internal int ReadBufferOffset {
104 set { readBufferOffset = value;}
107 internal int ReadBufferSize {
108 set { readBufferSize = value; }
111 internal byte[] WriteBuffer {
112 get { return writeBuffer.GetBuffer (); }
115 internal int WriteBufferLength {
116 get { return (int) writeBuffer.Length; }
119 internal void ForceCompletion ()
121 nextReadCalled = true;
125 internal void CheckComplete ()
127 bool nrc = nextReadCalled;
128 if (!nrc && readBufferSize - readBufferOffset == contentLength) {
129 nextReadCalled = true;
134 internal void ReadAll ()
136 if (!isRead || totalRead >= contentLength || nextReadCalled) {
137 if (!nextReadCalled) {
138 nextReadCalled = true;
146 if (totalRead >= contentLength)
150 int diff = readBufferSize - readBufferOffset;
153 if (contentLength == Int32.MaxValue) {
154 MemoryStream ms = new MemoryStream ();
155 byte [] buffer = null;
156 if (readBuffer != null && diff > 0) {
157 ms.Write (readBuffer, readBufferOffset, diff);
158 if (readBufferSize >= 8192)
163 buffer = new byte [8192];
166 while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
167 ms.Write (buffer, 0, read);
170 new_size = (int) ms.Length;
171 contentLength = new_size;
173 new_size = contentLength - totalRead;
174 b = new byte [new_size];
175 if (readBuffer != null && diff > 0) {
179 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
182 int remaining = new_size - diff;
184 while (remaining > 0 && r != 0) {
185 r = cnc.Read (b, diff, remaining);
192 readBufferOffset = 0;
193 readBufferSize = new_size;
195 nextReadCalled = true;
201 void WriteCallbackWrapper (IAsyncResult r)
203 WebAsyncResult result;
204 if (r.AsyncState != null) {
205 result = (WebAsyncResult) r.AsyncState;
206 result.InnerAsyncResult = r;
207 result.DoCallback ();
213 void ReadCallbackWrapper (IAsyncResult r)
215 WebAsyncResult result;
216 if (r.AsyncState != null) {
217 result = (WebAsyncResult) r.AsyncState;
218 result.InnerAsyncResult = r;
219 result.DoCallback ();
225 public override int Read (byte [] buffer, int offset, int size)
228 throw new NotSupportedException ("this stream does not allow reading");
230 if (totalRead >= contentLength)
233 AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
234 WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
235 if (!res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
237 throw new IOException ("Read timed out.");
240 return EndRead (res);
243 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
244 AsyncCallback cb, object state)
247 throw new NotSupportedException ("this stream does not allow reading");
250 throw new ArgumentNullException ("buffer");
252 int length = buffer.Length;
253 if (size < 0 || offset < 0 || length < offset || length - offset < size)
254 throw new ArgumentOutOfRangeException ();
261 WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
262 if (totalRead >= contentLength) {
263 result.SetCompleted (true, -1);
264 result.DoCallback ();
268 int remaining = readBufferSize - readBufferOffset;
270 int copy = (remaining > size) ? size : remaining;
271 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
272 readBufferOffset += copy;
276 if (size == 0 || totalRead >= contentLength) {
277 result.SetCompleted (true, copy);
278 result.DoCallback ();
281 result.NBytes = copy;
285 cb = new AsyncCallback (ReadCallbackWrapper);
287 if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
288 size = contentLength - totalRead;
290 result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
294 public override int EndRead (IAsyncResult r)
296 WebAsyncResult result = (WebAsyncResult) r;
297 if (result.EndCalled) {
298 int xx = result.NBytes;
299 return (xx >= 0) ? xx : 0;
302 result.EndCalled = true;
304 if (!result.IsCompleted) {
305 int nbytes = cnc.EndRead (result);
306 bool finished = (nbytes == -1);
307 if (finished && result.NBytes > 0)
311 result.SetCompleted (false, nbytes + result.NBytes);
312 result.DoCallback ();
313 if (finished || nbytes == 0)
314 contentLength = totalRead;
319 if (pendingReads == 0)
323 if (totalRead >= contentLength && !nextReadCalled)
326 int nb = result.NBytes;
327 return (nb >= 0) ? nb : 0;
330 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
331 AsyncCallback cb, object state)
334 throw new NotSupportedException ("this stream does not allow writing");
337 throw new ArgumentNullException ("buffer");
339 int length = buffer.Length;
340 if (size < 0 || offset < 0 || length < offset || length - offset < size)
341 throw new ArgumentOutOfRangeException ();
350 WebAsyncResult result = new WebAsyncResult (cb, state);
351 if (allowBuffering) {
352 writeBuffer.Write (buffer, offset, size);
354 result.SetCompleted (true, 0);
355 result.DoCallback ();
360 AsyncCallback callback = null;
362 callback = new AsyncCallback (WriteCallbackWrapper);
367 string cSize = String.Format ("{0:X}\r\n", size);
368 byte [] head = Encoding.ASCII.GetBytes (cSize);
369 int chunkSize = 2 + size + head.Length;
370 byte [] newBuffer = new byte [chunkSize];
371 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
372 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
373 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
380 result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
384 public override void EndWrite (IAsyncResult r)
387 throw new ArgumentNullException ("r");
389 WebAsyncResult result = r as WebAsyncResult;
391 throw new ArgumentException ("Invalid IAsyncResult");
393 if (result.EndCalled)
396 result.EndCalled = true;
398 if (allowBuffering && !sendChunked)
401 if (result.GotException)
402 throw result.Exception;
404 cnc.EndWrite (result.InnerAsyncResult);
405 result.SetCompleted (false, 0);
409 if (pendingWrites == 0)
415 public override void Write (byte [] buffer, int offset, int size)
418 throw new NotSupportedException ("This stream does not allow writing");
420 AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
421 WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
422 if (!res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
424 throw new IOException ("Write timed out.");
430 public override void Flush ()
434 internal void SetHeaders (byte [] buffer, int offset, int size)
439 if (!allowBuffering || sendChunked) {
442 throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
444 cnc.Write (buffer, offset, size);
447 WebConnection.InitRead (cnc);
450 headers = new byte [size];
451 Buffer.BlockCopy (buffer, offset, headers, 0, size);
455 internal bool RequestWritten {
456 get { return requestWritten; }
459 internal void WriteRequest ()
465 request.SendRequestHeaders ();
466 requestWritten = true;
470 if (!allowBuffering || writeBuffer == null)
473 byte [] bytes = writeBuffer.GetBuffer ();
474 int length = (int) writeBuffer.Length;
475 if (request.ContentLength != -1 && request.ContentLength < length) {
476 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
477 WebExceptionStatus.ServerProtocolViolation, null);
480 request.InternalContentLength = length;
481 request.SendRequestHeaders ();
482 requestWritten = true;
483 cnc.Write (headers, 0, headers.Length);
485 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
488 if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
491 cnc.Write (bytes, 0, length);
494 internal void InternalClose ()
499 public override void Close ()
503 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
504 cnc.Write (chunk, 0, chunk.Length);
509 if (!nextReadCalled) {
511 // If we have not read all the contents
516 } else if (!allowBuffering) {
519 WebConnection.InitRead (cnc);
529 long length = request.ContentLength;
530 if (length != -1 && length > writeBuffer.Length)
531 throw new IOException ("Cannot close the stream until all bytes are written");
536 WebConnection.InitRead (cnc);
540 public override long Seek (long a, SeekOrigin b)
542 throw new NotSupportedException ();
545 public override void SetLength (long a)
547 throw new NotSupportedException ();
550 public override bool CanSeek {
551 get { return false; }
554 public override bool CanRead {
555 get { return isRead; }
558 public override bool CanWrite {
559 get { return !isRead; }
562 public override long Length {
563 get { throw new NotSupportedException (); }
566 public override long Position {
567 get { throw new NotSupportedException (); }
568 set { throw new NotSupportedException (); }