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