2003-06-09 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 noe 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                         if (!sPoint.SendContinue)
113                                 return false;
114
115                         if (waitForContinue == null)
116                                 waitForContinue = new AutoResetEvent (false);
117
118                         Write (headers, offset, size);
119                         waitingForContinue = true;
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");
154                                 return;
155                         }
156
157                         if (nread < 0) {
158                                 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
159                                 cnc.dataAvailable.Set ();
160                                 return;
161                         }
162
163                         //Console.WriteLine (System.Text.Encoding.Default.GetString (cnc.buffer, 0, nread));
164                         int pos = -1;
165                         if (cnc.readState == ReadState.None) { 
166                                 Exception exc = null;
167                                 try {
168                                         pos = cnc.GetResponse (cnc.buffer, nread);
169                                         if (data.StatusCode == 100) {
170                                                 cnc.readState = ReadState.None;
171                                                 InitRead (cnc);
172                                                 cnc.sPoint.SendContinue = true;
173                                                 if (cnc.waitingForContinue) {
174                                                         cnc.waitForContinue.Set ();
175                                                 } else if (data.request.ExpectContinue) { // We get a 100 after waiting for it.
176                                                         data.request.DoContinueDelegate (data.StatusCode, data.Headers);
177                                                 }
178
179                                                 return;
180                                         }
181                                 } catch (Exception e) {
182                                         exc = e;
183                                 }
184
185                                 if (pos == -1 || exc != null) {
186                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc);
187                                         cnc.dataAvailable.Set ();
188                                         return;
189                                 }
190                         }
191
192                         if (cnc.readState != ReadState.Content) {
193                                 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
194                                 cnc.dataAvailable.Set ();
195                                 return;
196                         }
197
198                         WebConnectionStream stream = new WebConnectionStream (cnc);
199
200                         string contentType = data.Headers ["Transfer-Encoding"];
201                         cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
202                         if (!cnc.chunkedRead) {
203                                 stream.ReadBuffer = cnc.buffer;
204                                 stream.ReadBufferOffset = pos;
205                                 stream.ReadBufferSize = nread;
206                                 stream.CheckComplete ();
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                 }
218                 
219                 static void InitRead (object state)
220                 {
221                         WebConnection cnc = (WebConnection) state;
222                         NetworkStream ns = cnc.nstream;
223                         try {
224                                 ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
225                         } catch (Exception e) {
226                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
227                                 cnc.dataAvailable.Set ();
228                         }
229                 }
230                 
231                 int GetResponse (byte [] buffer, int max)
232                 {
233                         int pos = 0;
234                         string line = null;
235                         bool lineok = false;
236                         
237                         if (readState == ReadState.None) {
238                                 lineok = ReadLine (buffer, ref pos, max, ref line);
239                                 if (!lineok)
240                                         return -1;
241
242                                 readState = ReadState.Status;
243
244                                 string [] parts = line.Split (' ');
245                                 if (parts.Length < 3)
246                                         return -1;
247
248                                 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
249                                         Data.Version = HttpVersion.Version11;
250                                 } else {
251                                         Data.Version = HttpVersion.Version10;
252                                 }
253
254                                 Data.StatusCode = (int) UInt32.Parse (parts [1]);
255                                 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
256                                 if (pos >= max)
257                                         return pos;
258                         }
259
260                         if (readState == ReadState.Status) {
261                                 readState = ReadState.Headers;
262                                 Data.Headers = new WebHeaderCollection ();
263                                 ArrayList headers = new ArrayList ();
264                                 bool finished = false;
265                                 while (!finished) {
266                                         if (ReadLine (buffer, ref pos, max, ref line) == false)
267                                                 break;
268                                         
269                                         if (line == null) {
270                                                 // Empty line: end of headers
271                                                 finished = true;
272                                                 continue;
273                                         }
274                                         
275                                         if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
276                                                 int count = headers.Count - 1;
277                                                 if (count < 0)
278                                                         break;
279
280                                                 string prev = (string) headers [count] + line;
281                                                 headers [count] = prev;
282                                         } else {
283                                                 headers.Add (line);
284                                         }
285                                 }
286
287                                 if (!finished) {
288                                         // handle the error...
289                                 } else {
290                                         foreach (string s in headers)
291                                                 Data.Headers.Add (s);
292
293                                         readState = ReadState.Content;
294                                         return pos;
295                                 }
296                         }
297
298                         return -1;
299                 }
300                 
301                 void InitConnection (object state, bool notUsed)
302                 {
303                         HttpWebRequest request = (HttpWebRequest) state;
304                         if (aborted) {
305                                 status = WebExceptionStatus.RequestCanceled;
306                                 request.SetWriteStreamError (status);
307                                 return;
308                         }
309
310                         Connect ();
311                         if (status != WebExceptionStatus.Success) {
312                                 request.SetWriteStreamError (status);
313                                 Close ();
314                                 return;
315                         }
316                         
317                         if (!CreateStream (request)) {
318                                 request.SetWriteStreamError (status);
319                                 Close ();
320                                 return;
321                         }
322
323                         readState = ReadState.None;
324                         request.SetWriteStream (new WebConnectionStream (this, request));
325                         InitRead (this);
326                 }
327                 
328                 void BeginRequest (HttpWebRequest request)
329                 {
330                         lock (this) {
331                                 keepAlive = request.KeepAlive;
332                                 Data.Init ();
333                                 Data.request = request;
334                         }
335
336                         ThreadPool.RegisterWaitForSingleObject (dataAvailable, initConn, request, -1, true);
337                 }
338
339                 internal EventHandler SendRequest (HttpWebRequest request)
340                 {
341                         Monitor.Enter (this);
342
343                         if (prevStream != null && socket != null && socket.Connected) {
344                                 prevStream.ReadAll ();
345                                 prevStream = null;
346                         }
347                                 
348                         if (!busy) {
349                                 busy = true;
350                                 Monitor.Exit (this);
351                                 BeginRequest (request);
352                         } else {
353                                 queue.Add (request);
354                                 Monitor.Exit (this);
355                         }
356
357                         return abortHandler;
358                 }
359                 
360                 internal void NextRead ()
361                 {
362                         Monitor.Enter (this);
363                         string cncHeader = (Data.Headers != null) ? Data.Headers ["Connection"] : null;
364                         // Bug in xsp...? It does not send Connection: close. Well. it's 1.0
365                         if (Data.Version == HttpVersion.Version10 || (socket != null && !socket.Connected) || (!keepAlive ||
366                             (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
367                                 Close ();
368                         }
369
370                         if (queue.Count > 0) {
371                                 HttpWebRequest request = (HttpWebRequest) queue [0];
372                                 queue.RemoveAt (0);
373                                 Monitor.Exit (this);
374                                 SendRequest (request);
375                         } else {
376                                 busy = false;
377                                 Monitor.Exit (this);
378                         }
379                 }
380                 
381                 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
382                 {
383                         bool foundCR = false;
384                         StringBuilder text = new StringBuilder ();
385
386                         int c = 0;
387                         while (start < max) {
388                                 c = (int) buffer [start++];
389
390                                 if (c == '\n') {                        // newline
391                                         if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
392                                                 text.Length--;
393
394                                         foundCR = false;
395                                         break;
396                                 } else if (foundCR) {
397                                         text.Length--;
398                                         break;
399                                 }
400
401                                 if (c == '\r')
402                                         foundCR = true;
403                                         
404
405                                 text.Append ((char) c);
406                         }
407
408                         if (c != '\n' && c != '\r')
409                                 return false;
410
411                         if (text.Length == 0) {
412                                 output = null;
413                                 return (c == '\n' || c == '\r');
414                         }
415
416                         if (foundCR)
417                                 text.Length--;
418
419                         output = text.ToString ();
420                         return true;
421                 }
422
423                 internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
424                 {
425                         if (nstream == null)
426                                 return null;
427
428                         IAsyncResult result = null;
429                         if (!chunkedRead || chunkStream.WantMore) {
430                                 try {
431                                         result = nstream.BeginRead (buffer, offset, size, cb, state);
432                                 } catch (Exception e) {
433                                         status = WebExceptionStatus.ReceiveFailure;
434                                         throw;
435                                 }
436                         }
437
438                         if (chunkedRead) {
439                                 WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
440                                 wr.InnerAsyncResult = result;
441                                 return wr;
442                         }
443
444                         return result;
445                 }
446                 
447                 internal int EndRead (IAsyncResult result)
448                 {
449                         if (nstream == null)
450                                 return 0;
451
452                         if (chunkedRead) {
453                                 WebAsyncResult wr = (WebAsyncResult) result;
454                                 int nbytes = 0;
455                                 if (wr.InnerAsyncResult != null)
456                                         nbytes = nstream.EndRead (wr.InnerAsyncResult);
457
458                                 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
459                                 return nbytes;
460                         }
461
462                         return nstream.EndRead (result);
463                 }
464
465                 internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
466                 {
467                         IAsyncResult result = null;
468                         if (nstream == null)
469                                 return null;
470
471                         try {
472                                 result = nstream.BeginWrite (buffer, offset, size, cb, state);
473                         } catch (Exception e) {
474                                 status = WebExceptionStatus.SendFailure;
475                                 throw;
476                         }
477
478                         return result;
479                 }
480
481                 internal void EndWrite (IAsyncResult result)
482                 {
483                         if (nstream != null)
484                                 nstream.EndWrite (result);
485                 }
486
487                 internal int Read (byte [] buffer, int offset, int size)
488                 {
489                         if (nstream == null)
490                                 return 0;
491
492                         int result = 0;
493                         try {
494                                 if (!chunkedRead || chunkStream.WantMore)
495                                         result = nstream.Read (buffer, offset, size);
496
497                                 if (chunkedRead)
498                                         chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
499                         } catch (Exception e) {
500                                 status = WebExceptionStatus.ReceiveFailure;
501                                 HandleError (status, e);
502                         }
503
504                         return result;
505                 }
506
507                 internal void Write (byte [] buffer, int offset, int size)
508                 {
509                         if (nstream == null)
510                                 return;
511
512                         try {
513                                 nstream.Write (buffer, offset, size);
514                         } catch (Exception e) {
515                                 status = WebExceptionStatus.SendFailure;
516                                 HandleError (status, e);
517                         }
518                 }
519
520                 void Close ()
521                 {
522                         if (nstream != null) {
523                                 try {
524                                         nstream.Close ();
525                                 } catch {}
526                                 nstream = null;
527                         }
528
529                         if (socket != null) {
530                                 try {
531                                         socket.Close ();
532                                 } catch {}
533                                 socket = null;
534                         }
535                 }
536
537                 void Abort (object sender, EventArgs args)
538                 {
539                         HandleError (WebExceptionStatus.RequestCanceled, null);
540                 }
541         }
542 }
543