Merge pull request #1109 from adbre/iss358
[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 monotouch_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                                         monotouch_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 #if TARGET_JVM
494                                         throw new Exception ();
495 #else
496                                         throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
497 #endif
498                                 } catch (Exception e2) {
499                                         e = e2;
500                                 }
501                         }
502
503                         HttpWebRequest req = null;
504                         if (Data != null && Data.request != null)
505                                 req = Data.request;
506
507                         Close (true);
508                         if (req != null) {
509                                 req.FinishedReading = true;
510                                 req.SetResponseError (st, e, where);
511                         }
512                 }
513                 
514                 static void ReadDone (IAsyncResult result)
515                 {
516                         WebConnection cnc = (WebConnection)result.AsyncState;
517                         WebConnectionData data = cnc.Data;
518                         Stream ns = cnc.nstream;
519                         if (ns == null) {
520                                 cnc.Close (true);
521                                 return;
522                         }
523
524                         int nread = -1;
525                         try {
526                                 nread = ns.EndRead (result);
527                         } catch (ObjectDisposedException) {
528                                 return;
529                         } catch (Exception e) {
530                                 if (e.InnerException is ObjectDisposedException)
531                                         return;
532
533                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
534                                 return;
535                         }
536
537                         if (nread == 0) {
538                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
539                                 return;
540                         }
541
542                         if (nread < 0) {
543                                 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
544                                 return;
545                         }
546
547                         int pos = -1;
548                         nread += cnc.position;
549                         if (data.ReadState == ReadState.None) { 
550                                 Exception exc = null;
551                                 try {
552                                         pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
553                                 } catch (Exception e) {
554                                         exc = e;
555                                 }
556
557                                 if (exc != null || pos == -1) {
558                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
559                                         return;
560                                 }
561                         }
562
563                         if (data.ReadState == ReadState.Aborted) {
564                                 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
565                                 return;
566                         }
567
568                         if (data.ReadState != ReadState.Content) {
569                                 int est = nread * 2;
570                                 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
571                                 byte [] newBuffer = new byte [max];
572                                 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
573                                 cnc.buffer = newBuffer;
574                                 cnc.position = nread;
575                                 data.ReadState = ReadState.None;
576                                 InitRead (cnc);
577                                 return;
578                         }
579
580                         cnc.position = 0;
581
582                         WebConnectionStream stream = new WebConnectionStream (cnc, data);
583                         bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
584                         string tencoding = null;
585                         if (expect_content)
586                                 tencoding = data.Headers ["Transfer-Encoding"];
587
588                         cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
589                         if (!cnc.chunkedRead) {
590                                 stream.ReadBuffer = cnc.buffer;
591                                 stream.ReadBufferOffset = pos;
592                                 stream.ReadBufferSize = nread;
593                                 try {
594                                         stream.CheckResponseInBuffer ();
595                                 } catch (Exception e) {
596                                         cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
597                                 }
598                         } else if (cnc.chunkStream == null) {
599                                 try {
600                                         cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
601                                 } catch (Exception e) {
602                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
603                                         return;
604                                 }
605                         } else {
606                                 cnc.chunkStream.ResetBuffer ();
607                                 try {
608                                         cnc.chunkStream.Write (cnc.buffer, pos, nread);
609                                 } catch (Exception e) {
610                                         cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
611                                         return;
612                                 }
613                         }
614
615                         data.stream = stream;
616                         
617                         if (!expect_content)
618                                 stream.ForceCompletion ();
619
620                         data.request.SetResponseData (data);
621                 }
622
623                 static bool ExpectContent (int statusCode, string method)
624                 {
625                         if (method == "HEAD")
626                                 return false;
627                         return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
628                 }
629
630                 internal void GetCertificates (Stream stream) 
631                 {
632                         // here the SSL negotiation have been done
633 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
634                         HttpsClientStream s = (stream as HttpsClientStream);
635                         X509Certificate client = s.SelectedClientCertificate;
636                         X509Certificate server = s.ServerCertificate;
637 #else
638                         X509Certificate client = (X509Certificate) piClient.GetValue (stream, null);
639                         X509Certificate server = (X509Certificate) piServer.GetValue (stream, null);
640 #endif
641                         sPoint.SetCertificates (client, server);
642                         certsAvailable = (server != null);
643                 }
644
645                 internal static void InitRead (object state)
646                 {
647                         WebConnection cnc = (WebConnection) state;
648                         Stream ns = cnc.nstream;
649
650                         try {
651                                 int size = cnc.buffer.Length - cnc.position;
652                                 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
653                         } catch (Exception e) {
654                                 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
655                         }
656                 }
657                 
658                 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
659                                         byte [] buffer, int max)
660                 {
661                         int pos = 0;
662                         string line = null;
663                         bool lineok = false;
664                         bool isContinue = false;
665                         bool emptyFirstLine = false;
666                         do {
667                                 if (data.ReadState == ReadState.Aborted)
668                                         return -1;
669
670                                 if (data.ReadState == ReadState.None) {
671                                         lineok = ReadLine (buffer, ref pos, max, ref line);
672                                         if (!lineok)
673                                                 return 0;
674
675                                         if (line == null) {
676                                                 emptyFirstLine = true;
677                                                 continue;
678                                         }
679                                         emptyFirstLine = false;
680                                         data.ReadState = ReadState.Status;
681
682                                         string [] parts = line.Split (' ');
683                                         if (parts.Length < 2)
684                                                 return -1;
685
686                                         if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
687                                                 data.Version = HttpVersion.Version11;
688                                                 sPoint.SetVersion (HttpVersion.Version11);
689                                         } else {
690                                                 data.Version = HttpVersion.Version10;
691                                                 sPoint.SetVersion (HttpVersion.Version10);
692                                         }
693
694                                         data.StatusCode = (int) UInt32.Parse (parts [1]);
695                                         if (parts.Length >= 3)
696                                                 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
697                                         else
698                                                 data.StatusDescription = "";
699
700                                         if (pos >= max)
701                                                 return pos;
702                                 }
703
704                                 emptyFirstLine = false;
705                                 if (data.ReadState == ReadState.Status) {
706                                         data.ReadState = ReadState.Headers;
707                                         data.Headers = new WebHeaderCollection ();
708                                         ArrayList headers = new ArrayList ();
709                                         bool finished = false;
710                                         while (!finished) {
711                                                 if (ReadLine (buffer, ref pos, max, ref line) == false)
712                                                         break;
713                                         
714                                                 if (line == null) {
715                                                         // Empty line: end of headers
716                                                         finished = true;
717                                                         continue;
718                                                 }
719                                         
720                                                 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
721                                                         int count = headers.Count - 1;
722                                                         if (count < 0)
723                                                                 break;
724
725                                                         string prev = (string) headers [count] + line;
726                                                         headers [count] = prev;
727                                                 } else {
728                                                         headers.Add (line);
729                                                 }
730                                         }
731
732                                         if (!finished)
733                                                 return 0;
734
735                                         foreach (string s in headers)
736                                                 data.Headers.SetInternal (s);
737
738                                         if (data.StatusCode == (int) HttpStatusCode.Continue) {
739                                                 sPoint.SendContinue = true;
740                                                 if (pos >= max)
741                                                         return pos;
742
743                                                 if (data.request.ExpectContinue) {
744                                                         data.request.DoContinueDelegate (data.StatusCode, data.Headers);
745                                                         // Prevent double calls when getting the
746                                                         // headers in several packets.
747                                                         data.request.ExpectContinue = false;
748                                                 }
749
750                                                 data.ReadState = ReadState.None;
751                                                 isContinue = true;
752                                         }
753                                         else {
754                                                 data.ReadState = ReadState.Content;
755                                                 return pos;
756                                         }
757                                 }
758                         } while (emptyFirstLine || isContinue);
759
760                         return -1;
761                 }
762                 
763                 void InitConnection (object state)
764                 {
765                         HttpWebRequest request = (HttpWebRequest) state;
766                         request.WebConnection = this;
767                         if (request.ReuseConnection)
768                                 request.StoredConnection = this;
769
770                         if (request.Aborted)
771                                 return;
772
773                         keepAlive = request.KeepAlive;
774                         Data = new WebConnectionData (request);
775                 retry:
776                         Connect (request);
777                         if (request.Aborted)
778                                 return;
779
780                         if (status != WebExceptionStatus.Success) {
781                                 if (!request.Aborted) {
782                                         request.SetWriteStreamError (status, connect_exception);
783                                         Close (true);
784                                 }
785                                 return;
786                         }
787                         
788                         if (!CreateStream (request)) {
789                                 if (request.Aborted)
790                                         return;
791
792                                 WebExceptionStatus st = status;
793                                 if (Data.Challenge != null)
794                                         goto retry;
795
796                                 Exception cnc_exc = connect_exception;
797                                 connect_exception = null;
798                                 request.SetWriteStreamError (st, cnc_exc);
799                                 Close (true);
800                                 return;
801                         }
802
803                         request.SetWriteStream (new WebConnectionStream (this, request));
804                 }
805
806 #if MONOTOUCH
807                 static bool warned_about_queue = false;
808 #endif
809
810                 internal EventHandler SendRequest (HttpWebRequest request)
811                 {
812                         if (request.Aborted)
813                                 return null;
814
815                         lock (this) {
816                                 if (state.TrySetBusy ()) {
817                                         status = WebExceptionStatus.Success;
818                                         ThreadPool.QueueUserWorkItem (initConn, request);
819                                 } else {
820                                         lock (queue) {
821 #if MONOTOUCH
822                                                 if (!warned_about_queue) {
823                                                         warned_about_queue = true;
824                                                         Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
825                                                 }
826 #endif
827                                                 queue.Enqueue (request);
828                                         }
829                                 }
830                         }
831
832                         return abortHandler;
833                 }
834                 
835                 void SendNext ()
836                 {
837                         lock (queue) {
838                                 if (queue.Count > 0) {
839                                         SendRequest ((HttpWebRequest) queue.Dequeue ());
840                                 }
841                         }
842                 }
843
844                 internal void NextRead ()
845                 {
846                         lock (this) {
847                                 if (Data.request != null)
848                                         Data.request.FinishedReading = true;
849                                 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
850                                 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
851                                 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
852                                 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
853                                         keepAlive = false;
854                                 if (cncHeader != null) {
855                                         cncHeader = cncHeader.ToLower ();
856                                         keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
857                                 }
858
859                                 if ((socket != null && !socket.Connected) ||
860                                    (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
861                                         Close (false);
862                                 }
863
864                                 state.SetIdle ();
865                                 if (priority_request != null) {
866                                         SendRequest (priority_request);
867                                         priority_request = null;
868                                 } else {
869                                         SendNext ();
870                                 }
871                         }
872                 }
873                 
874                 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
875                 {
876                         bool foundCR = false;
877                         StringBuilder text = new StringBuilder ();
878
879                         int c = 0;
880                         while (start < max) {
881                                 c = (int) buffer [start++];
882
883                                 if (c == '\n') {                        // newline
884                                         if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
885                                                 text.Length--;
886
887                                         foundCR = false;
888                                         break;
889                                 } else if (foundCR) {
890                                         text.Length--;
891                                         break;
892                                 }
893
894                                 if (c == '\r')
895                                         foundCR = true;
896                                         
897
898                                 text.Append ((char) c);
899                         }
900
901                         if (c != '\n' && c != '\r')
902                                 return false;
903
904                         if (text.Length == 0) {
905                                 output = null;
906                                 return (c == '\n' || c == '\r');
907                         }
908
909                         if (foundCR)
910                                 text.Length--;
911
912                         output = text.ToString ();
913                         return true;
914                 }
915
916
917                 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
918                 {
919                         Stream s = null;
920                         lock (this) {
921                                 if (Data.request != request)
922                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
923                                 if (nstream == null)
924                                         return null;
925                                 s = nstream;
926                         }
927
928                         IAsyncResult result = null;
929                         if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
930                                 try {
931                                         result = s.BeginRead (buffer, offset, size, cb, state);
932                                         cb = null;
933                                 } catch (Exception) {
934                                         HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
935                                         throw;
936                                 }
937                         }
938
939                         if (chunkedRead) {
940                                 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
941                                 wr.InnerAsyncResult = result;
942                                 if (result == null) {
943                                         // Will be completed from the data in ChunkStream
944                                         wr.SetCompleted (true, (Exception) null);
945                                         wr.DoCallback ();
946                                 }
947                                 return wr;
948                         }
949
950                         return result;
951                 }
952                 
953                 internal int EndRead (HttpWebRequest request, IAsyncResult result)
954                 {
955                         Stream s = null;
956                         lock (this) {
957                                 if (Data.request != request)
958                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
959                                 if (nstream == null)
960                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
961                                 s = nstream;
962                         }
963
964                         int nbytes = 0;
965                         bool done = false;
966                         WebAsyncResult wr = null;
967                         IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
968                         if (chunkedRead && (nsAsync is WebAsyncResult)) {
969                                 wr = (WebAsyncResult) nsAsync;
970                                 IAsyncResult inner = wr.InnerAsyncResult;
971                                 if (inner != null && !(inner is WebAsyncResult)) {
972                                         nbytes = s.EndRead (inner);
973                                         done = nbytes == 0;
974                                 }
975                         } else if (!(nsAsync is WebAsyncResult)) {
976                                 nbytes = s.EndRead (nsAsync);
977                                 wr = (WebAsyncResult) result;
978                                 done = nbytes == 0;
979                         }
980
981                         if (chunkedRead) {
982                                 try {
983                                         chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
984                                         if (!done && nbytes == 0 && chunkStream.WantMore)
985                                                 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
986                                 } catch (Exception e) {
987                                         if (e is WebException)
988                                                 throw e;
989
990                                         throw new WebException ("Invalid chunked data.", e,
991                                                                 WebExceptionStatus.ServerProtocolViolation, null);
992                                 }
993
994                                 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
995                                         HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
996                                         throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
997                                 }
998                         }
999
1000                         return (nbytes != 0) ? nbytes : -1;
1001                 }
1002
1003                 // To be called on chunkedRead when we can read no data from the ChunkStream yet
1004                 int EnsureRead (byte [] buffer, int offset, int size)
1005                 {
1006                         byte [] morebytes = null;
1007                         int nbytes = 0;
1008                         while (nbytes == 0 && chunkStream.WantMore) {
1009                                 int localsize = chunkStream.ChunkLeft;
1010                                 if (localsize <= 0) // not read chunk size yet
1011                                         localsize = 1024;
1012                                 else if (localsize > 16384)
1013                                         localsize = 16384;
1014
1015                                 if (morebytes == null || morebytes.Length < localsize)
1016                                         morebytes = new byte [localsize];
1017
1018                                 int nread = nstream.Read (morebytes, 0, localsize);
1019                                 if (nread <= 0)
1020                                         return 0; // Error
1021
1022                                 chunkStream.Write (morebytes, 0, nread);
1023                                 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
1024                         }
1025
1026                         return nbytes;
1027                 }
1028
1029                 bool CompleteChunkedRead()
1030                 {
1031                         if (!chunkedRead || chunkStream == null)
1032                                 return true;
1033
1034                         while (chunkStream.WantMore) {
1035                                 int nbytes = nstream.Read (buffer, 0, buffer.Length);
1036                                 if (nbytes <= 0)
1037                                         return false; // Socket was disconnected
1038
1039                                 chunkStream.Write (buffer, 0, nbytes);
1040                         }
1041
1042                         return true;
1043                 }
1044
1045                 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1046                 {
1047                         Stream s = null;
1048                         lock (this) {
1049                                 if (Data.request != request)
1050                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1051                                 if (nstream == null)
1052                                         return null;
1053                                 s = nstream;
1054                         }
1055
1056                         IAsyncResult result = null;
1057                         try {
1058                                 result = s.BeginWrite (buffer, offset, size, cb, state);
1059                         } catch (Exception) {
1060                                 status = WebExceptionStatus.SendFailure;
1061                                 throw;
1062                         }
1063
1064                         return result;
1065                 }
1066
1067                 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1068                 {
1069                         if (request.FinishedReading)
1070                                 return true;
1071
1072                         Stream s = null;
1073                         lock (this) {
1074                                 if (Data.request != request)
1075                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1076                                 if (nstream == null)
1077                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1078                                 s = nstream;
1079                         }
1080
1081                         try {
1082                                 s.EndWrite (result);
1083                                 return true;
1084                         } catch (Exception exc) {
1085                                 status = WebExceptionStatus.SendFailure;
1086                                 if (throwOnError && exc.InnerException != null)
1087                                         throw exc.InnerException;
1088                                 return false;
1089                         }
1090                 }
1091
1092                 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1093                 {
1094                         Stream s = null;
1095                         lock (this) {
1096                                 if (Data.request != request)
1097                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1098                                 if (nstream == null)
1099                                         return 0;
1100                                 s = nstream;
1101                         }
1102
1103                         int result = 0;
1104                         try {
1105                                 bool done = false;
1106                                 if (!chunkedRead) {
1107                                         result = s.Read (buffer, offset, size);
1108                                         done = (result == 0);
1109                                 }
1110
1111                                 if (chunkedRead) {
1112                                         try {
1113                                                 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1114                                                 if (!done && result == 0 && chunkStream.WantMore)
1115                                                         result = EnsureRead (buffer, offset, size);
1116                                         } catch (Exception e) {
1117                                                 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1118                                                 throw;
1119                                         }
1120
1121                                         if ((done || result == 0) && chunkStream.WantMore) {
1122                                                 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1123                                                 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1124                                         }
1125                                 }
1126                         } catch (Exception e) {
1127                                 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1128                         }
1129
1130                         return result;
1131                 }
1132
1133                 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1134                 {
1135                         err_msg = null;
1136                         Stream s = null;
1137                         lock (this) {
1138                                 if (Data.request != request)
1139                                         throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1140                                 s = nstream;
1141                                 if (s == null)
1142                                         return false;
1143                         }
1144
1145                         try {
1146                                 s.Write (buffer, offset, size);
1147                                 // here SSL handshake should have been done
1148                                 if (ssl && !certsAvailable)
1149                                         GetCertificates (s);
1150                         } catch (Exception e) {
1151                                 err_msg = e.Message;
1152                                 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1153                                 string msg = "Write: " + err_msg;
1154                                 if (e is WebException) {
1155                                         HandleError (wes, e, msg);
1156                                         return false;
1157                                 }
1158
1159                                 // if SSL is in use then check for TrustFailure
1160                                 if (ssl) {
1161 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
1162                                         HttpsClientStream https = (s as HttpsClientStream);
1163                                         if (https.TrustFailure) {
1164 #else
1165                                         if ((bool) piTrustFailure.GetValue (s , null)) {
1166 #endif
1167                                                 wes = WebExceptionStatus.TrustFailure;
1168                                                 msg = "Trust failure";
1169                                         }
1170                                 }
1171
1172                                 HandleError (wes, e, msg);
1173                                 return false;
1174                         }
1175                         return true;
1176                 }
1177
1178                 internal void Close (bool sendNext)
1179                 {
1180                         lock (this) {
1181                                 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1182                                         Data.request.ReuseConnection = false;
1183                                         return;
1184                                 }
1185
1186                                 if (nstream != null) {
1187                                         try {
1188                                                 nstream.Close ();
1189                                         } catch {}
1190                                         nstream = null;
1191                                 }
1192
1193                                 if (socket != null) {
1194                                         try {
1195                                                 socket.Close ();
1196                                         } catch {}
1197                                         socket = null;
1198                                 }
1199
1200                                 if (ntlm_authenticated)
1201                                         ResetNtlm ();
1202                                 if (Data != null) {
1203                                         lock (Data) {
1204                                                 Data.ReadState = ReadState.Aborted;
1205                                         }
1206                                 }
1207                                 state.SetIdle ();
1208                                 Data = new WebConnectionData ();
1209                                 if (sendNext)
1210                                         SendNext ();
1211                                 
1212                                 connect_request = null;
1213                                 connect_ntlm_auth_state = NtlmAuthState.None;
1214                         }
1215                 }
1216
1217                 void Abort (object sender, EventArgs args)
1218                 {
1219                         lock (this) {
1220                                 lock (queue) {
1221                                         HttpWebRequest req = (HttpWebRequest) sender;
1222                                         if (Data.request == req || Data.request == null) {
1223                                                 if (!req.FinishedReading) {
1224                                                         status = WebExceptionStatus.RequestCanceled;
1225                                                         Close (false);
1226                                                         if (queue.Count > 0) {
1227                                                                 Data.request = (HttpWebRequest) queue.Dequeue ();
1228                                                                 SendRequest (Data.request);
1229                                                         }
1230                                                 }
1231                                                 return;
1232                                         }
1233
1234                                         req.FinishedReading = true;
1235                                         req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1236                                         if (queue.Count > 0 && queue.Peek () == sender) {
1237                                                 queue.Dequeue ();
1238                                         } else if (queue.Count > 0) {
1239                                                 object [] old = queue.ToArray ();
1240                                                 queue.Clear ();
1241                                                 for (int i = old.Length - 1; i >= 0; i--) {
1242                                                         if (old [i] != sender)
1243                                                                 queue.Enqueue (old [i]);
1244                                                 }
1245                                         }
1246                                 }
1247                         }
1248                 }
1249
1250                 internal void ResetNtlm ()
1251                 {
1252                         ntlm_authenticated = false;
1253                         ntlm_credentials = null;
1254                         unsafe_sharing = false;
1255                 }
1256
1257                 internal bool Connected {
1258                         get {
1259                                 lock (this) {
1260                                         return (socket != null && socket.Connected);
1261                                 }
1262                         }
1263                 }
1264
1265                 // -Used for NTLM authentication
1266                 internal HttpWebRequest PriorityRequest {
1267                         set { priority_request = value; }
1268                 }
1269
1270                 internal bool NtlmAuthenticated {
1271                         get { return ntlm_authenticated; }
1272                         set { ntlm_authenticated = value; }
1273                 }
1274
1275                 internal NetworkCredential NtlmCredential {
1276                         get { return ntlm_credentials; }
1277                         set { ntlm_credentials = value; }
1278                 }
1279
1280                 internal bool UnsafeAuthenticatedConnectionSharing {
1281                         get { return unsafe_sharing; }
1282                         set { unsafe_sharing = value; }
1283                 }
1284                 // -
1285         }
1286 }
1287