2003-07-01 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System / System.Net / WebConnection.cs
1 //
2 // System.Net.WebConnection
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
8 //
9
10 using System.Collections;
11 using System.Net.Sockets;
12 using System.Text;
13 using System.Threading;
14
15 namespace System.Net
16 {
17         enum ReadState
18         {
19                 None,
20                 Status,
21                 Headers,
22                 Content
23         }
24         
25         class WebConnection
26         {
27                 ServicePoint sPoint;
28                 NetworkStream nstream;
29                 Socket socket;
30                 WebExceptionStatus status;
31                 WebConnectionGroup group;
32                 bool busy;
33                 ArrayList queue;
34                 WaitOrTimerCallback initConn;
35                 internal ManualResetEvent dataAvailable;
36                 bool keepAlive;
37                 bool aborted;
38                 byte [] buffer;
39                 internal static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
40                 EventHandler abortHandler;
41                 ReadState readState;
42                 internal WebConnectionData Data;
43                 WebConnectionStream prevStream;
44                 bool chunkedRead;
45                 ChunkStream chunkStream;
46                 AutoResetEvent waitForContinue;
47                 bool waitingForContinue;
48                 
49                 public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
50                 {
51                         this.group = group;
52                         this.sPoint = sPoint;
53                         queue = new ArrayList (1);
54                         dataAvailable = new ManualResetEvent (true);
55                         buffer = new byte [4096];
56                         readState = ReadState.None;
57                         Data = new WebConnectionData ();
58                         initConn = new WaitOrTimerCallback (InitConnection);
59                         abortHandler = new EventHandler (Abort);
60                 }
61
62                 public void Connect ()
63                 {
64                         if (socket != null && socket.Connected && status == WebExceptionStatus.Success)
65                                 return;
66
67                         lock (this) {
68                                 if (socket != null && socket.Connected && status == WebExceptionStatus.Success)
69                                         return;
70
71                                 
72                                 if (socket == null)
73                                         socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
74
75                                 status = sPoint.Connect (socket);
76                                 chunkStream = null;
77                         }
78                 }
79
80                 bool CreateStream (HttpWebRequest request)
81                 {
82                         //TODO: create stream for https
83                         try {
84                                 nstream = new NetworkStream (socket, false);
85                         } catch (Exception e) {
86                                 status = WebExceptionStatus.ConnectFailure;
87                                 return false;
88                         }
89
90                         return true;
91                 }
92                 
93                 void HandleError (WebExceptionStatus st, Exception e)
94                 {
95                         status = st;
96                         Close ();
97                         if (e == null) { // At least we now where it comes from
98                                 try {
99                                         throw new Exception ();
100                                 } catch (Exception e2) {
101                                         e = e2;
102                                 }
103                         }
104
105                         if (Data != null && Data.request != null)
106                                 Data.request.SetResponseError (st, e);
107                 }
108                 
109                 internal bool WaitForContinue (byte [] headers, int offset, int size)
110                 {
111                         Data.StatusCode = 0;
112                         waitingForContinue = sPoint.SendContinue;
113                         if (waitingForContinue && waitForContinue == null)
114                                 waitForContinue = new AutoResetEvent (false);
115
116                         Write (headers, offset, size);
117                         if (!waitingForContinue)
118                                 return false;
119
120                         bool result = waitForContinue.WaitOne (2000, false);
121                         waitingForContinue = false;
122                         if (result) {
123                                 sPoint.SendContinue = true;
124                                 if (Data.request.ExpectContinue)
125                                         Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
126                         } else {
127                                 sPoint.SendContinue = false;
128                         }
129
130                         return result;
131                 }
132                 
133                 static void ReadDone (IAsyncResult result)
134                 {
135                         WebConnection cnc = (WebConnection) result.AsyncState;
136                         WebConnectionData data = cnc.Data;
137                         NetworkStream ns = cnc.nstream;
138                         if (ns == null)
139                                 return;
140
141                         int nread = -1;
142                         cnc.dataAvailable.Reset ();
143                         try {
144                                 nread = ns.EndRead (result);
145                         } catch (Exception e) {
146                                 cnc.status = WebExceptionStatus.ReceiveFailure;
147                                 cnc.HandleError (cnc.status, e);
148                                 cnc.dataAvailable.Set ();
149                                 return;
150                         }
151
152                         if (nread == 0) {
153                                 Console.WriteLine ("nread == 0: may be the connection was closed?");
154                                 cnc.dataAvailable.Set ();
155                                 return;
156                         }
157
158                         if (nread < 0) {
159                                 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
160                                 cnc.dataAvailable.Set ();
161                                 return;
162                         }
163
164                         //Console.WriteLine (System.Text.Encoding.Default.GetString (cnc.buffer, 0, nread));
165                         int pos = -1;
166                         if (cnc.readState == ReadState.None) { 
167                                 Exception exc = null;
168                                 try {
169                                         pos = cnc.GetResponse (cnc.buffer, nread);
170                                         if (data.StatusCode == 100) {
171                                                 cnc.readState = ReadState.None;
172                                                 InitRead (cnc);
173                                                 cnc.sPoint.SendContinue = true;
174                                                 if (cnc.waitingForContinue) {
175                                                         cnc.waitForContinue.Set ();
176                                                 } else if (data.request.ExpectContinue) { // We get a 100 after waiting for it.
177                                                         data.request.DoContinueDelegate (data.StatusCode, data.Headers);
178                                                 }
179
180                                                 return;
181                                         }
182                                 } catch (Exception e) {
183                                         exc = e;
184                                 }
185
186                                 if (pos == -1 || exc != null) {
187                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc);
188                                         cnc.dataAvailable.Set ();
189                                         return;
190                                 }
191                         }
192
193                         if (cnc.readState != ReadState.Content) {
194                                 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
195                                 cnc.dataAvailable.Set ();
196                                 return;
197                         }
198
199                         WebConnectionStream stream = new WebConnectionStream (cnc);
200
201                         string contentType = data.Headers ["Transfer-Encoding"];
202                         cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
203                         if (!cnc.chunkedRead) {
204                                 stream.ReadBuffer = cnc.buffer;
205                                 stream.ReadBufferOffset = pos;
206                                 stream.ReadBufferSize = nread;
207                         } else if (cnc.chunkStream == null) {
208                                 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
209                         } else {
210                                 cnc.chunkStream.ResetBuffer ();
211                                 cnc.chunkStream.Write (cnc.buffer, pos, nread);
212                         }
213
214                         cnc.prevStream = stream;
215                         data.stream = stream;
216                         data.request.SetResponseData (data);
217                         stream.CheckComplete ();
218                 }
219                 
220                 static void InitRead (object state)
221                 {
222                         WebConnection cnc = (WebConnection) state;
223                         NetworkStream ns = cnc.nstream;
224                         try {
225                                 ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
226                         } catch (Exception e) {
227                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
228                                 cnc.dataAvailable.Set ();
229                         }
230                 }
231                 
232                 int GetResponse (byte [] buffer, int max)
233                 {
234                         int pos = 0;
235                         string line = null;
236                         bool lineok = false;
237                         
238                         if (readState == ReadState.None) {
239                                 lineok = ReadLine (buffer, ref pos, max, ref line);
240                                 if (!lineok)
241                                         return -1;
242
243                                 readState = ReadState.Status;
244
245                                 string [] parts = line.Split (' ');
246                                 if (parts.Length < 3)
247                                         return -1;
248
249                                 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
250                                         Data.Version = HttpVersion.Version11;
251                                 } else {
252                                         Data.Version = HttpVersion.Version10;
253                                 }
254
255                                 Data.StatusCode = (int) UInt32.Parse (parts [1]);
256                                 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
257                                 if (pos >= max)
258                                         return pos;
259                         }
260
261                         if (readState == ReadState.Status) {
262                                 readState = ReadState.Headers;
263                                 Data.Headers = new WebHeaderCollection ();
264                                 ArrayList headers = new ArrayList ();
265                                 bool finished = false;
266                                 while (!finished) {
267                                         if (ReadLine (buffer, ref pos, max, ref line) == false)
268                                                 break;
269                                         
270                                         if (line == null) {
271                                                 // Empty line: end of headers
272                                                 finished = true;
273                                                 continue;
274                                         }
275                                         
276                                         if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
277                                                 int count = headers.Count - 1;
278                                                 if (count < 0)
279                                                         break;
280
281                                                 string prev = (string) headers [count] + line;
282                                                 headers [count] = prev;
283                                         } else {
284                                                 headers.Add (line);
285                                         }
286                                 }
287
288                                 if (!finished) {
289                                         // handle the error...
290                                 } else {
291                                         foreach (string s in headers)
292                                                 Data.Headers.Add (s);
293
294                                         readState = ReadState.Content;
295                                         return pos;
296                                 }
297                         }
298
299                         return -1;
300                 }
301                 
302                 void InitConnection (object state, bool notUsed)
303                 {
304                         HttpWebRequest request = (HttpWebRequest) state;
305                         if (aborted) {
306                                 status = WebExceptionStatus.RequestCanceled;
307                                 request.SetWriteStreamError (status);
308                                 return;
309                         }
310
311                         Connect ();
312                         if (status != WebExceptionStatus.Success) {
313                                 request.SetWriteStreamError (status);
314                                 Close ();
315                                 return;
316                         }
317                         
318                         if (!CreateStream (request)) {
319                                 request.SetWriteStreamError (status);
320                                 Close ();
321                                 return;
322                         }
323
324                         readState = ReadState.None;
325                         request.SetWriteStream (new WebConnectionStream (this, request));
326                         InitRead (this);
327                 }
328                 
329                 void BeginRequest (HttpWebRequest request)
330                 {
331                         lock (this) {
332                                 keepAlive = request.KeepAlive;
333                                 Data.Init ();
334                                 Data.request = request;
335                         }
336
337                         ThreadPool.RegisterWaitForSingleObject (dataAvailable, initConn, request, -1, true);
338                 }
339
340                 internal EventHandler SendRequest (HttpWebRequest request)
341                 {
342                         Monitor.Enter (this);
343
344                         if (prevStream != null && socket != null && socket.Connected) {
345                                 prevStream.ReadAll ();
346                                 prevStream = null;
347                         }
348
349                         if (!busy) {
350                                 busy = true;
351                                 Monitor.Exit (this);
352                                 BeginRequest (request);
353                         } else {
354                                 queue.Add (request);
355                                 Monitor.Exit (this);
356                         }
357
358                         return abortHandler;
359                 }
360                 
361                 internal void NextRead ()
362                 {
363                         Monitor.Enter (this);
364                         string cncHeader = (Data.Headers != null) ? Data.Headers ["Connection"] : null;
365                         // Bug in xsp...? It does not send Connection: close. Well. it's 1.0
366                         if (Data.Version == HttpVersion.Version10 || (socket != null && !socket.Connected) || (!keepAlive ||
367                             (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
368                                 Close ();
369                         }
370
371                         busy = false;
372                         dataAvailable.Set ();
373
374                         if (queue.Count > 0) {
375                                 HttpWebRequest request = (HttpWebRequest) queue [0];
376                                 queue.RemoveAt (0);
377                                 Monitor.Exit (this);
378                                 SendRequest (request);
379                         } else {
380                                 Monitor.Exit (this);
381                         }
382                 }
383                 
384                 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
385                 {
386                         bool foundCR = false;
387                         StringBuilder text = new StringBuilder ();
388
389                         int c = 0;
390                         while (start < max) {
391                                 c = (int) buffer [start++];
392
393                                 if (c == '\n') {                        // newline
394                                         if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
395                                                 text.Length--;
396
397                                         foundCR = false;
398                                         break;
399                                 } else if (foundCR) {
400                                         text.Length--;
401                                         break;
402                                 }
403
404                                 if (c == '\r')
405                                         foundCR = true;
406                                         
407
408                                 text.Append ((char) c);
409                         }
410
411                         if (c != '\n' && c != '\r')
412                                 return false;
413
414                         if (text.Length == 0) {
415                                 output = null;
416                                 return (c == '\n' || c == '\r');
417                         }
418
419                         if (foundCR)
420                                 text.Length--;
421
422                         output = text.ToString ();
423                         return true;
424                 }
425
426                 internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
427                 {
428                         if (nstream == null)
429                                 return null;
430
431                         IAsyncResult result = null;
432                         if (!chunkedRead || chunkStream.WantMore) {
433                                 try {
434                                         result = nstream.BeginRead (buffer, offset, size, cb, state);
435                                 } catch (Exception e) {
436                                         status = WebExceptionStatus.ReceiveFailure;
437                                         throw;
438                                 }
439                         }
440
441                         if (chunkedRead) {
442                                 WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
443                                 wr.InnerAsyncResult = result;
444                                 return wr;
445                         }
446
447                         return result;
448                 }
449                 
450                 internal int EndRead (IAsyncResult result)
451                 {
452                         if (nstream == null)
453                                 return 0;
454
455                         if (chunkedRead) {
456                                 WebAsyncResult wr = (WebAsyncResult) result;
457                                 int nbytes = 0;
458                                 if (wr.InnerAsyncResult != null)
459                                         nbytes = nstream.EndRead (wr.InnerAsyncResult);
460
461                                 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
462                                 return nbytes;
463                         }
464
465                         return nstream.EndRead (result);
466                 }
467
468                 internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
469                 {
470                         IAsyncResult result = null;
471                         if (nstream == null)
472                                 return null;
473
474                         try {
475                                 result = nstream.BeginWrite (buffer, offset, size, cb, state);
476                         } catch (Exception e) {
477                                 status = WebExceptionStatus.SendFailure;
478                                 throw;
479                         }
480
481                         return result;
482                 }
483
484                 internal void EndWrite (IAsyncResult result)
485                 {
486                         if (nstream != null)
487                                 nstream.EndWrite (result);
488                 }
489
490                 internal int Read (byte [] buffer, int offset, int size)
491                 {
492                         if (nstream == null)
493                                 return 0;
494
495                         int result = 0;
496                         try {
497                                 if (!chunkedRead || chunkStream.WantMore)
498                                         result = nstream.Read (buffer, offset, size);
499
500                                 if (chunkedRead)
501                                         chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
502                         } catch (Exception e) {
503                                 status = WebExceptionStatus.ReceiveFailure;
504                                 HandleError (status, e);
505                         }
506
507                         return result;
508                 }
509
510                 internal void Write (byte [] buffer, int offset, int size)
511                 {
512                         if (nstream == null)
513                                 return;
514
515                         try {
516                                 nstream.Write (buffer, offset, size);
517                         } catch (Exception e) {
518                                 status = WebExceptionStatus.SendFailure;
519                                 HandleError (status, e);
520                         }
521                 }
522
523                 void Close ()
524                 {
525                         if (nstream != null) {
526                                 try {
527                                         nstream.Close ();
528                                 } catch {}
529                                 nstream = null;
530                         }
531
532                         if (socket != null) {
533                                 try {
534                                         socket.Close ();
535                                 } catch {}
536                                 socket = null;
537                         }
538                 }
539
540                 void Abort (object sender, EventArgs args)
541                 {
542                         HandleError (WebExceptionStatus.RequestCanceled, null);
543                 }
544
545                 ~WebConnection ()
546                 {
547                         Close ();
548                 }
549         }
550 }
551