WebConnection.cs 33 KB

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