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