WebConnection.cs 33 KB

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