WebConnection.cs 31 KB

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