WebConnection.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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.ModuleAuthenticationType == "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 ("Proxy-Authentic");
  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. // .NET uses ParseHeaders or ParseHeadersStrict which is much better
  585. foreach (string s in headers) {
  586. int pos_s = s.IndexOf (':');
  587. if (pos_s == -1)
  588. throw new ArgumentException ("no colon found", "header");
  589. var header = s.Substring (0, pos_s);
  590. var value = s.Substring (pos_s + 1).Trim ();
  591. var h = data.Headers;
  592. if (h.AllowMultiValues (header)) {
  593. h.AddInternal (header, value);
  594. } else {
  595. h.SetInternal (header, value);
  596. }
  597. }
  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. Stream s = null;
  876. lock (this) {
  877. if (status == WebExceptionStatus.RequestCanceled)
  878. return true;
  879. if (Data.request != request)
  880. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  881. if (nstream == null)
  882. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  883. s = nstream;
  884. }
  885. try {
  886. s.EndWrite (result);
  887. return true;
  888. } catch (Exception exc) {
  889. status = WebExceptionStatus.SendFailure;
  890. if (throwOnError && exc.InnerException != null)
  891. throw exc.InnerException;
  892. return false;
  893. }
  894. }
  895. internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
  896. {
  897. Stream s = null;
  898. lock (this) {
  899. if (Data.request != request)
  900. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  901. if (nstream == null)
  902. return 0;
  903. s = nstream;
  904. }
  905. int result = 0;
  906. try {
  907. bool done = false;
  908. if (!chunkedRead) {
  909. result = s.Read (buffer, offset, size);
  910. done = (result == 0);
  911. }
  912. if (chunkedRead) {
  913. try {
  914. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  915. if (!done && result == 0 && chunkStream.WantMore)
  916. result = EnsureRead (buffer, offset, size);
  917. } catch (Exception e) {
  918. HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
  919. throw;
  920. }
  921. if ((done || result == 0) && chunkStream.WantMore) {
  922. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
  923. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  924. }
  925. }
  926. } catch (Exception e) {
  927. HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
  928. }
  929. return result;
  930. }
  931. internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
  932. {
  933. err_msg = null;
  934. Stream s = null;
  935. lock (this) {
  936. if (Data.request != request)
  937. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  938. s = nstream;
  939. if (s == null)
  940. return false;
  941. }
  942. try {
  943. s.Write (buffer, offset, size);
  944. } catch (Exception e) {
  945. err_msg = e.Message;
  946. WebExceptionStatus wes = WebExceptionStatus.SendFailure;
  947. string msg = "Write: " + err_msg;
  948. if (e is WebException) {
  949. HandleError (wes, e, msg);
  950. return false;
  951. }
  952. HandleError (wes, e, msg);
  953. return false;
  954. }
  955. return true;
  956. }
  957. internal void Close (bool sendNext)
  958. {
  959. lock (this) {
  960. if (Data != null && Data.request != null && Data.request.ReuseConnection) {
  961. Data.request.ReuseConnection = false;
  962. return;
  963. }
  964. if (nstream != null) {
  965. try {
  966. nstream.Close ();
  967. } catch {}
  968. nstream = null;
  969. }
  970. if (socket != null) {
  971. try {
  972. socket.Close ();
  973. } catch {}
  974. socket = null;
  975. }
  976. if (ntlm_authenticated)
  977. ResetNtlm ();
  978. if (Data != null) {
  979. lock (Data) {
  980. Data.ReadState = ReadState.Aborted;
  981. }
  982. }
  983. state.SetIdle ();
  984. Data = new WebConnectionData ();
  985. if (sendNext)
  986. SendNext ();
  987. connect_request = null;
  988. connect_ntlm_auth_state = NtlmAuthState.None;
  989. }
  990. }
  991. void Abort (object sender, EventArgs args)
  992. {
  993. lock (this) {
  994. lock (queue) {
  995. HttpWebRequest req = (HttpWebRequest) sender;
  996. if (Data.request == req || Data.request == null) {
  997. if (!req.FinishedReading) {
  998. status = WebExceptionStatus.RequestCanceled;
  999. Close (false);
  1000. if (queue.Count > 0) {
  1001. Data.request = (HttpWebRequest) queue.Dequeue ();
  1002. SendRequest (Data.request);
  1003. }
  1004. }
  1005. return;
  1006. }
  1007. req.FinishedReading = true;
  1008. req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
  1009. if (queue.Count > 0 && queue.Peek () == sender) {
  1010. queue.Dequeue ();
  1011. } else if (queue.Count > 0) {
  1012. object [] old = queue.ToArray ();
  1013. queue.Clear ();
  1014. for (int i = old.Length - 1; i >= 0; i--) {
  1015. if (old [i] != sender)
  1016. queue.Enqueue (old [i]);
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. internal void ResetNtlm ()
  1023. {
  1024. ntlm_authenticated = false;
  1025. ntlm_credentials = null;
  1026. unsafe_sharing = false;
  1027. }
  1028. internal bool Connected {
  1029. get {
  1030. lock (this) {
  1031. return (socket != null && socket.Connected);
  1032. }
  1033. }
  1034. }
  1035. // -Used for NTLM authentication
  1036. internal HttpWebRequest PriorityRequest {
  1037. set { priority_request = value; }
  1038. }
  1039. internal bool NtlmAuthenticated {
  1040. get { return ntlm_authenticated; }
  1041. set { ntlm_authenticated = value; }
  1042. }
  1043. internal NetworkCredential NtlmCredential {
  1044. get { return ntlm_credentials; }
  1045. set { ntlm_credentials = value; }
  1046. }
  1047. internal bool UnsafeAuthenticatedConnectionSharing {
  1048. get { return unsafe_sharing; }
  1049. set { unsafe_sharing = value; }
  1050. }
  1051. // -
  1052. }
  1053. }