WebConnection.cs 32 KB

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