2007-07-14 Gonzalo Paniagua Javier <gonzalo.mono@gmail.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                 object locker = new object ();
61                 bool initRead;
62                 bool read_eof;
63                 bool complete_request_written;
64                 long max_buffer_size;
65
66                 public WebConnectionStream (WebConnection cnc)
67                 {
68                         isRead = true;
69                         pending = new ManualResetEvent (true);
70                         this.request = cnc.Data.request;
71                         this.cnc = cnc;
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 != "") {
76
77                                 try {
78                                         contentLength = Int32.Parse (clength);
79                                 } catch {
80                                         contentLength = Int32.MaxValue;
81                                 }
82                         } else {
83                                 contentLength = Int32.MaxValue;
84                         }
85                 }
86
87                 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
88                 {
89                         isRead = false;
90                         this.cnc = cnc;
91                         this.request = request;
92                         allowBuffering = request.InternalAllowBuffering;
93                         sendChunked = request.SendChunked;
94                         if (allowBuffering) {
95                                 writeBuffer = new MemoryStream ();
96                                 max_buffer_size = request.ContentLength;
97                         } else {
98                                 max_buffer_size = -1;
99                         }
100
101                         if (sendChunked)
102                                 pending = new ManualResetEvent (true);
103                 }
104 #if NET_2_0
105                 public override bool CanTimeout {
106                         get { return true; }
107                 }
108 #endif
109
110                 internal bool CompleteRequestWritten {
111                         get { return complete_request_written; }
112                 }
113
114                 internal bool SendChunked {
115                         set { sendChunked = value; }
116                 }
117
118                 internal byte [] ReadBuffer {
119                         set { readBuffer = value; }
120                 }
121
122                 internal int ReadBufferOffset {
123                         set { readBufferOffset = value;}
124                 }
125                 
126                 internal int ReadBufferSize {
127                         set { readBufferSize = value; }
128                 }
129                 
130                 internal byte[] WriteBuffer {
131                         get { return writeBuffer.GetBuffer (); }
132                 }
133
134                 internal int WriteBufferLength {
135                         get { return (int) writeBuffer.Length; }
136                 }
137
138                 internal void ForceCompletion ()
139                 {
140                         nextReadCalled = true;
141                         cnc.NextRead ();
142                 }
143                 
144                 internal void CheckComplete ()
145                 {
146                         bool nrc = nextReadCalled;
147                         if (!nrc && readBufferSize - readBufferOffset == contentLength) {
148                                 nextReadCalled = true;
149                                 cnc.NextRead ();
150                         }
151                 }
152
153                 internal void ReadAll ()
154                 {
155                         if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
156                                 if (isRead && !nextReadCalled) {
157                                         nextReadCalled = true;
158                                         cnc.NextRead ();
159                                 }
160                                 return;
161                         }
162
163                         pending.WaitOne ();
164                         lock (locker) {
165                                 if (totalRead >= contentLength)
166                                         return;
167                                 
168                                 byte [] b = null;
169                                 int diff = readBufferSize - readBufferOffset;
170                                 int new_size;
171
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)
178                                                         buffer = readBuffer;
179                                         }
180
181                                         if (buffer == null)
182                                                 buffer = new byte [8192];
183
184                                         int read;
185                                         while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
186                                                 ms.Write (buffer, 0, read);
187
188                                         b = ms.GetBuffer ();
189                                         new_size = (int) ms.Length;
190                                         contentLength = new_size;
191                                 } else {
192                                         new_size = contentLength - totalRead;
193                                         b = new byte [new_size];
194                                         if (readBuffer != null && diff > 0) {
195                                                 if (diff > new_size)
196                                                         diff = new_size;
197
198                                                 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
199                                         }
200                                         
201                                         int remaining = new_size - diff;
202                                         int r = -1;
203                                         while (remaining > 0 && r != 0) {
204                                                 r = cnc.Read (b, diff, remaining);
205                                                 remaining -= r;
206                                                 diff += r;
207                                         }
208                                 }
209
210                                 readBuffer = b;
211                                 readBufferOffset = 0;
212                                 readBufferSize = new_size;
213                                 totalRead = 0;
214                                 nextReadCalled = true;
215                         }
216
217                         cnc.NextRead ();
218                 }
219
220                 void WriteCallbackWrapper (IAsyncResult r)
221                 {
222                         WebAsyncResult result;
223                         if (r.AsyncState != null) {
224                                 result = (WebAsyncResult) r.AsyncState;
225                                 result.InnerAsyncResult = r;
226                                 result.DoCallback ();
227                         } else {
228                                 EndWrite (r);
229                         }
230                 }
231
232                 void ReadCallbackWrapper (IAsyncResult r)
233                 {
234                         WebAsyncResult result;
235                         if (r.AsyncState != null) {
236                                 result = (WebAsyncResult) r.AsyncState;
237                                 result.InnerAsyncResult = r;
238                                 result.DoCallback ();
239                         } else {
240                                 EndRead (r);
241                         }
242                 }
243
244                 public override int Read (byte [] buffer, int offset, int size)
245                 {
246                         if (!isRead)
247                                 throw new NotSupportedException ("this stream does not allow reading");
248
249                         if (totalRead >= contentLength)
250                                 return 0;
251
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;
256                                 cnc.Close (true);
257                                 throw new WebException ("The operation has timed out.",
258                                         WebExceptionStatus.Timeout);
259                         }
260
261                         return EndRead (res);
262                 }
263
264                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
265                                                         AsyncCallback cb, object state)
266                 {
267                         if (!isRead)
268                                 throw new NotSupportedException ("this stream does not allow reading");
269
270                         if (buffer == null)
271                                 throw new ArgumentNullException ("buffer");
272
273                         int length = buffer.Length;
274                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
275                                 throw new ArgumentOutOfRangeException ();
276
277                         lock (locker) {
278                                 pendingReads++;
279                                 pending.Reset ();
280                         }
281
282                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
283                         if (totalRead >= contentLength) {
284                                 result.SetCompleted (true, -1);
285                                 result.DoCallback ();
286                                 return result;
287                         }
288                         
289                         int remaining = readBufferSize - readBufferOffset;
290                         if (remaining > 0) {
291                                 int copy = (remaining > size) ? size : remaining;
292                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
293                                 readBufferOffset += copy;
294                                 offset += copy;
295                                 size -= copy;
296                                 totalRead += copy;
297                                 if (size == 0 || totalRead >= contentLength) {
298                                         result.SetCompleted (true, copy);
299                                         result.DoCallback ();
300                                         return result;
301                                 }
302                                 result.NBytes = copy;
303                         }
304
305                         if (cb != null)
306                                 cb = new AsyncCallback (ReadCallbackWrapper);
307
308                         if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
309                                 size = contentLength - totalRead;
310
311                         if (!read_eof) {
312                                 result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
313                         } else {
314                                 result.SetCompleted (true, result.NBytes);
315                                 result.DoCallback ();
316                         }
317                         return result;
318                 }
319
320                 public override int EndRead (IAsyncResult r)
321                 {
322                         WebAsyncResult result = (WebAsyncResult) r;
323                         if (result.EndCalled) {
324                                 int xx = result.NBytes;
325                                 return (xx >= 0) ? xx : 0;
326                         }
327
328                         result.EndCalled = true;
329
330                         if (!result.IsCompleted) {
331                                 int nbytes = -1;
332                                 try {
333                                         nbytes = cnc.EndRead (result);
334                                 } catch (Exception exc) {
335                                         lock (locker) {
336                                                 pendingReads--;
337                                                 if (pendingReads == 0)
338                                                         pending.Set ();
339                                         }
340
341                                         nextReadCalled = true;
342                                         cnc.Close (true);
343                                         result.SetCompleted (false, exc);
344                                         throw;
345                                 }
346
347                                 if (nbytes < 0) {
348                                         nbytes = 0;
349                                         read_eof = true;
350                                 }
351
352                                 totalRead += nbytes;
353                                 result.SetCompleted (false, nbytes + result.NBytes);
354                                 result.DoCallback ();
355                                 if (nbytes == 0)
356                                         contentLength = totalRead;
357                         }
358
359                         lock (locker) {
360                                 pendingReads--;
361                                 if (pendingReads == 0)
362                                         pending.Set ();
363                         }
364
365                         if (totalRead >= contentLength && !nextReadCalled)
366                                 ReadAll ();
367
368                         int nb = result.NBytes;
369                         return (nb >= 0) ? nb : 0;
370                 }
371                 
372                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
373                                                         AsyncCallback cb, object state)
374                 {
375                         if (isRead)
376                                 throw new NotSupportedException ("this stream does not allow writing");
377
378                         if (buffer == null)
379                                 throw new ArgumentNullException ("buffer");
380
381                         int length = buffer.Length;
382                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
383                                 throw new ArgumentOutOfRangeException ();
384
385                         if (sendChunked) {
386                                 lock (locker) {
387                                         pendingWrites++;
388                                         pending.Reset ();
389                                 }
390                         }
391
392                         WebAsyncResult result = new WebAsyncResult (cb, state);
393                         if (allowBuffering) {
394                                 if (max_buffer_size >= 0) {
395                                         long avail = max_buffer_size - writeBuffer.Length;
396                                         if (size > avail) {
397                                                 if (requestWritten)
398                                                         throw new ProtocolViolationException (
399                                                         "The number of bytes to be written is greater than " +
400                                                         "the specified ContentLength.");
401                                         }
402                                 }
403                                 writeBuffer.Write (buffer, offset, size);
404                                 if (!sendChunked) {
405                                         result.SetCompleted (true, 0);
406                                         result.DoCallback ();
407                                         return result;
408                                 }
409                         }
410
411                         AsyncCallback callback = null;
412                         if (cb != null)
413                                 callback = new AsyncCallback (WriteCallbackWrapper);
414
415                         if (sendChunked) {
416                                 WriteRequest ();
417
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);
425
426                                 buffer = newBuffer;
427                                 offset = 0;
428                                 size = chunkSize;
429                         }
430
431                         result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
432                         return result;
433                 }
434
435                 public override void EndWrite (IAsyncResult r)
436                 {
437                         if (r == null)
438                                 throw new ArgumentNullException ("r");
439
440                         WebAsyncResult result = r as WebAsyncResult;
441                         if (result == null)
442                                 throw new ArgumentException ("Invalid IAsyncResult");
443
444                         if (result.EndCalled)
445                                 return;
446
447                         result.EndCalled = true;
448
449                         if (allowBuffering && !sendChunked)
450                                 return;
451
452                         if (result.GotException)
453                                 throw result.Exception;
454
455                         try { 
456                                 cnc.EndWrite (result.InnerAsyncResult);
457                                 result.SetCompleted (false, 0);
458                         } catch (Exception e) {
459                                 result.SetCompleted (false, e);
460                         }
461
462                         if (sendChunked) {
463                                 lock (locker) {
464                                         pendingWrites--;
465                                         if (pendingWrites == 0)
466                                                 pending.Set ();
467                                 }
468                         }
469                 }
470                 
471                 public override void Write (byte [] buffer, int offset, int size)
472                 {
473                         if (isRead)
474                                 throw new NotSupportedException ("This stream does not allow writing");
475
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;
480                                 cnc.Close (true);
481                                 throw new IOException ("Write timed out.");
482                         }
483
484                         EndWrite (res);
485                 }
486
487                 public override void Flush ()
488                 {
489                 }
490
491                 internal void SetHeaders (byte [] buffer, int offset, int size)
492                 {
493                         if (headersSent)
494                                 return;
495
496                         if (!allowBuffering || sendChunked) {
497                                 headersSent = true;
498                                 if (!cnc.Connected)
499                                         throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
500
501                                 
502                                 if (!cnc.Write (buffer, offset, size))
503                                         throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
504
505                                 if (!initRead) {
506                                         initRead = true;
507                                         WebConnection.InitRead (cnc);
508                                 }
509                         } else {
510                                 headers = new byte [size];
511                                 Buffer.BlockCopy (buffer, offset, headers, 0, size);
512                         }
513                 }
514
515                 internal bool RequestWritten {
516                         get { return requestWritten; }
517                 }
518
519                 internal void WriteRequest ()
520                 {
521                         if (requestWritten)
522                                 return;
523
524                         if (sendChunked) {
525                                 request.SendRequestHeaders ();
526                                 requestWritten = true;
527                                 return;
528                         }
529
530                         if (!allowBuffering || writeBuffer == null)
531                                 return;
532
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);
538                         }
539
540                         request.InternalContentLength = length;
541                         request.SendRequestHeaders ();
542                         requestWritten = true;
543                         if (!cnc.Write (headers, 0, headers.Length))
544                                 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
545
546                         headersSent = true;
547                         if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
548                                 return;
549
550                         IAsyncResult result = null;
551                         if (length > 0)
552                                 result = cnc.BeginWrite (bytes, 0, length, null, null);
553
554                         if (!initRead) {
555                                 initRead = true;
556                                 WebConnection.InitRead (cnc);
557                         }
558
559                         if (length > 0) 
560                                 complete_request_written = cnc.EndWrite (result);
561                         else
562                                 complete_request_written = true;
563                 }
564
565                 internal void InternalClose ()
566                 {
567                         disposed = true;
568                 }
569
570                 internal void ForceCloseConnection ()
571                 {
572                         if (!disposed) {
573                                 disposed = true;
574                                 cnc.Close (true);
575                         }
576                 }
577
578                 public override void Close ()
579                 {
580                         if (sendChunked) {
581                                 pending.WaitOne ();
582                                 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
583                                 cnc.Write (chunk, 0, chunk.Length);
584                                 return;
585                         }
586
587                         if (isRead) {
588                                 if (!nextReadCalled) {
589                                         CheckComplete ();
590                                         // If we have not read all the contents
591                                         if (!nextReadCalled) {
592                                                 nextReadCalled = true;
593                                                 cnc.Close (true);
594                                         }
595                                 }
596                                 return;
597                         } else if (!allowBuffering) {
598                                 complete_request_written = true;
599                                 if (!initRead) {
600                                         initRead = true;
601                                         WebConnection.InitRead (cnc);
602                                 }
603                                 return;
604                         }
605
606                         if (disposed)
607                                 return;
608
609                         long length = request.ContentLength;
610                         if (length != -1 && length > writeBuffer.Length)
611                                 throw new IOException ("Cannot close the stream until all bytes are written");
612
613                         WriteRequest ();
614                         disposed = true;
615                 }
616
617                 public override long Seek (long a, SeekOrigin b)
618                 {
619                         throw new NotSupportedException ();
620                 }
621                 
622                 public override void SetLength (long a)
623                 {
624                         throw new NotSupportedException ();
625                 }
626                 
627                 public override bool CanSeek {
628                         get { return false; }
629                 }
630
631                 public override bool CanRead {
632                         get { return isRead; }
633                 }
634
635                 public override bool CanWrite {
636                         get { return !isRead; }
637                 }
638
639                 public override long Length {
640                         get { throw new NotSupportedException (); }
641                 }
642
643                 public override long Position {
644                         get { throw new NotSupportedException (); }
645                         set { throw new NotSupportedException (); }
646                 }
647         }
648 }
649