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