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