2005-04-07 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System / System.Net / WebConnectionStream.cs
1 //
2 // System.Net.WebConnectionStream
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
8 // (C) 2004 Novell, Inc (http://www.novell.com)
9 //
10
11 //
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:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
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.
30 //
31
32 using System.IO;
33 using System.Text;
34 using System.Threading;
35
36 namespace System.Net
37 {
38         class WebConnectionStream : Stream
39         {
40                 static byte [] crlf = new byte [] { 13, 10 };
41                 bool isRead;
42                 WebConnection cnc;
43                 HttpWebRequest request;
44                 byte [] readBuffer;
45                 int readBufferOffset;
46                 int readBufferSize;
47                 int contentLength;
48                 int totalRead;
49                 bool nextReadCalled;
50                 int pendingReads;
51                 int pendingWrites;
52                 ManualResetEvent pending;
53                 bool allowBuffering;
54                 bool sendChunked;
55                 MemoryStream writeBuffer;
56                 bool requestWritten;
57                 byte [] headers;
58                 bool disposed;
59                 bool headersSent;
60
61                 public WebConnectionStream (WebConnection cnc)
62                 {
63                         isRead = true;
64                         pending = new ManualResetEvent (true);
65                         this.cnc = cnc;
66                         string clength = cnc.Data.Headers ["Content-Length"];
67                         if (clength != null && clength != "") {
68                                 try {
69                                         contentLength = Int32.Parse (clength);
70                                 } catch {
71                                         contentLength = Int32.MaxValue;
72                                 }
73                         } else {
74                                 contentLength = Int32.MaxValue;
75                         }
76                 }
77
78                 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
79                 {
80                         isRead = false;
81                         this.cnc = cnc;
82                         this.request = request;
83                         allowBuffering = request.InternalAllowBuffering;
84                         sendChunked = request.SendChunked;
85                         if (allowBuffering)
86                                 writeBuffer = new MemoryStream ();
87
88                         if (sendChunked)
89                                 pending = new ManualResetEvent (true);
90                 }
91
92                 internal bool SendChunked {
93                         set { sendChunked = value; }
94                 }
95
96                 internal byte [] ReadBuffer {
97                         set { readBuffer = value; }
98                 }
99
100                 internal int ReadBufferOffset {
101                         set { readBufferOffset = value;}
102                 }
103                 
104                 internal int ReadBufferSize {
105                         set { readBufferSize = value; }
106                 }
107                 
108                 internal byte[] WriteBuffer {
109                         get { return writeBuffer.GetBuffer (); }
110                 }
111
112                 internal int WriteBufferLength {
113                         get { return (int) writeBuffer.Length; }
114                 }
115
116                 internal void ForceCompletion ()
117                 {
118                         nextReadCalled = true;
119                         cnc.NextRead ();
120                 }
121                 
122                 internal void CheckComplete ()
123                 {
124                         bool nrc = nextReadCalled;
125                         if (!nrc && readBufferSize - readBufferOffset == contentLength) {
126                                 nextReadCalled = true;
127                                 cnc.NextRead ();
128                         }
129                 }
130
131                 internal void ReadAll ()
132                 {
133                         if (!isRead || totalRead >= contentLength || nextReadCalled) {
134                                 if (!nextReadCalled) {
135                                         nextReadCalled = true;
136                                         cnc.NextRead ();
137                                 }
138                                 return;
139                         }
140
141                         pending.WaitOne ();
142                         lock (this) {
143                                 if (totalRead >= contentLength)
144                                         return;
145                                 
146                                 byte [] b = null;
147                                 int diff = readBufferSize - readBufferOffset;
148                                 int new_size;
149
150                                 if (contentLength == Int32.MaxValue) {
151                                         MemoryStream ms = new MemoryStream ();
152                                         byte [] buffer = null;
153                                         if (readBuffer != null && diff > 0) {
154                                                 ms.Write (readBuffer, readBufferOffset, diff);
155                                                 if (readBufferSize >= 8192)
156                                                         buffer = readBuffer;
157                                         }
158
159                                         if (buffer == null)
160                                                 buffer = new byte [8192];
161
162                                         int read;
163                                         while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
164                                                 ms.Write (buffer, 0, read);
165
166                                         b = ms.GetBuffer ();
167                                         new_size = (int) ms.Length;
168                                         contentLength = new_size;
169                                 } else {
170                                         new_size = contentLength - totalRead;
171                                         b = new byte [new_size];
172                                         if (readBuffer != null && diff > 0) {
173                                                 if (diff > new_size)
174                                                         diff = new_size;
175
176                                                 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
177                                         }
178                                         
179                                         int remaining = new_size - diff;
180                                         int r = -1;
181                                         while (remaining > 0 && r != 0) {
182                                                 r = cnc.Read (b, diff, remaining);
183                                                 remaining -= r;
184                                                 diff += r;
185                                         }
186                                 }
187
188                                 readBuffer = b;
189                                 readBufferOffset = 0;
190                                 readBufferSize = new_size;
191                                 totalRead = 0;
192                                 nextReadCalled = true;
193                         }
194
195                         cnc.NextRead ();
196                 }
197                 
198                 static void CallbackWrapper (IAsyncResult r)
199                 {
200                         WebAsyncResult result = (WebAsyncResult) r.AsyncState;
201                         result.InnerAsyncResult = r;
202                         result.DoCallback ();
203                 }
204
205                 public override int Read (byte [] buffer, int offset, int size)
206                 {
207                         if (!isRead)
208                                 throw new NotSupportedException ("this stream does not allow reading");
209
210                         if (totalRead >= contentLength)
211                                 return 0;
212
213                         IAsyncResult res = BeginRead (buffer, offset, size, null, null);
214                         return EndRead (res);
215                 }
216
217                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
218                                                         AsyncCallback cb, object state)
219                 {
220                         if (!isRead)
221                                 throw new NotSupportedException ("this stream does not allow reading");
222
223                         if (buffer == null)
224                                 throw new ArgumentNullException ("buffer");
225
226                         int length = buffer.Length;
227                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
228                                 throw new ArgumentOutOfRangeException ();
229
230                         lock (this) {
231                                 pendingReads++;
232                                 pending.Reset ();
233                         }
234
235                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
236                         if (totalRead >= contentLength) {
237                                 result.SetCompleted (true, -1);
238                                 result.DoCallback ();
239                                 return result;
240                         }
241                         
242                         int remaining = readBufferSize - readBufferOffset;
243                         if (remaining > 0) {
244                                 int copy = (remaining > size) ? size : remaining;
245                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
246                                 readBufferOffset += copy;
247                                 offset += copy;
248                                 size -= copy;
249                                 totalRead += copy;
250                                 if (size == 0 || totalRead >= contentLength) {
251                                         result.SetCompleted (true, copy);
252                                         result.DoCallback ();
253                                         return result;
254                                 }
255                                 result.NBytes = copy;
256                         }
257
258                         if (cb != null)
259                                 cb = new AsyncCallback (CallbackWrapper);
260
261                         if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
262                                 size = contentLength - totalRead;
263
264                         result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
265                         return result;
266                 }
267
268                 public override int EndRead (IAsyncResult r)
269                 {
270                         WebAsyncResult result = (WebAsyncResult) r;
271
272                         if (!result.IsCompleted) {
273                                 int nbytes = cnc.EndRead (result.InnerAsyncResult);
274                                 bool finished = (nbytes == -1);
275                                 if (finished && result.NBytes > 0)
276                                         nbytes = 0;
277
278                                 result.SetCompleted (false, nbytes + result.NBytes);
279                                 totalRead += nbytes;
280                                 if (finished || nbytes == 0)
281                                         contentLength = totalRead;
282                         }
283
284                         lock (this) {
285                                 pendingReads--;
286                                 if (pendingReads == 0)
287                                         pending.Set ();
288                         }
289
290                         if (totalRead >= contentLength && !nextReadCalled)
291                                 ReadAll ();
292
293                         return result.NBytes;
294                 }
295                 
296                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
297                                                         AsyncCallback cb, object state)
298                 {
299                         if (isRead)
300                                 throw new NotSupportedException ("this stream does not allow writing");
301
302                         if (buffer == null)
303                                 throw new ArgumentNullException ("buffer");
304
305                         int length = buffer.Length;
306                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
307                                 throw new ArgumentOutOfRangeException ();
308
309                         if (sendChunked) {
310                                 lock (this) {
311                                         pendingWrites++;
312                                         pending.Reset ();
313                                 }
314                         }
315
316                         WebAsyncResult result = new WebAsyncResult (cb, state);
317                         if (allowBuffering) {
318                                 writeBuffer.Write (buffer, offset, size);
319                                 if (!sendChunked) {
320                                         result.SetCompleted (true, 0);
321                                         result.DoCallback ();
322                                         return result;
323                                 }
324                         }
325
326                         AsyncCallback callback = null;
327                         if (cb != null)
328                                 callback = new AsyncCallback (CallbackWrapper);
329
330                         if (sendChunked) {
331                                 WriteRequest ();
332
333                                 string cSize = String.Format ("{0:X}\r\n", size);
334                                 byte [] head = Encoding.ASCII.GetBytes (cSize);
335                                 int chunkSize = 2 + size + head.Length;
336                                 byte [] newBuffer = new byte [chunkSize];
337                                 Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
338                                 Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
339                                 Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
340
341                                 buffer = newBuffer;
342                                 offset = 0;
343                                 size = chunkSize;
344                         }
345
346                         result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
347                         return result;
348                 }
349
350                 public override void EndWrite (IAsyncResult r)
351                 {
352                         if (r == null)
353                                 throw new ArgumentNullException ("r");
354
355                         if (allowBuffering && !sendChunked)
356                                 return;
357
358                         WebAsyncResult result = r as WebAsyncResult;
359                         if (result == null)
360                                 throw new ArgumentException ("Invalid IAsyncResult");
361
362                         if (result.GotException)
363                                 throw result.Exception;
364
365                         cnc.EndWrite (result.InnerAsyncResult);
366                         if (sendChunked) {
367                                 lock (this) {
368                                         pendingWrites--;
369                                         if (pendingWrites == 0)
370                                                 pending.Set ();
371                                 }
372                         }
373                 }
374                 
375                 public override void Write (byte [] buffer, int offset, int size)
376                 {
377                         if (isRead)
378                                 throw new NotSupportedException ("This stream does not allow writing");
379
380                         IAsyncResult res = BeginWrite (buffer, offset, size, null, null);
381                         EndWrite (res);
382                 }
383
384                 public override void Flush ()
385                 {
386                 }
387
388                 internal void SetHeaders (byte [] buffer, int offset, int size)
389                 {
390                         if (headersSent)
391                                 return;
392
393                         if (!allowBuffering || sendChunked) {
394                                 headersSent = true;
395                                 if (!cnc.Connected)
396                                         throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
397
398                                 cnc.Write (buffer, offset, size);
399                         } else {
400                                 headers = new byte [size];
401                                 Buffer.BlockCopy (buffer, offset, headers, 0, size);
402                         }
403                 }
404
405                 internal bool RequestWritten {
406                         get { return requestWritten; }
407                 }
408
409                 internal void WriteRequest ()
410                 {
411                         if (requestWritten)
412                                 return;
413
414                         if (sendChunked) {
415                                 request.SendRequestHeaders ();
416                                 requestWritten = true;
417                                 return;
418                         }
419
420                         if (!allowBuffering || writeBuffer == null)
421                                 return;
422
423                         byte [] bytes = writeBuffer.GetBuffer ();
424                         int length = (int) writeBuffer.Length;
425                         if (request.ContentLength != -1 && request.ContentLength < length) {
426                                 throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
427                                                         WebExceptionStatus.ServerProtocolViolation, null);
428                         }
429
430                         request.InternalContentLength = length;
431                         request.SendRequestHeaders ();
432                         requestWritten = true;
433                         cnc.Write (headers, 0, headers.Length);
434                         if (!cnc.Connected)
435                                 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
436
437                         headersSent = true;
438                         if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
439                                 return;
440
441                         cnc.Write (bytes, 0, length);
442                 }
443
444                 internal void InternalClose ()
445                 {
446                         disposed = true;
447                 }
448                 
449                 public override void Close ()
450                 {
451                         if (sendChunked) {
452                                 pending.WaitOne ();
453                                 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
454                                 cnc.Write (chunk, 0, chunk.Length);
455                                 return;
456                         }
457
458                         if (isRead) {
459                                 if (!nextReadCalled) {
460                                         CheckComplete ();
461                                         // If we have not read all the contents
462                                         if (!nextReadCalled)
463                                                 cnc.Close (true);
464                                 }
465                                 return;
466                         }
467
468                         if (!allowBuffering || disposed)
469                                 return;
470
471                         disposed = true;
472
473                         long length = request.ContentLength;
474                         if (length != -1 && length > writeBuffer.Length)
475                                 throw new IOException ("Cannot close the stream until all bytes are written");
476
477                         WriteRequest ();
478                 }
479
480                 public override long Seek (long a, SeekOrigin b)
481                 {
482                         throw new NotSupportedException ();
483                 }
484                 
485                 public override void SetLength (long a)
486                 {
487                         throw new NotSupportedException ();
488                 }
489                 
490                 public override bool CanSeek {
491                         get { return false; }
492                 }
493
494                 public override bool CanRead {
495                         get { return isRead; }
496                 }
497
498                 public override bool CanWrite {
499                         get { return !isRead; }
500                 }
501
502                 public override long Length {
503                         get { throw new NotSupportedException (); }
504                 }
505
506                 public override long Position {
507                         get { throw new NotSupportedException (); }
508                         set { throw new NotSupportedException (); }
509                 }
510         }
511 }
512