2003-07-13 Andreas Nahr <ClassDevelopment@A-SoftTech.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                         
225                         try {
226                                 ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
227                         } catch (Exception e) {
228                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
229                                 cnc.dataAvailable.Set ();
230                         }
231                 }
232                 
233                 int GetResponse (byte [] buffer, int max)
234                 {
235                         int pos = 0;
236                         string line = null;
237                         bool lineok = false;
238                         
239                         if (readState == ReadState.None) {
240                                 lineok = ReadLine (buffer, ref pos, max, ref line);
241                                 if (!lineok)
242                                         return -1;
243
244                                 readState = ReadState.Status;
245
246                                 string [] parts = line.Split (' ');
247                                 if (parts.Length < 3)
248                                         return -1;
249
250                                 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
251                                         Data.Version = HttpVersion.Version11;
252                                 } else {
253                                         Data.Version = HttpVersion.Version10;
254                                 }
255
256                                 Data.StatusCode = (int) UInt32.Parse (parts [1]);
257                                 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
258                                 if (pos >= max)
259                                         return pos;
260                         }
261
262                         if (readState == ReadState.Status) {
263                                 readState = ReadState.Headers;
264                                 Data.Headers = new WebHeaderCollection ();
265                                 ArrayList headers = new ArrayList ();
266                                 bool finished = false;
267                                 while (!finished) {
268                                         if (ReadLine (buffer, ref pos, max, ref line) == false)
269                                                 break;
270                                         
271                                         if (line == null) {
272                                                 // Empty line: end of headers
273                                                 finished = true;
274                                                 continue;
275                                         }
276                                         
277                                         if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
278                                                 int count = headers.Count - 1;
279                                                 if (count < 0)
280                                                         break;
281
282                                                 string prev = (string) headers [count] + line;
283                                                 headers [count] = prev;
284                                         } else {
285                                                 headers.Add (line);
286                                         }
287                                 }
288
289                                 if (!finished) {
290                                         // handle the error...
291                                 } else {
292                                         foreach (string s in headers)
293                                                 Data.Headers.Add (s);
294
295                                         readState = ReadState.Content;
296                                         return pos;
297                                 }
298                         }
299
300                         return -1;
301                 }
302                 
303                 void InitConnection (object state, bool notUsed)
304                 {
305                         HttpWebRequest request = (HttpWebRequest) state;
306                         if (aborted) {
307                                 status = WebExceptionStatus.RequestCanceled;
308                                 request.SetWriteStreamError (status);
309                                 return;
310                         }
311
312                         Connect ();
313                         if (status != WebExceptionStatus.Success) {
314                                 request.SetWriteStreamError (status);
315                                 Close ();
316                                 return;
317                         }
318                         
319                         if (!CreateStream (request)) {
320                                 request.SetWriteStreamError (status);
321                                 Close ();
322                                 return;
323                         }
324
325                         readState = ReadState.None;
326                         request.SetWriteStream (new WebConnectionStream (this, request));
327                         InitRead (this);
328                 }
329                 
330                 void BeginRequest (HttpWebRequest request)
331                 {
332                         lock (this) {
333                                 keepAlive = request.KeepAlive;
334                                 Data.Init ();
335                                 Data.request = request;
336                         }
337
338                         ThreadPool.RegisterWaitForSingleObject (dataAvailable, initConn, request, -1, true);
339                 }
340
341                 internal EventHandler SendRequest (HttpWebRequest request)
342                 {
343                         Monitor.Enter (this);
344
345                         if (prevStream != null && socket != null && socket.Connected) {
346                                 prevStream.ReadAll ();
347                                 prevStream = null;
348                         }
349
350                         if (!busy) {
351                                 busy = true;
352                                 Monitor.Exit (this);
353                                 BeginRequest (request);
354                         } else {
355                                 queue.Add (request);
356                                 Monitor.Exit (this);
357                         }
358
359                         return abortHandler;
360                 }
361                 
362                 internal void NextRead ()
363                 {
364                         Monitor.Enter (this);
365                         string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
366                         string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
367                         bool keepAlive = this.keepAlive;
368                         if (cncHeader != null) {
369                                 cncHeader = cncHeader.ToLower ();
370                                 keepAlive = (keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
371                         }
372
373                         if ((socket != null && !socket.Connected) ||
374                            (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
375                                 Close ();
376                         }
377
378                         busy = false;
379                         dataAvailable.Set ();
380
381                         if (queue.Count > 0) {
382                                 HttpWebRequest request = (HttpWebRequest) queue [0];
383                                 queue.RemoveAt (0);
384                                 Monitor.Exit (this);
385                                 SendRequest (request);
386                         } else {
387                                 Monitor.Exit (this);
388                         }
389                 }
390                 
391                 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
392                 {
393                         bool foundCR = false;
394                         StringBuilder text = new StringBuilder ();
395
396                         int c = 0;
397                         while (start < max) {
398                                 c = (int) buffer [start++];
399
400                                 if (c == '\n') {                        // newline
401                                         if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
402                                                 text.Length--;
403
404                                         foundCR = false;
405                                         break;
406                                 } else if (foundCR) {
407                                         text.Length--;
408                                         break;
409                                 }
410
411                                 if (c == '\r')
412                                         foundCR = true;
413                                         
414
415                                 text.Append ((char) c);
416                         }
417
418                         if (c != '\n' && c != '\r')
419                                 return false;
420
421                         if (text.Length == 0) {
422                                 output = null;
423                                 return (c == '\n' || c == '\r');
424                         }
425
426                         if (foundCR)
427                                 text.Length--;
428
429                         output = text.ToString ();
430                         return true;
431                 }
432
433                 internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
434                 {
435                         if (nstream == null)
436                                 return null;
437
438                         IAsyncResult result = null;
439                         if (!chunkedRead || chunkStream.WantMore) {
440                                 try {
441                                         result = nstream.BeginRead (buffer, offset, size, cb, state);
442                                 } catch (Exception e) {
443                                         status = WebExceptionStatus.ReceiveFailure;
444                                         throw;
445                                 }
446                         }
447
448                         if (chunkedRead) {
449                                 WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
450                                 wr.InnerAsyncResult = result;
451                                 return wr;
452                         }
453
454                         return result;
455                 }
456                 
457                 internal int EndRead (IAsyncResult result)
458                 {
459                         if (nstream == null)
460                                 return 0;
461
462                         if (chunkedRead) {
463                                 WebAsyncResult wr = (WebAsyncResult) result;
464                                 int nbytes = 0;
465                                 if (wr.InnerAsyncResult != null)
466                                         nbytes = nstream.EndRead (wr.InnerAsyncResult);
467
468                                 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
469                                 return nbytes;
470                         }
471
472                         return nstream.EndRead (result);
473                 }
474
475                 internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
476                 {
477                         IAsyncResult result = null;
478                         if (nstream == null)
479                                 return null;
480
481                         try {
482                                 result = nstream.BeginWrite (buffer, offset, size, cb, state);
483                         } catch (Exception e) {
484                                 status = WebExceptionStatus.SendFailure;
485                                 throw;
486                         }
487
488                         return result;
489                 }
490
491                 internal void EndWrite (IAsyncResult result)
492                 {
493                         if (nstream != null)
494                                 nstream.EndWrite (result);
495                 }
496
497                 internal int Read (byte [] buffer, int offset, int size)
498                 {
499                         if (nstream == null)
500                                 return 0;
501
502                         int result = 0;
503                         try {
504                                 if (!chunkedRead || chunkStream.WantMore)
505                                         result = nstream.Read (buffer, offset, size);
506
507                                 if (chunkedRead)
508                                         chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
509                         } catch (Exception e) {
510                                 status = WebExceptionStatus.ReceiveFailure;
511                                 HandleError (status, e);
512                         }
513
514                         return result;
515                 }
516
517                 internal void Write (byte [] buffer, int offset, int size)
518                 {
519                         if (nstream == null)
520                                 return;
521
522                         try {
523                                 nstream.Write (buffer, offset, size);
524                         } catch (Exception e) {
525                                 status = WebExceptionStatus.SendFailure;
526                                 HandleError (status, e);
527                         }
528                 }
529
530                 void Close ()
531                 {
532                         lock (this) {
533                                 if (nstream != null) {
534                                         try {
535                                                 nstream.Close ();
536                                         } catch {}
537                                         nstream = null;
538                                 }
539
540                                 if (socket != null) {
541                                         try {
542                                                 socket.Close ();
543                                         } catch {}
544                                         socket = null;
545                                 }
546                         }
547                 }
548
549                 void Abort (object sender, EventArgs args)
550                 {
551                         HandleError (WebExceptionStatus.RequestCanceled, null);
552                 }
553
554                 ~WebConnection ()
555                 {
556                         Close ();
557                 }
558         }
559 }
560