WebConnection.cs 34 KB

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