2005-04-16 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                 object locker = new object ();
61                 bool initRead;
62
63                 public WebConnectionStream (WebConnection cnc)
64                 {
65                         isRead = true;
66                         pending = new ManualResetEvent (true);
67                         this.request = cnc.Data.request;
68                         this.cnc = cnc;
69                         string clength = cnc.Data.Headers ["Content-Length"];
70                         if (clength != null && clength != "") {
71                                 try {
72                                         contentLength = Int32.Parse (clength);
73                                 } catch {
74                                         contentLength = Int32.MaxValue;
75                                 }
76                         } else {
77                                 contentLength = Int32.MaxValue;
78                         }
79                 }
80
81                 public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
82                 {
83                         isRead = false;
84                         this.cnc = cnc;
85                         this.request = request;
86                         allowBuffering = request.InternalAllowBuffering;
87                         sendChunked = request.SendChunked;
88                         if (allowBuffering)
89                                 writeBuffer = new MemoryStream ();
90
91                         if (sendChunked)
92                                 pending = new ManualResetEvent (true);
93                 }
94
95                 internal bool SendChunked {
96                         set { sendChunked = value; }
97                 }
98
99                 internal byte [] ReadBuffer {
100                         set { readBuffer = value; }
101                 }
102
103                 internal int ReadBufferOffset {
104                         set { readBufferOffset = value;}
105                 }
106                 
107                 internal int ReadBufferSize {
108                         set { readBufferSize = value; }
109                 }
110                 
111                 internal byte[] WriteBuffer {
112                         get { return writeBuffer.GetBuffer (); }
113                 }
114
115                 internal int WriteBufferLength {
116                         get { return (int) writeBuffer.Length; }
117                 }
118
119                 internal void ForceCompletion ()
120                 {
121                         nextReadCalled = true;
122                         cnc.NextRead ();
123                 }
124                 
125                 internal void CheckComplete ()
126                 {
127                         bool nrc = nextReadCalled;
128                         if (!nrc && readBufferSize - readBufferOffset == contentLength) {
129                                 nextReadCalled = true;
130                                 cnc.NextRead ();
131                         }
132                 }
133
134                 internal void ReadAll ()
135                 {
136                         if (!isRead || totalRead >= contentLength || nextReadCalled) {
137                                 if (!nextReadCalled) {
138                                         nextReadCalled = true;
139                                         cnc.NextRead ();
140                                 }
141                                 return;
142                         }
143
144                         pending.WaitOne ();
145                         lock (locker) {
146                                 if (totalRead >= contentLength)
147                                         return;
148                                 
149                                 byte [] b = null;
150                                 int diff = readBufferSize - readBufferOffset;
151                                 int new_size;
152
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)
159                                                         buffer = readBuffer;
160                                         }
161
162                                         if (buffer == null)
163                                                 buffer = new byte [8192];
164
165                                         int read;
166                                         while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
167                                                 ms.Write (buffer, 0, read);
168
169                                         b = ms.GetBuffer ();
170                                         new_size = (int) ms.Length;
171                                         contentLength = new_size;
172                                 } else {
173                                         new_size = contentLength - totalRead;
174                                         b = new byte [new_size];
175                                         if (readBuffer != null && diff > 0) {
176                                                 if (diff > new_size)
177                                                         diff = new_size;
178
179                                                 Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
180                                         }
181                                         
182                                         int remaining = new_size - diff;
183                                         int r = -1;
184                                         while (remaining > 0 && r != 0) {
185                                                 r = cnc.Read (b, diff, remaining);
186                                                 remaining -= r;
187                                                 diff += r;
188                                         }
189                                 }
190
191                                 readBuffer = b;
192                                 readBufferOffset = 0;
193                                 readBufferSize = new_size;
194                                 totalRead = 0;
195                                 nextReadCalled = true;
196                         }
197
198                         cnc.NextRead ();
199                 }
200
201                 void WriteCallbackWrapper (IAsyncResult r)
202                 {
203                         WebAsyncResult result;
204                         if (r.AsyncState != null) {
205                                 result = (WebAsyncResult) r.AsyncState;
206                                 result.InnerAsyncResult = r;
207                                 result.DoCallback ();
208                         } else {
209                                 EndWrite (r);
210                         }
211                 }
212
213                 void ReadCallbackWrapper (IAsyncResult r)
214                 {
215                         WebAsyncResult result;
216                         if (r.AsyncState != null) {
217                                 result = (WebAsyncResult) r.AsyncState;
218                                 result.InnerAsyncResult = r;
219                                 result.DoCallback ();
220                         } else {
221                                 EndRead (r);
222                         }
223                 }
224
225                 public override int Read (byte [] buffer, int offset, int size)
226                 {
227                         if (!isRead)
228                                 throw new NotSupportedException ("this stream does not allow reading");
229
230                         if (totalRead >= contentLength)
231                                 return 0;
232
233                         AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
234                         WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
235                         if (!res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
236                                 cnc.Close (true);
237                                 throw new IOException ("Read timed out.");
238                         }
239
240                         return EndRead (res);
241                 }
242
243                 public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
244                                                         AsyncCallback cb, object state)
245                 {
246                         if (!isRead)
247                                 throw new NotSupportedException ("this stream does not allow reading");
248
249                         if (buffer == null)
250                                 throw new ArgumentNullException ("buffer");
251
252                         int length = buffer.Length;
253                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
254                                 throw new ArgumentOutOfRangeException ();
255
256                         lock (locker) {
257                                 pendingReads++;
258                                 pending.Reset ();
259                         }
260
261                         WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
262                         if (totalRead >= contentLength) {
263                                 result.SetCompleted (true, -1);
264                                 result.DoCallback ();
265                                 return result;
266                         }
267                         
268                         int remaining = readBufferSize - readBufferOffset;
269                         if (remaining > 0) {
270                                 int copy = (remaining > size) ? size : remaining;
271                                 Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
272                                 readBufferOffset += copy;
273                                 offset += copy;
274                                 size -= copy;
275                                 totalRead += copy;
276                                 if (size == 0 || totalRead >= contentLength) {
277                                         result.SetCompleted (true, copy);
278                                         result.DoCallback ();
279                                         return result;
280                                 }
281                                 result.NBytes = copy;
282                         }
283
284                         if (cb != null)
285                                 cb = new AsyncCallback (ReadCallbackWrapper);
286
287                         if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
288                                 size = contentLength - totalRead;
289
290                         result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
291                         return result;
292                 }
293
294                 public override int EndRead (IAsyncResult r)
295                 {
296                         WebAsyncResult result = (WebAsyncResult) r;
297                         if (result.EndCalled) {
298                                 int xx = result.NBytes;
299                                 return (xx >= 0) ? xx : 0;
300                         }
301
302                         result.EndCalled = true;
303
304                         if (!result.IsCompleted) {
305                                 int nbytes = cnc.EndRead (result);
306                                 bool finished = (nbytes == -1);
307                                 if (finished && result.NBytes > 0)
308                                         nbytes = 0;
309
310                                 totalRead += nbytes;
311                                 result.SetCompleted (false, nbytes + result.NBytes);
312                                 result.DoCallback ();
313                                 if (finished || nbytes == 0)
314                                         contentLength = totalRead;
315                         }
316
317                         lock (locker) {
318                                 pendingReads--;
319                                 if (pendingReads == 0)
320                                         pending.Set ();
321                         }
322
323                         if (totalRead >= contentLength && !nextReadCalled)
324                                 ReadAll ();
325
326                         int nb = result.NBytes;
327                         return (nb >= 0) ? nb : 0;
328                 }
329                 
330                 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
331                                                         AsyncCallback cb, object state)
332                 {
333                         if (isRead)
334                                 throw new NotSupportedException ("this stream does not allow writing");
335
336                         if (buffer == null)
337                                 throw new ArgumentNullException ("buffer");
338
339                         int length = buffer.Length;
340                         if (size < 0 || offset < 0 || length < offset || length - offset < size)
341                                 throw new ArgumentOutOfRangeException ();
342
343                         if (sendChunked) {
344                                 lock (locker) {
345                                         pendingWrites++;
346                                         pending.Reset ();
347                                 }
348                         }
349
350                         WebAsyncResult result = new WebAsyncResult (cb, state);
351                         if (allowBuffering) {
352                                 writeBuffer.Write (buffer, offset, size);
353                                 if (!sendChunked) {
354                                         result.SetCompleted (true, 0);
355                                         result.DoCallback ();
356                                         return result;
357                                 }
358                         }
359
360                         AsyncCallback callback = null;
361                         if (cb != null)
362                                 callback = new AsyncCallback (WriteCallbackWrapper);
363
364                         if (sendChunked) {
365                                 WriteRequest ();
366
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);
374
375                                 buffer = newBuffer;
376                                 offset = 0;
377                                 size = chunkSize;
378                         }
379
380                         result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
381                         return result;
382                 }
383
384                 public override void EndWrite (IAsyncResult r)
385                 {
386                         if (r == null)
387                                 throw new ArgumentNullException ("r");
388
389                         WebAsyncResult result = r as WebAsyncResult;
390                         if (result == null)
391                                 throw new ArgumentException ("Invalid IAsyncResult");
392
393                         if (result.EndCalled)
394                                 return;
395
396                         result.EndCalled = true;
397
398                         if (allowBuffering && !sendChunked)
399                                 return;
400
401                         if (result.GotException)
402                                 throw result.Exception;
403
404                         cnc.EndWrite (result.InnerAsyncResult);
405                         result.SetCompleted (false, 0);
406                         if (sendChunked) {
407                                 lock (locker) {
408                                         pendingWrites--;
409                                         if (pendingWrites == 0)
410                                                 pending.Set ();
411                                 }
412                         }
413                 }
414                 
415                 public override void Write (byte [] buffer, int offset, int size)
416                 {
417                         if (isRead)
418                                 throw new NotSupportedException ("This stream does not allow writing");
419
420                         AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
421                         WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
422                         if (!res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
423                                 cnc.Close (true);
424                                 throw new IOException ("Write timed out.");
425                         }
426
427                         EndWrite (res);
428                 }
429
430                 public override void Flush ()
431                 {
432                 }
433
434                 internal void SetHeaders (byte [] buffer, int offset, int size)
435                 {
436                         if (headersSent)
437                                 return;
438
439                         if (!allowBuffering || sendChunked) {
440                                 headersSent = true;
441                                 if (!cnc.Connected)
442                                         throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
443
444                                 cnc.Write (buffer, offset, size);
445                                 if (!initRead) {
446                                         initRead = true;
447                                         WebConnection.InitRead (cnc);
448                                 }
449                         } else {
450                                 headers = new byte [size];
451                                 Buffer.BlockCopy (buffer, offset, headers, 0, size);
452                         }
453                 }
454
455                 internal bool RequestWritten {
456                         get { return requestWritten; }
457                 }
458
459                 internal void WriteRequest ()
460                 {
461                         if (requestWritten)
462                                 return;
463
464                         if (sendChunked) {
465                                 request.SendRequestHeaders ();
466                                 requestWritten = true;
467                                 return;
468                         }
469
470                         if (!allowBuffering || writeBuffer == null)
471                                 return;
472
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);
478                         }
479
480                         request.InternalContentLength = length;
481                         request.SendRequestHeaders ();
482                         requestWritten = true;
483                         cnc.Write (headers, 0, headers.Length);
484                         if (!cnc.Connected)
485                                 throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
486
487                         headersSent = true;
488                         if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
489                                 return;
490
491                         cnc.Write (bytes, 0, length);
492                 }
493
494                 internal void InternalClose ()
495                 {
496                         disposed = true;
497                 }
498                 
499                 public override void Close ()
500                 {
501                         if (sendChunked) {
502                                 pending.WaitOne ();
503                                 byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
504                                 cnc.Write (chunk, 0, chunk.Length);
505                                 return;
506                         }
507
508                         if (isRead) {
509                                 if (!nextReadCalled) {
510                                         CheckComplete ();
511                                         // If we have not read all the contents
512                                         if (!nextReadCalled)
513                                                 cnc.Close (true);
514                                 }
515                                 return;
516                         } else if (!allowBuffering) {
517                                 if (!initRead) {
518                                         initRead = true;
519                                         WebConnection.InitRead (cnc);
520                                 }
521                                 return;
522                         }
523
524                         if (disposed)
525                                 return;
526
527                         disposed = true;
528
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");
532
533                         WriteRequest ();
534                         if (!initRead) {
535                                 initRead = true;
536                                 WebConnection.InitRead (cnc);
537                         }
538                 }
539
540                 public override long Seek (long a, SeekOrigin b)
541                 {
542                         throw new NotSupportedException ();
543                 }
544                 
545                 public override void SetLength (long a)
546                 {
547                         throw new NotSupportedException ();
548                 }
549                 
550                 public override bool CanSeek {
551                         get { return false; }
552                 }
553
554                 public override bool CanRead {
555                         get { return isRead; }
556                 }
557
558                 public override bool CanWrite {
559                         get { return !isRead; }
560                 }
561
562                 public override long Length {
563                         get { throw new NotSupportedException (); }
564                 }
565
566                 public override long Position {
567                         get { throw new NotSupportedException (); }
568                         set { throw new NotSupportedException (); }
569                 }
570         }
571 }
572