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