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