WebConnection.cs 32 KB

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