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