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