WebConnection.cs 31 KB

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