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