[resgen] Implement conditional resources (#if/#ifdef)
[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 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 #if SECURITY_DEP
32
33 #if MONOTOUCH || MONODROID
34 using Mono.Security.Protocol.Tls;
35 #else
36 extern alias MonoSecurity;
37 using MonoSecurity::Mono.Security.Protocol.Tls;
38 #endif
39
40 #endif
41
42 using System.IO;
43 using System.Collections;
44 using System.Net.Sockets;
45 using System.Reflection;
46 using System.Security.Cryptography.X509Certificates;
47 using System.Text;
48 using System.Threading;
49 using System.Diagnostics;
50
51 namespace System.Net
52 {
53         enum ReadState
54         {
55                 None,
56                 Status,
57                 Headers,
58                 Content,
59                 Aborted
60         }
61
62         class WebConnection
63         {
64                 ServicePoint sPoint;
65                 Stream nstream;
66                 internal Socket socket;
67                 object socketLock = new object ();
68                 IWebConnectionState state;
69                 WebExceptionStatus status;
70                 WaitCallback initConn;
71                 bool keepAlive;
72                 byte [] buffer;
73                 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
74                 EventHandler abortHandler;
75                 AbortHelper abortHelper;
76                 internal WebConnectionData Data;
77                 bool chunkedRead;
78                 ChunkStream chunkStream;
79                 Queue queue;
80                 bool reused;
81                 int position;
82                 HttpWebRequest priority_request;                
83                 NetworkCredential ntlm_credentials;
84                 bool ntlm_authenticated;
85                 bool unsafe_sharing;
86
87                 enum NtlmAuthState
88                 {
89                         None,
90                         Challenge,
91                         Response
92                 }
93                 NtlmAuthState connect_ntlm_auth_state;
94                 HttpWebRequest connect_request;
95
96                 bool ssl;
97                 bool certsAvailable;
98                 Exception connect_exception;
99                 static object classLock = new object ();
100                 static Type sslStream;
101 #if !MONOTOUCH && !MONODROID
102                 static PropertyInfo piClient;
103                 static PropertyInfo piServer;
104                 static PropertyInfo piTrustFailure;
105 #endif
106
107 #if MONOTOUCH
108                 [System.Runtime.InteropServices.DllImport ("__Internal")]
109                 static extern void xamarin_start_wwan (string uri);
110 #endif
111
112                 internal ChunkStream ChunkStream {
113                         get { return chunkStream; }
114                 }
115
116                 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
117                 {
118                         this.state = wcs;
119                         this.sPoint = sPoint;
120                         buffer = new byte [4096];
121                         Data = new WebConnectionData ();
122                         initConn = new WaitCallback (state => {
123                                 try {
124                                         InitConnection (state);
125                                 } catch {}
126                                 });
127                         queue = wcs.Group.Queue;
128                         abortHelper = new AbortHelper ();
129                         abortHelper.Connection = this;
130                         abortHandler = new EventHandler (abortHelper.Abort);
131                 }
132
133                 class AbortHelper {
134                         public WebConnection Connection;
135
136                         public void Abort (object sender, EventArgs args)
137                         {
138                                 WebConnection other = ((HttpWebRequest) sender).WebConnection;
139                                 if (other == null)
140                                         other = Connection;
141                                 other.Abort (sender, args);
142                         }
143                 }
144
145                 bool CanReuse ()
146                 {
147                         // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
148                         // but if there's data pending to read (!) we won't reuse the socket.
149                         return (socket.Poll (0, SelectMode.SelectRead) == false);
150                 }
151                 
152                 void Connect (HttpWebRequest request)
153                 {
154                         lock (socketLock) {
155                                 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
156                                         // Take the chunked stream to the expected state (State.None)
157                                         if (CanReuse () && CompleteChunkedRead ()) {
158                                                 reused = true;
159                                                 return;
160                                         }
161                                 }
162
163                                 reused = false;
164                                 if (socket != null) {
165                                         socket.Close();
166                                         socket = null;
167                                 }
168
169                                 chunkStream = null;
170                                 IPHostEntry hostEntry = sPoint.HostEntry;
171
172                                 if (hostEntry == null) {
173 #if MONOTOUCH
174                                         xamarin_start_wwan (sPoint.Address.ToString ());
175                                         hostEntry = sPoint.HostEntry;
176                                         if (hostEntry == null) {
177 #endif
178                                                 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
179                                                                             WebExceptionStatus.NameResolutionFailure;
180                                                 return;
181 #if MONOTOUCH
182                                         }
183 #endif
184                                 }
185
186                                 //WebConnectionData data = Data;
187                                 foreach (IPAddress address in hostEntry.AddressList) {
188                                         try {
189                                                 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
190                                         } catch (Exception se) {
191                                                 // The Socket ctor can throw if we run out of FD's
192                                                 if (!request.Aborted)
193                                                                 status = WebExceptionStatus.ConnectFailure;
194                                                 connect_exception = se;
195                                                 return;
196                                         }
197                                         IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
198                                         socket.NoDelay = !sPoint.UseNagleAlgorithm;
199                                         try {
200                                                 sPoint.KeepAliveSetup (socket);
201                                         } catch {
202                                                 // Ignore. Not supported in all platforms.
203                                         }
204
205                                         if (!sPoint.CallEndPointDelegate (socket, remote)) {
206                                                 socket.Close ();
207                                                 socket = null;
208                                                 status = WebExceptionStatus.ConnectFailure;
209                                         } else {
210                                                 try {
211                                                         if (request.Aborted)
212                                                                 return;
213                                                         socket.Connect (remote);
214                                                         status = WebExceptionStatus.Success;
215                                                         break;
216                                                 } catch (ThreadAbortException) {
217                                                         // program exiting...
218                                                         Socket s = socket;
219                                                         socket = null;
220                                                         if (s != null)
221                                                                 s.Close ();
222                                                         return;
223                                                 } catch (ObjectDisposedException) {
224                                                         // socket closed from another thread
225                                                         return;
226                                                 } catch (Exception exc) {
227                                                         Socket s = socket;
228                                                         socket = null;
229                                                         if (s != null)
230                                                                 s.Close ();
231                                                         if (!request.Aborted)
232                                                                 status = WebExceptionStatus.ConnectFailure;
233                                                         connect_exception = exc;
234                                                 }
235                                         }
236                                 }
237                         }
238                 }
239
240                 static void EnsureSSLStreamAvailable ()
241                 {
242                         lock (classLock) {
243                                 if (sslStream != null)
244                                         return;
245
246 #if NET_2_1 && SECURITY_DEP
247                                 sslStream = typeof (HttpsClientStream);
248 #else
249                                 // HttpsClientStream is an internal glue class in Mono.Security.dll
250                                 sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
251                                                         Consts.AssemblyMono_Security, false);
252
253                                 if (sslStream == null) {
254                                         string msg = "Missing Mono.Security.dll assembly. " +
255                                                         "Support for SSL/TLS is unavailable.";
256
257                                         throw new NotSupportedException (msg);
258                                 }
259 #endif
260 #if !MONOTOUCH && !MONODROID
261                                 piClient = sslStream.GetProperty ("SelectedClientCertificate");
262                                 piServer = sslStream.GetProperty ("ServerCertificate");
263                                 piTrustFailure = sslStream.GetProperty ("TrustFailure");
264 #endif
265                         }
266                 }
267
268                 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
269                                    Stream stream, out byte[] buffer)
270                 {
271                         StringBuilder sb = new StringBuilder ();
272                         sb.Append ("CONNECT ");
273                         sb.Append (request.Address.Host);
274                         sb.Append (':');
275                         sb.Append (request.Address.Port);
276                         sb.Append (" HTTP/");
277                         if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
278                                 sb.Append ("1.1");
279                         else
280                                 sb.Append ("1.0");
281
282                         sb.Append ("\r\nHost: ");
283                         sb.Append (request.Address.Authority);
284
285                         bool ntlm = false;
286                         var challenge = Data.Challenge;
287                         Data.Challenge = null;
288                         var auth_header = request.Headers ["Proxy-Authorization"];
289                         bool have_auth = auth_header != null;
290                         if (have_auth) {
291                                 sb.Append ("\r\nProxy-Authorization: ");
292                                 sb.Append (auth_header);
293                                 ntlm = auth_header.ToUpper ().Contains ("NTLM");
294                         } else if (challenge != null && Data.StatusCode == 407) {
295                                 ICredentials creds = request.Proxy.Credentials;
296                                 have_auth = true;
297
298                                 if (connect_request == null) {
299                                         // create a CONNECT request to use with Authenticate
300                                         connect_request = (HttpWebRequest)WebRequest.Create (
301                                                 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
302                                         connect_request.Method = "CONNECT";
303                                         connect_request.Credentials = creds;
304                                 }
305
306                                 for (int i = 0; i < challenge.Length; i++) {
307                                         var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
308                                         if (auth == null)
309                                                 continue;
310                                         ntlm = (auth.Module.AuthenticationType == "NTLM");
311                                         sb.Append ("\r\nProxy-Authorization: ");
312                                         sb.Append (auth.Message);
313                                         break;
314                                 }
315                         }
316
317                         if (ntlm) {
318                                 sb.Append ("\r\nProxy-Connection: keep-alive");
319                                 connect_ntlm_auth_state++;
320                         }
321
322                         sb.Append ("\r\n\r\n");
323
324                         Data.StatusCode = 0;
325                         byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
326                         stream.Write (connectBytes, 0, connectBytes.Length);
327
328                         int status;
329                         WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
330                         if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
331                             result != null && status == 407) { // Needs proxy auth
332                                 var connectionHeader = result ["Connection"];
333                                 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
334                                     connectionHeader.ToLower() == "close") {
335                                         // The server is requesting that this connection be closed
336                                         socket.Close();
337                                         socket = null;
338                                 }
339
340                                 Data.StatusCode = status;
341                                 Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false);
342                                 return false;
343                         } else if (status != 200) {
344                                 string msg = String.Format ("The remote server returned a {0} status code.", status);
345                                 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
346                                 return false;
347                         }
348
349                         return (result != null);
350                 }
351
352                 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
353                 {
354                         retBuffer = null;
355                         status = 200;
356
357                         byte [] buffer = new byte [1024];
358                         MemoryStream ms = new MemoryStream ();
359
360                         while (true) {
361                                 int n = stream.Read (buffer, 0, 1024);
362                                 if (n == 0) {
363                                         HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
364                                         return null;
365                                 }
366                                 
367                                 ms.Write (buffer, 0, n);
368                                 int start = 0;
369                                 string str = null;
370                                 bool gotStatus = false;
371                                 WebHeaderCollection headers = new WebHeaderCollection ();
372                                 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
373                                         if (str == null) {
374                                                 int contentLen = 0;
375                                                 try     {
376                                                         contentLen = int.Parse(headers["Content-Length"]);
377                                                 }
378                                                 catch {
379                                                         contentLen = 0;
380                                                 }
381
382                                                 if (ms.Length - start - contentLen > 0) {
383                                                         // we've read more data than the response header and conents,
384                                                         // give back extra data to the caller
385                                                         retBuffer = new byte[ms.Length - start - contentLen];
386                                                         Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
387                                                 }
388                                                 else {
389                                                         // haven't read in some or all of the contents for the response, do so now
390                                                         FlushContents(stream, contentLen - (int)(ms.Length - start));
391                                                 }
392
393                                                 return headers;
394                                         }
395
396                                         if (gotStatus) {
397                                                 headers.Add (str);
398                                                 continue;
399                                         }
400
401                                         string[] parts = str.Split (' ');
402                                         if (parts.Length < 2) {
403                                                 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
404                                                 return null;
405                                         }
406
407                                         if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
408                                                 Data.ProxyVersion = HttpVersion.Version11;
409                                         else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
410                                                 Data.ProxyVersion = HttpVersion.Version10;
411                                         else {
412                                                 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
413                                                 return null;
414                                         }
415
416                                         status = (int)UInt32.Parse (parts [1]);
417                                         gotStatus = true;
418                                 }
419                         }
420                 }
421
422                 void FlushContents(Stream stream, int contentLength)
423                 {
424                         while (contentLength > 0) {
425                                 byte[] contentBuffer = new byte[contentLength];
426                                 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
427                                 if (bytesRead > 0) {
428                                         contentLength -= bytesRead;
429                                 }
430                                 else {
431                                         break;
432                                 }
433                         }
434                 }
435
436                 bool CreateStream (HttpWebRequest request)
437                 {
438                         try {
439                                 NetworkStream serverStream = new NetworkStream (socket, false);
440
441                                 if (request.Address.Scheme == Uri.UriSchemeHttps) {
442                                         ssl = true;
443                                         EnsureSSLStreamAvailable ();
444                                         if (!reused || nstream == null || nstream.GetType () != sslStream) {
445                                                 byte [] buffer = null;
446                                                 if (sPoint.UseConnect) {
447                                                         bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
448                                                         if (!ok)
449                                                                 return false;
450                                                 }
451 #if SECURITY_DEP
452 #if MONOTOUCH || MONODROID
453                                                 nstream = new HttpsClientStream (serverStream, request.ClientCertificates, request, buffer);
454 #else
455                                                 object[] args = new object [4] { serverStream,
456                                                         request.ClientCertificates,
457                                                         request, buffer};
458                                                 nstream = (Stream) Activator.CreateInstance (sslStream, args);
459 #endif
460                                                 SslClientStream scs = (SslClientStream) nstream;
461                                                 var helper = new ServicePointManager.ChainValidationHelper (request, request.Address.Host);
462                                                 scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
463 #endif
464                                                 certsAvailable = false;
465                                         }
466                                         // we also need to set ServicePoint.Certificate 
467                                         // and ServicePoint.ClientCertificate but this can
468                                         // only be done later (after handshake - which is
469                                         // done only after a read operation).
470                                 } else {
471                                         ssl = false;
472                                         nstream = serverStream;
473                                 }
474                         } catch (Exception) {
475                                 if (!request.Aborted)
476                                         status = WebExceptionStatus.ConnectFailure;
477                                 return false;
478                         }
479
480                         return true;
481                 }
482                 
483                 void HandleError (WebExceptionStatus st, Exception e, string where)
484                 {
485                         status = st;
486                         lock (this) {
487                                 if (st == WebExceptionStatus.RequestCanceled)
488                                         Data = new WebConnectionData ();
489                         }
490
491                         if (e == null) { // At least we now where it comes from
492                                 try {
493                                         throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
494                                 } catch (Exception e2) {
495                                         e = e2;
496                                 }
497                         }
498
499                         HttpWebRequest req = null;
500                         if (Data != null && Data.request != null)
501                                 req = Data.request;
502
503                         Close (true);
504                         if (req != null) {
505                                 req.FinishedReading = true;
506                                 req.SetResponseError (st, e, where);
507                         }
508                 }
509                 
510                 static void ReadDone (IAsyncResult result)
511                 {
512                         WebConnection cnc = (WebConnection)result.AsyncState;
513                         WebConnectionData data = cnc.Data;
514                         Stream ns = cnc.nstream;
515                         if (ns == null) {
516                                 cnc.Close (true);
517                                 return;
518                         }
519
520                         int nread = -1;
521                         try {
522                                 nread = ns.EndRead (result);
523                         } catch (ObjectDisposedException) {
524                                 return;
525                         } catch (Exception e) {
526                                 if (e.InnerException is ObjectDisposedException)
527                                         return;
528
529                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
530                                 return;
531                         }
532
533                         if (nread == 0) {
534                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
535                                 return;
536                         }
537
538                         if (nread < 0) {
539                                 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
540                                 return;
541                         }
542
543                         int pos = -1;
544                         nread += cnc.position;
545                         if (data.ReadState == ReadState.None) { 
546                                 Exception exc = null;
547                                 try {
548                                         pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
549                                 } catch (Exception e) {
550                                         exc = e;
551                                 }
552
553                                 if (exc != null || pos == -1) {
554                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
555                                         return;
556                                 }
557                         }
558
559                         if (data.ReadState == ReadState.Aborted) {
560                                 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
561                                 return;
562                         }
563
564                         if (data.ReadState != ReadState.Content) {
565                                 int est = nread * 2;
566                                 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
567                                 byte [] newBuffer = new byte [max];
568                                 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
569                                 cnc.buffer = newBuffer;
570                                 cnc.position = nread;
571                                 data.ReadState = ReadState.None;
572                                 InitRead (cnc);
573                                 return;
574                         }
575
576                         cnc.position = 0;
577
578                         WebConnectionStream stream = new WebConnectionStream (cnc, data);
579                         bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
580                         string tencoding = null;
581                         if (expect_content)
582                                 tencoding = data.Headers ["Transfer-Encoding"];
583
584                         cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
585                         if (!cnc.chunkedRead) {
586                                 stream.ReadBuffer = cnc.buffer;
587                                 stream.ReadBufferOffset = pos;
588                                 stream.ReadBufferSize = nread;
589                                 try {
590                                         stream.CheckResponseInBuffer ();
591                                 } catch (Exception e) {
592                                         cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
593                                 }
594                         } else if (cnc.chunkStream == null) {
595                                 try {
596                                         cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
597                                 } catch (Exception e) {
598                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
599                                         return;
600                                 }
601                         } else {
602                                 cnc.chunkStream.ResetBuffer ();
603                                 try {
604                                         cnc.chunkStream.Write (cnc.buffer, pos, nread);
605                                 } catch (Exception e) {
606                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
607                                         return;
608                                 }
609                         }
610
611                         data.stream = stream;
612                         
613                         if (!expect_content)
614                                 stream.ForceCompletion ();
615
616                         data.request.SetResponseData (data);
617                 }
618
619                 static bool ExpectContent (int statusCode, string method)
620                 {
621                         if (method == "HEAD")
622                                 return false;
623                         return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
624                 }
625
626                 internal void GetCertificates (Stream stream) 
627                 {
628                         // here the SSL negotiation have been done
629 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
630                         HttpsClientStream s = (stream as HttpsClientStream);
631                         X509Certificate client = s.SelectedClientCertificate;
632                         X509Certificate server = s.ServerCertificate;
633 #else
634                         X509Certificate client = (X509Certificate) piClient.GetValue (stream, null);
635                         X509Certificate server = (X509Certificate) piServer.GetValue (stream, null);
636 #endif
637                         sPoint.SetCertificates (client, server);
638                         certsAvailable = (server != null);
639                 }
640
641                 internal static void InitRead (object state)
642                 {
643                         WebConnection cnc = (WebConnection) state;
644                         Stream ns = cnc.nstream;
645
646                         try {
647                                 int size = cnc.buffer.Length - cnc.position;
648                                 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
649                         } catch (Exception e) {
650                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
651                         }
652                 }
653                 
654                 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
655                                         byte [] buffer, int max)
656                 {
657                         int pos = 0;
658                         string line = null;
659                         bool lineok = false;
660                         bool isContinue = false;
661                         bool emptyFirstLine = false;
662                         do {
663                                 if (data.ReadState == ReadState.Aborted)
664                                         return -1;
665
666                                 if (data.ReadState == ReadState.None) {
667                                         lineok = ReadLine (buffer, ref pos, max, ref line);
668                                         if (!lineok)
669                                                 return 0;
670
671                                         if (line == null) {
672                                                 emptyFirstLine = true;
673                                                 continue;
674                                         }
675                                         emptyFirstLine = false;
676                                         data.ReadState = ReadState.Status;
677
678                                         string [] parts = line.Split (' ');
679                                         if (parts.Length < 2)
680                                                 return -1;
681
682                                         if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
683                                                 data.Version = HttpVersion.Version11;
684                                                 sPoint.SetVersion (HttpVersion.Version11);
685                                         } else {
686                                                 data.Version = HttpVersion.Version10;
687                                                 sPoint.SetVersion (HttpVersion.Version10);
688                                         }
689
690                                         data.StatusCode = (int) UInt32.Parse (parts [1]);
691                                         if (parts.Length >= 3)
692                                                 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
693                                         else
694                                                 data.StatusDescription = "";
695
696                                         if (pos >= max)
697                                                 return pos;
698                                 }
699
700                                 emptyFirstLine = false;
701                                 if (data.ReadState == ReadState.Status) {
702                                         data.ReadState = ReadState.Headers;
703                                         data.Headers = new WebHeaderCollection ();
704                                         ArrayList headers = new ArrayList ();
705                                         bool finished = false;
706                                         while (!finished) {
707                                                 if (ReadLine (buffer, ref pos, max, ref line) == false)
708                                                         break;
709                                         
710                                                 if (line == null) {
711                                                         // Empty line: end of headers
712                                                         finished = true;
713                                                         continue;
714                                                 }
715                                         
716                                                 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
717                                                         int count = headers.Count - 1;
718                                                         if (count < 0)
719                                                                 break;
720
721                                                         string prev = (string) headers [count] + line;
722                                                         headers [count] = prev;
723                                                 } else {
724                                                         headers.Add (line);
725                                                 }
726                                         }
727
728                                         if (!finished)
729                                                 return 0;
730
731                                         foreach (string s in headers)
732                                                 data.Headers.SetInternal (s);
733
734                                         if (data.StatusCode == (int) HttpStatusCode.Continue) {
735                                                 sPoint.SendContinue = true;
736                                                 if (pos >= max)
737                                                         return pos;
738
739                                                 if (data.request.ExpectContinue) {
740                                                         data.request.DoContinueDelegate (data.StatusCode, data.Headers);
741                                                         // Prevent double calls when getting the
742                                                         // headers in several packets.
743                                                         data.request.ExpectContinue = false;
744                                                 }
745
746                                                 data.ReadState = ReadState.None;
747                                                 isContinue = true;
748                                         }
749                                         else {
750                                                 data.ReadState = ReadState.Content;
751                                                 return pos;
752                                         }
753                                 }
754                         } while (emptyFirstLine || isContinue);
755
756                         return -1;
757                 }
758                 
759                 void InitConnection (object state)
760                 {
761                         HttpWebRequest request = (HttpWebRequest) state;
762                         request.WebConnection = this;
763                         if (request.ReuseConnection)
764                                 request.StoredConnection = this;
765
766                         if (request.Aborted)
767                                 return;
768
769                         keepAlive = request.KeepAlive;
770                         Data = new WebConnectionData (request);
771                 retry:
772                         Connect (request);
773                         if (request.Aborted)
774                                 return;
775
776                         if (status != WebExceptionStatus.Success) {
777                                 if (!request.Aborted) {
778                                         request.SetWriteStreamError (status, connect_exception);
779                                         Close (true);
780                                 }
781                                 return;
782                         }
783                         
784                         if (!CreateStream (request)) {
785                                 if (request.Aborted)
786                                         return;
787
788                                 WebExceptionStatus st = status;
789                                 if (Data.Challenge != null)
790                                         goto retry;
791
792                                 Exception cnc_exc = connect_exception;
793                                 connect_exception = null;
794                                 request.SetWriteStreamError (st, cnc_exc);
795                                 Close (true);
796                                 return;
797                         }
798
799                         request.SetWriteStream (new WebConnectionStream (this, request));
800                 }
801
802 #if MONOTOUCH
803                 static bool warned_about_queue = false;
804 #endif
805
806                 internal EventHandler SendRequest (HttpWebRequest request)
807                 {
808                         if (request.Aborted)
809                                 return null;
810
811                         lock (this) {
812                                 if (state.TrySetBusy ()) {
813                                         status = WebExceptionStatus.Success;
814                                         ThreadPool.QueueUserWorkItem (initConn, request);
815                                 } else {
816                                         lock (queue) {
817 #if MONOTOUCH
818                                                 if (!warned_about_queue) {
819                                                         warned_about_queue = true;
820                                                         Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
821                                                 }
822 #endif
823                                                 queue.Enqueue (request);
824                                         }
825                                 }
826                         }
827
828                         return abortHandler;
829                 }
830                 
831                 void SendNext ()
832                 {
833                         lock (queue) {
834                                 if (queue.Count > 0) {
835                                         SendRequest ((HttpWebRequest) queue.Dequeue ());
836                                 }
837                         }
838                 }
839
840                 internal void NextRead ()
841                 {
842                         lock (this) {
843                                 if (Data.request != null)
844                                         Data.request.FinishedReading = true;
845                                 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
846                                 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
847                                 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
848                                 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
849                                         keepAlive = false;
850                                 if (cncHeader != null) {
851                                         cncHeader = cncHeader.ToLower ();
852                                         keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
853                                 }
854
855                                 if ((socket != null && !socket.Connected) ||
856                                    (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
857                                         Close (false);
858                                 }
859
860                                 state.SetIdle ();
861                                 if (priority_request != null) {
862                                         SendRequest (priority_request);
863                                         priority_request = null;
864                                 } else {
865                                         SendNext ();
866                                 }
867                         }
868                 }
869                 
870                 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
871                 {
872                         bool foundCR = false;
873                         StringBuilder text = new StringBuilder ();
874
875                         int c = 0;
876                         while (start < max) {
877                                 c = (int) buffer [start++];
878
879                                 if (c == '\n') {                        // newline
880                                         if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
881                                                 text.Length--;
882
883                                         foundCR = false;
884                                         break;
885                                 } else if (foundCR) {
886                                         text.Length--;
887                                         break;
888                                 }
889
890                                 if (c == '\r')
891                                         foundCR = true;
892                                         
893
894                                 text.Append ((char) c);
895                         }
896
897                         if (c != '\n' && c != '\r')
898                                 return false;
899
900                         if (text.Length == 0) {
901                                 output = null;
902                                 return (c == '\n' || c == '\r');
903                         }
904
905                         if (foundCR)
906                                 text.Length--;
907
908                         output = text.ToString ();
909                         return true;
910                 }
911
912
913                 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
914                 {
915                         Stream s = null;
916                         lock (this) {
917                                 if (Data.request != request)
918                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
919                                 if (nstream == null)
920                                         return null;
921                                 s = nstream;
922                         }
923
924                         IAsyncResult result = null;
925                         if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
926                                 try {
927                                         result = s.BeginRead (buffer, offset, size, cb, state);
928                                         cb = null;
929                                 } catch (Exception) {
930                                         HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
931                                         throw;
932                                 }
933                         }
934
935                         if (chunkedRead) {
936                                 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
937                                 wr.InnerAsyncResult = result;
938                                 if (result == null) {
939                                         // Will be completed from the data in ChunkStream
940                                         wr.SetCompleted (true, (Exception) null);
941                                         wr.DoCallback ();
942                                 }
943                                 return wr;
944                         }
945
946                         return result;
947                 }
948                 
949                 internal int EndRead (HttpWebRequest request, IAsyncResult result)
950                 {
951                         Stream s = null;
952                         lock (this) {
953                                 if (Data.request != request)
954                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
955                                 if (nstream == null)
956                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
957                                 s = nstream;
958                         }
959
960                         int nbytes = 0;
961                         bool done = false;
962                         WebAsyncResult wr = null;
963                         IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
964                         if (chunkedRead && (nsAsync is WebAsyncResult)) {
965                                 wr = (WebAsyncResult) nsAsync;
966                                 IAsyncResult inner = wr.InnerAsyncResult;
967                                 if (inner != null && !(inner is WebAsyncResult)) {
968                                         nbytes = s.EndRead (inner);
969                                         done = nbytes == 0;
970                                 }
971                         } else if (!(nsAsync is WebAsyncResult)) {
972                                 nbytes = s.EndRead (nsAsync);
973                                 wr = (WebAsyncResult) result;
974                                 done = nbytes == 0;
975                         }
976
977                         if (chunkedRead) {
978                                 try {
979                                         chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
980                                         if (!done && nbytes == 0 && chunkStream.WantMore)
981                                                 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
982                                 } catch (Exception e) {
983                                         if (e is WebException)
984                                                 throw e;
985
986                                         throw new WebException ("Invalid chunked data.", e,
987                                                                 WebExceptionStatus.ServerProtocolViolation, null);
988                                 }
989
990                                 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
991                                         HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
992                                         throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
993                                 }
994                         }
995
996                         return (nbytes != 0) ? nbytes : -1;
997                 }
998
999                 // To be called on chunkedRead when we can read no data from the ChunkStream yet
1000                 int EnsureRead (byte [] buffer, int offset, int size)
1001                 {
1002                         byte [] morebytes = null;
1003                         int nbytes = 0;
1004                         while (nbytes == 0 && chunkStream.WantMore) {
1005                                 int localsize = chunkStream.ChunkLeft;
1006                                 if (localsize <= 0) // not read chunk size yet
1007                                         localsize = 1024;
1008                                 else if (localsize > 16384)
1009                                         localsize = 16384;
1010
1011                                 if (morebytes == null || morebytes.Length < localsize)
1012                                         morebytes = new byte [localsize];
1013
1014                                 int nread = nstream.Read (morebytes, 0, localsize);
1015                                 if (nread <= 0)
1016                                         return 0; // Error
1017
1018                                 chunkStream.Write (morebytes, 0, nread);
1019                                 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
1020                         }
1021
1022                         return nbytes;
1023                 }
1024
1025                 bool CompleteChunkedRead()
1026                 {
1027                         if (!chunkedRead || chunkStream == null)
1028                                 return true;
1029
1030                         while (chunkStream.WantMore) {
1031                                 int nbytes = nstream.Read (buffer, 0, buffer.Length);
1032                                 if (nbytes <= 0)
1033                                         return false; // Socket was disconnected
1034
1035                                 chunkStream.Write (buffer, 0, nbytes);
1036                         }
1037
1038                         return true;
1039                 }
1040
1041                 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1042                 {
1043                         Stream s = null;
1044                         lock (this) {
1045                                 if (Data.request != request)
1046                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1047                                 if (nstream == null)
1048                                         return null;
1049                                 s = nstream;
1050                         }
1051
1052                         IAsyncResult result = null;
1053                         try {
1054                                 result = s.BeginWrite (buffer, offset, size, cb, state);
1055                         } catch (Exception) {
1056                                 status = WebExceptionStatus.SendFailure;
1057                                 throw;
1058                         }
1059
1060                         return result;
1061                 }
1062
1063                 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1064                 {
1065                         if (request.FinishedReading)
1066                                 return true;
1067
1068                         Stream s = null;
1069                         lock (this) {
1070                                 if (Data.request != request)
1071                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1072                                 if (nstream == null)
1073                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1074                                 s = nstream;
1075                         }
1076
1077                         try {
1078                                 s.EndWrite (result);
1079                                 return true;
1080                         } catch (Exception exc) {
1081                                 status = WebExceptionStatus.SendFailure;
1082                                 if (throwOnError && exc.InnerException != null)
1083                                         throw exc.InnerException;
1084                                 return false;
1085                         }
1086                 }
1087
1088                 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1089                 {
1090                         Stream s = null;
1091                         lock (this) {
1092                                 if (Data.request != request)
1093                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1094                                 if (nstream == null)
1095                                         return 0;
1096                                 s = nstream;
1097                         }
1098
1099                         int result = 0;
1100                         try {
1101                                 bool done = false;
1102                                 if (!chunkedRead) {
1103                                         result = s.Read (buffer, offset, size);
1104                                         done = (result == 0);
1105                                 }
1106
1107                                 if (chunkedRead) {
1108                                         try {
1109                                                 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1110                                                 if (!done && result == 0 && chunkStream.WantMore)
1111                                                         result = EnsureRead (buffer, offset, size);
1112                                         } catch (Exception e) {
1113                                                 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1114                                                 throw;
1115                                         }
1116
1117                                         if ((done || result == 0) && chunkStream.WantMore) {
1118                                                 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1119                                                 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1120                                         }
1121                                 }
1122                         } catch (Exception e) {
1123                                 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1124                         }
1125
1126                         return result;
1127                 }
1128
1129                 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1130                 {
1131                         err_msg = null;
1132                         Stream s = null;
1133                         lock (this) {
1134                                 if (Data.request != request)
1135                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1136                                 s = nstream;
1137                                 if (s == null)
1138                                         return false;
1139                         }
1140
1141                         try {
1142                                 s.Write (buffer, offset, size);
1143                                 // here SSL handshake should have been done
1144                                 if (ssl && !certsAvailable)
1145                                         GetCertificates (s);
1146                         } catch (Exception e) {
1147                                 err_msg = e.Message;
1148                                 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1149                                 string msg = "Write: " + err_msg;
1150                                 if (e is WebException) {
1151                                         HandleError (wes, e, msg);
1152                                         return false;
1153                                 }
1154
1155                                 // if SSL is in use then check for TrustFailure
1156                                 if (ssl) {
1157 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
1158                                         HttpsClientStream https = (s as HttpsClientStream);
1159                                         if (https.TrustFailure) {
1160 #else
1161                                         if ((bool) piTrustFailure.GetValue (s , null)) {
1162 #endif
1163                                                 wes = WebExceptionStatus.TrustFailure;
1164                                                 msg = "Trust failure";
1165                                         }
1166                                 }
1167
1168                                 HandleError (wes, e, msg);
1169                                 return false;
1170                         }
1171                         return true;
1172                 }
1173
1174                 internal void Close (bool sendNext)
1175                 {
1176                         lock (this) {
1177                                 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1178                                         Data.request.ReuseConnection = false;
1179                                         return;
1180                                 }
1181
1182                                 if (nstream != null) {
1183                                         try {
1184                                                 nstream.Close ();
1185                                         } catch {}
1186                                         nstream = null;
1187                                 }
1188
1189                                 if (socket != null) {
1190                                         try {
1191                                                 socket.Close ();
1192                                         } catch {}
1193                                         socket = null;
1194                                 }
1195
1196                                 if (ntlm_authenticated)
1197                                         ResetNtlm ();
1198                                 if (Data != null) {
1199                                         lock (Data) {
1200                                                 Data.ReadState = ReadState.Aborted;
1201                                         }
1202                                 }
1203                                 state.SetIdle ();
1204                                 Data = new WebConnectionData ();
1205                                 if (sendNext)
1206                                         SendNext ();
1207                                 
1208                                 connect_request = null;
1209                                 connect_ntlm_auth_state = NtlmAuthState.None;
1210                         }
1211                 }
1212
1213                 void Abort (object sender, EventArgs args)
1214                 {
1215                         lock (this) {
1216                                 lock (queue) {
1217                                         HttpWebRequest req = (HttpWebRequest) sender;
1218                                         if (Data.request == req || Data.request == null) {
1219                                                 if (!req.FinishedReading) {
1220                                                         status = WebExceptionStatus.RequestCanceled;
1221                                                         Close (false);
1222                                                         if (queue.Count > 0) {
1223                                                                 Data.request = (HttpWebRequest) queue.Dequeue ();
1224                                                                 SendRequest (Data.request);
1225                                                         }
1226                                                 }
1227                                                 return;
1228                                         }
1229
1230                                         req.FinishedReading = true;
1231                                         req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1232                                         if (queue.Count > 0 && queue.Peek () == sender) {
1233                                                 queue.Dequeue ();
1234                                         } else if (queue.Count > 0) {
1235                                                 object [] old = queue.ToArray ();
1236                                                 queue.Clear ();
1237                                                 for (int i = old.Length - 1; i >= 0; i--) {
1238                                                         if (old [i] != sender)
1239                                                                 queue.Enqueue (old [i]);
1240                                                 }
1241                                         }
1242                                 }
1243                         }
1244                 }
1245
1246                 internal void ResetNtlm ()
1247                 {
1248                         ntlm_authenticated = false;
1249                         ntlm_credentials = null;
1250                         unsafe_sharing = false;
1251                 }
1252
1253                 internal bool Connected {
1254                         get {
1255                                 lock (this) {
1256                                         return (socket != null && socket.Connected);
1257                                 }
1258                         }
1259                 }
1260
1261                 // -Used for NTLM authentication
1262                 internal HttpWebRequest PriorityRequest {
1263                         set { priority_request = value; }
1264                 }
1265
1266                 internal bool NtlmAuthenticated {
1267                         get { return ntlm_authenticated; }
1268                         set { ntlm_authenticated = value; }
1269                 }
1270
1271                 internal NetworkCredential NtlmCredential {
1272                         get { return ntlm_credentials; }
1273                         set { ntlm_credentials = value; }
1274                 }
1275
1276                 internal bool UnsafeAuthenticatedConnectionSharing {
1277                         get { return unsafe_sharing; }
1278                         set { unsafe_sharing = value; }
1279                 }
1280                 // -
1281         }
1282 }
1283