WebConnection.cs 31 KB

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