WebConnection.cs 33 KB

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